Skip to content

Ethereum Test Tools Package

Module containing tools for generating cross-client Ethereum execution layer tests.

CalldataCase dataclass

Small helper class to represent a single case whose condition depends on the value of the contract's calldata in a Switch case statement.

By default the calldata is read from position zero, but this can be overridden using position.

The condition is generated automatically based on the value (and optionally position) and may not be set directly.

Source code in src/ethereum_test_tools/code/generators.py
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
@dataclass
class CalldataCase:
    """
    Small helper class to represent a single case whose condition depends
    on the value of the contract's calldata in a Switch case statement.

    By default the calldata is read from position zero, but this can be
    overridden using `position`.

    The `condition` is generated automatically based on the `value` (and
    optionally `position`) and may not be set directly.
    """

    action: str | bytes | SupportsBytes
    value: int | str | bytes | SupportsBytes
    position: int = 0
    condition: bytes = field(init=False)

    def __post_init__(self):
        """
        Generate the condition base on `value` and `position`.
        """
        value_as_bytes = self.value
        if not isinstance(self.value, int):
            value_as_bytes = Op.PUSH32(to_bytes(self.value))
        self.condition = Op.EQ(Op.CALLDATALOAD(self.position), value_as_bytes)
        self.action = to_bytes(self.action)

__post_init__()

Generate the condition base on value and position.

Source code in src/ethereum_test_tools/code/generators.py
278
279
280
281
282
283
284
285
286
def __post_init__(self):
    """
    Generate the condition base on `value` and `position`.
    """
    value_as_bytes = self.value
    if not isinstance(self.value, int):
        value_as_bytes = Op.PUSH32(to_bytes(self.value))
    self.condition = Op.EQ(Op.CALLDATALOAD(self.position), value_as_bytes)
    self.action = to_bytes(self.action)

Case dataclass

Small helper class to represent a single, generic case in a Switch cases list.

Source code in src/ethereum_test_tools/code/generators.py
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
@dataclass
class Case:
    """
    Small helper class to represent a single, generic case in a `Switch` cases
    list.
    """

    condition: str | bytes | SupportsBytes
    action: str | bytes | SupportsBytes

    def __post_init__(self):
        """
        Ensure that the condition and action are of type bytes.
        """
        self.condition = to_bytes(self.condition)
        self.action = to_bytes(self.action)

__post_init__()

Ensure that the condition and action are of type bytes.

Source code in src/ethereum_test_tools/code/generators.py
252
253
254
255
256
257
def __post_init__(self):
    """
    Ensure that the condition and action are of type bytes.
    """
    self.condition = to_bytes(self.condition)
    self.action = to_bytes(self.action)

Code

Bases: SupportsBytes, Sized

Generic code object.

Source code in src/ethereum_test_tools/code/code.py
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
class Code(SupportsBytes, Sized):
    """
    Generic code object.
    """

    bytecode: Optional[bytes] = None
    """
    bytes array that represents the bytecode of this object.
    """
    name: Optional[str] = None
    """
    Name used to describe this code.
    Usually used to add extra information to a test case.
    """

    def __init__(
        self,
        code: Optional[str | bytes | SupportsBytes] = None,
        *,
        name: Optional[str] = None,
    ):
        """
        Create a new Code object.
        """
        if code is not None:
            self.bytecode = to_bytes(code)
        self.name = name

    def __bytes__(self) -> bytes:
        """
        Transform the Code object into bytes.
        """
        if self.bytecode is None:
            return bytes()
        else:
            return self.bytecode

    def __len__(self) -> int:
        """
        Get the length of the Code object.
        """
        if self.bytecode is None:
            return 0
        else:
            return len(self.bytecode)

    def __add__(self, other: str | bytes | SupportsBytes) -> "Code":
        """
        Adds two code objects together, by converting both to bytes first.
        """
        return Code(to_bytes(self) + to_bytes(other))

    def __radd__(self, other: str | bytes | SupportsBytes) -> "Code":
        """
        Adds two code objects together, by converting both to bytes first.
        """
        return Code(to_bytes(other) + to_bytes(self))

bytecode: Optional[bytes] = None class-attribute instance-attribute

bytes array that represents the bytecode of this object.

name: Optional[str] = name class-attribute instance-attribute

Name used to describe this code. Usually used to add extra information to a test case.

__init__(code=None, *, name=None)

Create a new Code object.

Source code in src/ethereum_test_tools/code/code.py
25
26
27
28
29
30
31
32
33
34
35
36
def __init__(
    self,
    code: Optional[str | bytes | SupportsBytes] = None,
    *,
    name: Optional[str] = None,
):
    """
    Create a new Code object.
    """
    if code is not None:
        self.bytecode = to_bytes(code)
    self.name = name

__bytes__()

Transform the Code object into bytes.

Source code in src/ethereum_test_tools/code/code.py
38
39
40
41
42
43
44
45
def __bytes__(self) -> bytes:
    """
    Transform the Code object into bytes.
    """
    if self.bytecode is None:
        return bytes()
    else:
        return self.bytecode

__len__()

Get the length of the Code object.

Source code in src/ethereum_test_tools/code/code.py
47
48
49
50
51
52
53
54
def __len__(self) -> int:
    """
    Get the length of the Code object.
    """
    if self.bytecode is None:
        return 0
    else:
        return len(self.bytecode)

__add__(other)

Adds two code objects together, by converting both to bytes first.

Source code in src/ethereum_test_tools/code/code.py
56
57
58
59
60
def __add__(self, other: str | bytes | SupportsBytes) -> "Code":
    """
    Adds two code objects together, by converting both to bytes first.
    """
    return Code(to_bytes(self) + to_bytes(other))

__radd__(other)

Adds two code objects together, by converting both to bytes first.

Source code in src/ethereum_test_tools/code/code.py
62
63
64
65
66
def __radd__(self, other: str | bytes | SupportsBytes) -> "Code":
    """
    Adds two code objects together, by converting both to bytes first.
    """
    return Code(to_bytes(other) + to_bytes(self))

CodeGasMeasure dataclass

Bases: Code

Helper class used to generate bytecode that measures gas usage of a bytecode, taking into account and subtracting any extra overhead gas costs required to execute. By default, the result gas calculation is saved to storage key 0.

Source code in src/ethereum_test_tools/code/generators.py
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
@dataclass(kw_only=True)
class CodeGasMeasure(Code):
    """
    Helper class used to generate bytecode that measures gas usage of a
    bytecode, taking into account and subtracting any extra overhead gas costs
    required to execute.
    By default, the result gas calculation is saved to storage key 0.
    """

    code: str | bytes | SupportsBytes
    """
    Bytecode to be executed to measure the gas usage.
    """
    overhead_cost: int = 0
    """
    Extra gas cost to be subtracted from extra operations.
    """
    extra_stack_items: int = 0
    """
    Extra stack items that remain at the end of the execution.
    To be considered when subtracting the value of the previous GAS operation,
    and to be popped at the end of the execution.
    """
    sstore_key: int = 0
    """
    Storage key to save the gas used.
    """

    def __post_init__(self):
        """
        Assemble the bytecode that measures gas usage.
        """
        res = bytes()
        res += bytes(
            [
                0x5A,  # GAS
            ]
        )
        res += to_bytes(self.code)  # Execute code to measure its gas cost
        res += bytes(
            [
                0x5A,  # GAS
            ]
        )
        # We need to swap and pop for each extra stack item that remained from
        # the execution of the code
        res += (
            bytes(
                [
                    0x90,  # SWAP1
                    0x50,  # POP
                ]
            )
            * self.extra_stack_items
        )
        res += bytes(
            [
                0x90,  # SWAP1
                0x03,  # SUB
                0x60,  # PUSH1
                self.overhead_cost + 2,  # Overhead cost + GAS opcode price
                0x90,  # SWAP1
                0x03,  # SUB
                0x60,  # PUSH1
                self.sstore_key,  # -> SSTORE key
                0x55,  # SSTORE
                0x00,  # STOP
            ]
        )
        self.bytecode = res

code: str | bytes | SupportsBytes instance-attribute

Bytecode to be executed to measure the gas usage.

overhead_cost: int = 0 class-attribute instance-attribute

Extra gas cost to be subtracted from extra operations.

extra_stack_items: int = 0 class-attribute instance-attribute

Extra stack items that remain at the end of the execution. To be considered when subtracting the value of the previous GAS operation, and to be popped at the end of the execution.

sstore_key: int = 0 class-attribute instance-attribute

Storage key to save the gas used.

__post_init__()

Assemble the bytecode that measures gas usage.

Source code in src/ethereum_test_tools/code/generators.py
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
def __post_init__(self):
    """
    Assemble the bytecode that measures gas usage.
    """
    res = bytes()
    res += bytes(
        [
            0x5A,  # GAS
        ]
    )
    res += to_bytes(self.code)  # Execute code to measure its gas cost
    res += bytes(
        [
            0x5A,  # GAS
        ]
    )
    # We need to swap and pop for each extra stack item that remained from
    # the execution of the code
    res += (
        bytes(
            [
                0x90,  # SWAP1
                0x50,  # POP
            ]
        )
        * self.extra_stack_items
    )
    res += bytes(
        [
            0x90,  # SWAP1
            0x03,  # SUB
            0x60,  # PUSH1
            self.overhead_cost + 2,  # Overhead cost + GAS opcode price
            0x90,  # SWAP1
            0x03,  # SUB
            0x60,  # PUSH1
            self.sstore_key,  # -> SSTORE key
            0x55,  # SSTORE
            0x00,  # STOP
        ]
    )
    self.bytecode = res

Conditional dataclass

Bases: Code

Helper class used to generate conditional bytecode.

Source code in src/ethereum_test_tools/code/generators.py
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
@dataclass(kw_only=True)
class Conditional(Code):
    """
    Helper class used to generate conditional bytecode.
    """

    condition: str | bytes | SupportsBytes
    """
    Condition bytecode which must return the true or false condition of the conditional statement.
    """

    if_true: str | bytes | SupportsBytes
    """
    Bytecode to execute if the condition is true.
    """

    if_false: str | bytes | SupportsBytes
    """
    Bytecode to execute if the condition is false.
    """

    def __post_init__(self):
        """
        Assemble the conditional bytecode by generating the necessary jump and
        jumpdest opcodes surrounding the condition and the two possible execution
        paths.

        In the future, PC usage should be replaced by using RJUMP and RJUMPI
        """
        condition_bytes = to_bytes(self.condition)
        if_true_bytes = to_bytes(self.if_true)
        if_false_bytes = to_bytes(self.if_false)

        # First we append a jumpdest to the start of the true branch
        if_true_bytes = Op.JUMPDEST + if_true_bytes

        # Then we append the unconditional jump to the end of the false branch, used to skip the
        # true branch
        if_false_bytes += Op.JUMP(Op.ADD(Op.PC, len(if_true_bytes) + 3))

        # Then we need to do the conditional jump by skipping the false branch
        condition_bytes = Op.JUMPI(Op.ADD(Op.PC, len(if_false_bytes) + 3), condition_bytes)

        # Finally we append the true and false branches, and the condition, plus the jumpdest at
        # the very end
        self.bytecode = condition_bytes + if_false_bytes + if_true_bytes + Op.JUMPDEST

condition: str | bytes | SupportsBytes instance-attribute

Condition bytecode which must return the true or false condition of the conditional statement.

if_true: str | bytes | SupportsBytes instance-attribute

Bytecode to execute if the condition is true.

if_false: str | bytes | SupportsBytes instance-attribute

Bytecode to execute if the condition is false.

__post_init__()

Assemble the conditional bytecode by generating the necessary jump and jumpdest opcodes surrounding the condition and the two possible execution paths.

In the future, PC usage should be replaced by using RJUMP and RJUMPI

Source code in src/ethereum_test_tools/code/generators.py
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
def __post_init__(self):
    """
    Assemble the conditional bytecode by generating the necessary jump and
    jumpdest opcodes surrounding the condition and the two possible execution
    paths.

    In the future, PC usage should be replaced by using RJUMP and RJUMPI
    """
    condition_bytes = to_bytes(self.condition)
    if_true_bytes = to_bytes(self.if_true)
    if_false_bytes = to_bytes(self.if_false)

    # First we append a jumpdest to the start of the true branch
    if_true_bytes = Op.JUMPDEST + if_true_bytes

    # Then we append the unconditional jump to the end of the false branch, used to skip the
    # true branch
    if_false_bytes += Op.JUMP(Op.ADD(Op.PC, len(if_true_bytes) + 3))

    # Then we need to do the conditional jump by skipping the false branch
    condition_bytes = Op.JUMPI(Op.ADD(Op.PC, len(if_false_bytes) + 3), condition_bytes)

    # Finally we append the true and false branches, and the condition, plus the jumpdest at
    # the very end
    self.bytecode = condition_bytes + if_false_bytes + if_true_bytes + Op.JUMPDEST

Initcode

Bases: Code

Helper class used to generate initcode for the specified deployment code.

The execution gas cost of the initcode is calculated, and also the deployment gas costs for the deployed code.

The initcode can be padded to a certain length if necessary, which does not affect the deployed code.

Other costs such as the CREATE2 hashing costs or the initcode_word_cost of EIP-3860 are not taken into account by any of these calculated costs.

Source code in src/ethereum_test_tools/code/generators.py
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
class Initcode(Code):
    """
    Helper class used to generate initcode for the specified deployment code.

    The execution gas cost of the initcode is calculated, and also the
    deployment gas costs for the deployed code.

    The initcode can be padded to a certain length if necessary, which
    does not affect the deployed code.

    Other costs such as the CREATE2 hashing costs or the initcode_word_cost
    of EIP-3860 are *not* taken into account by any of these calculated
    costs.
    """

    deploy_code: str | bytes | SupportsBytes
    """
    Bytecode to be deployed by the initcode.
    """
    execution_gas: int
    """
    Gas cost of executing the initcode, without considering deployment gas
    costs.
    """
    deployment_gas: int
    """
    Gas cost of deploying the cost, subtracted after initcode execution,
    """

    def __init__(
        self,
        *,
        deploy_code: str | bytes | SupportsBytes,
        initcode_length: Optional[int] = None,
        initcode_prefix: str | bytes | SupportsBytes = b"",
        initcode_prefix_execution_gas: int = 0,
        padding_byte: int = 0x00,
        name: Optional[str] = None,
    ):
        """
        Generate legacy initcode that inits a contract with the specified code.
        The initcode can be padded to a specified length for testing purposes.
        """
        self.execution_gas = initcode_prefix_execution_gas
        self.deploy_code = deploy_code
        deploy_code_bytes = to_bytes(self.deploy_code)
        code_length = len(deploy_code_bytes)

        initcode_prefix_bytes = to_bytes(initcode_prefix)
        initcode = bytearray(initcode_prefix_bytes)

        # PUSH2: length=<bytecode length>
        initcode.append(0x61)
        initcode += code_length.to_bytes(length=2, byteorder="big")
        self.execution_gas += 3

        # PUSH1: offset=0
        initcode.append(0x60)
        initcode.append(0x00)
        self.execution_gas += 3

        # DUP2
        initcode.append(0x81)
        self.execution_gas += 3

        # PUSH1: initcode_length=11 + len(initcode_prefix_bytes) (constant)
        no_prefix_length = 0x0B
        assert no_prefix_length + len(initcode_prefix_bytes) <= 0xFF, "initcode prefix too long"
        initcode.append(0x60)
        initcode.append(no_prefix_length + len(initcode_prefix_bytes))
        self.execution_gas += 3

        # DUP3
        initcode.append(0x82)
        self.execution_gas += 3

        # CODECOPY: destinationOffset=0, offset=0, length
        initcode.append(0x39)
        self.execution_gas += (
            3
            + (3 * ceiling_division(code_length, 32))
            + (3 * code_length)
            + ((code_length * code_length) // 512)
        )

        # RETURN: offset=0, length
        initcode.append(0xF3)
        self.execution_gas += 0

        initcode_plus_deploy_code = bytes(initcode) + deploy_code_bytes
        padding_bytes = bytes()

        if initcode_length is not None:
            assert initcode_length >= len(
                initcode_plus_deploy_code
            ), "specified invalid length for initcode"

            padding_bytes = bytes(
                [padding_byte] * (initcode_length - len(initcode_plus_deploy_code))
            )

        self.deployment_gas = GAS_PER_DEPLOYED_CODE_BYTE * len(deploy_code_bytes)

        super().__init__(initcode_plus_deploy_code + padding_bytes, name=name)

deploy_code: str | bytes | SupportsBytes = deploy_code instance-attribute

Bytecode to be deployed by the initcode.

execution_gas: int = initcode_prefix_execution_gas instance-attribute

Gas cost of executing the initcode, without considering deployment gas costs.

deployment_gas: int = GAS_PER_DEPLOYED_CODE_BYTE * len(deploy_code_bytes) instance-attribute

Gas cost of deploying the cost, subtracted after initcode execution,

__init__(*, deploy_code, initcode_length=None, initcode_prefix=b'', initcode_prefix_execution_gas=0, padding_byte=0, name=None)

Generate legacy initcode that inits a contract with the specified code. The initcode can be padded to a specified length for testing purposes.

Source code in src/ethereum_test_tools/code/generators.py
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
def __init__(
    self,
    *,
    deploy_code: str | bytes | SupportsBytes,
    initcode_length: Optional[int] = None,
    initcode_prefix: str | bytes | SupportsBytes = b"",
    initcode_prefix_execution_gas: int = 0,
    padding_byte: int = 0x00,
    name: Optional[str] = None,
):
    """
    Generate legacy initcode that inits a contract with the specified code.
    The initcode can be padded to a specified length for testing purposes.
    """
    self.execution_gas = initcode_prefix_execution_gas
    self.deploy_code = deploy_code
    deploy_code_bytes = to_bytes(self.deploy_code)
    code_length = len(deploy_code_bytes)

    initcode_prefix_bytes = to_bytes(initcode_prefix)
    initcode = bytearray(initcode_prefix_bytes)

    # PUSH2: length=<bytecode length>
    initcode.append(0x61)
    initcode += code_length.to_bytes(length=2, byteorder="big")
    self.execution_gas += 3

    # PUSH1: offset=0
    initcode.append(0x60)
    initcode.append(0x00)
    self.execution_gas += 3

    # DUP2
    initcode.append(0x81)
    self.execution_gas += 3

    # PUSH1: initcode_length=11 + len(initcode_prefix_bytes) (constant)
    no_prefix_length = 0x0B
    assert no_prefix_length + len(initcode_prefix_bytes) <= 0xFF, "initcode prefix too long"
    initcode.append(0x60)
    initcode.append(no_prefix_length + len(initcode_prefix_bytes))
    self.execution_gas += 3

    # DUP3
    initcode.append(0x82)
    self.execution_gas += 3

    # CODECOPY: destinationOffset=0, offset=0, length
    initcode.append(0x39)
    self.execution_gas += (
        3
        + (3 * ceiling_division(code_length, 32))
        + (3 * code_length)
        + ((code_length * code_length) // 512)
    )

    # RETURN: offset=0, length
    initcode.append(0xF3)
    self.execution_gas += 0

    initcode_plus_deploy_code = bytes(initcode) + deploy_code_bytes
    padding_bytes = bytes()

    if initcode_length is not None:
        assert initcode_length >= len(
            initcode_plus_deploy_code
        ), "specified invalid length for initcode"

        padding_bytes = bytes(
            [padding_byte] * (initcode_length - len(initcode_plus_deploy_code))
        )

    self.deployment_gas = GAS_PER_DEPLOYED_CODE_BYTE * len(deploy_code_bytes)

    super().__init__(initcode_plus_deploy_code + padding_bytes, name=name)

Switch dataclass

Bases: Code

Helper class used to generate switch-case expressions in EVM bytecode.

Switch-case behavior
  • If no condition is met in the list of BytecodeCases conditions, the default_action bytecode is executed.
  • If multiple conditions are met, the action from the first valid condition is the only one executed.
  • There is no fall through; it is not possible to execute multiple actions.
Source code in src/ethereum_test_tools/code/generators.py
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
@dataclass(kw_only=True)
class Switch(Code):
    """
    Helper class used to generate switch-case expressions in EVM bytecode.

    Switch-case behavior:
        - If no condition is met in the list of BytecodeCases conditions,
            the `default_action` bytecode is executed.
        - If multiple conditions are met, the action from the first valid
            condition is the only one executed.
        - There is no fall through; it is not possible to execute multiple
            actions.
    """

    default_action: str | bytes | SupportsBytes
    """
    The default bytecode to execute; if no condition is met, this bytecode is
    executed.
    """

    cases: List[Case | CalldataCase]
    """
    A list of Case or CalldataCase: The first element with a condition that
    evaluates to a non-zero value is the one that is executed.
    """

    def __post_init__(self):
        """
        Assemble the bytecode by looping over the list of cases and adding
        the necessary JUMPI and JUMPDEST opcodes in order to replicate
        switch-case behavior.

        In the future, PC usage should be replaced by using RJUMP and RJUMPI.
        """
        # The length required to jump over subsequent actions to the final JUMPDEST at the end
        # of the switch-case block:
        # - add 6 per case for the length of the JUMPDEST and JUMP(ADD(PC, action_jump_length))
        #   bytecode
        # - add 3 to the total to account for this action's JUMP; the PC within the call
        #   requires a "correction" of 3.
        action_jump_length = sum(len(case.action) + 6 for case in self.cases) + 3

        # All conditions get pre-pended to this bytecode; if none are met, we reach the default
        self.bytecode = to_bytes(self.default_action) + Op.JUMP(Op.ADD(Op.PC, action_jump_length))

        # The length required to jump over the default action and its JUMP bytecode
        condition_jump_length = len(self.bytecode) + 3

        # Reversed: first case in the list has priority; it will become the outer-most onion layer.
        # We build up layers around the default_action, after 1 iteration of the loop, a simplified
        # representation of the bytecode is:
        #
        #  JUMPI(case[n-1].condition)
        #  + default_action + JUMP()
        #  + JUMPDEST + case[n-1].action + JUMP()
        #
        # and after n=len(cases) iterations:
        #
        #  JUMPI(case[0].condition)
        #  + JUMPI(case[1].condition)
        #    ...
        #  + JUMPI(case[n-1].condition)
        #  + default_action + JUMP()
        #  + JUMPDEST + case[n-1].action + JUMP()
        #  + ...
        #  + JUMPDEST + case[1].action + JUMP()
        #  + JUMPDEST + case[0].action + JUMP()
        #
        for case in reversed(self.cases):
            action_jump_length -= len(case.action) + 6
            action = Op.JUMPDEST + case.action + Op.JUMP(Op.ADD(Op.PC, action_jump_length))
            condition = Op.JUMPI(Op.ADD(Op.PC, condition_jump_length), case.condition)
            # wrap the current case around the onion as its next layer
            self.bytecode = condition + self.bytecode + action
            condition_jump_length += len(condition) + len(action)

        self.bytecode += Op.JUMPDEST

default_action: str | bytes | SupportsBytes instance-attribute

The default bytecode to execute; if no condition is met, this bytecode is executed.

cases: List[Case | CalldataCase] instance-attribute

A list of Case or CalldataCase: The first element with a condition that evaluates to a non-zero value is the one that is executed.

__post_init__()

Assemble the bytecode by looping over the list of cases and adding the necessary JUMPI and JUMPDEST opcodes in order to replicate switch-case behavior.

In the future, PC usage should be replaced by using RJUMP and RJUMPI.

Source code in src/ethereum_test_tools/code/generators.py
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
def __post_init__(self):
    """
    Assemble the bytecode by looping over the list of cases and adding
    the necessary JUMPI and JUMPDEST opcodes in order to replicate
    switch-case behavior.

    In the future, PC usage should be replaced by using RJUMP and RJUMPI.
    """
    # The length required to jump over subsequent actions to the final JUMPDEST at the end
    # of the switch-case block:
    # - add 6 per case for the length of the JUMPDEST and JUMP(ADD(PC, action_jump_length))
    #   bytecode
    # - add 3 to the total to account for this action's JUMP; the PC within the call
    #   requires a "correction" of 3.
    action_jump_length = sum(len(case.action) + 6 for case in self.cases) + 3

    # All conditions get pre-pended to this bytecode; if none are met, we reach the default
    self.bytecode = to_bytes(self.default_action) + Op.JUMP(Op.ADD(Op.PC, action_jump_length))

    # The length required to jump over the default action and its JUMP bytecode
    condition_jump_length = len(self.bytecode) + 3

    # Reversed: first case in the list has priority; it will become the outer-most onion layer.
    # We build up layers around the default_action, after 1 iteration of the loop, a simplified
    # representation of the bytecode is:
    #
    #  JUMPI(case[n-1].condition)
    #  + default_action + JUMP()
    #  + JUMPDEST + case[n-1].action + JUMP()
    #
    # and after n=len(cases) iterations:
    #
    #  JUMPI(case[0].condition)
    #  + JUMPI(case[1].condition)
    #    ...
    #  + JUMPI(case[n-1].condition)
    #  + default_action + JUMP()
    #  + JUMPDEST + case[n-1].action + JUMP()
    #  + ...
    #  + JUMPDEST + case[1].action + JUMP()
    #  + JUMPDEST + case[0].action + JUMP()
    #
    for case in reversed(self.cases):
        action_jump_length -= len(case.action) + 6
        action = Op.JUMPDEST + case.action + Op.JUMP(Op.ADD(Op.PC, action_jump_length))
        condition = Op.JUMPI(Op.ADD(Op.PC, condition_jump_length), case.condition)
        # wrap the current case around the onion as its next layer
        self.bytecode = condition + self.bytecode + action
        condition_jump_length += len(condition) + len(action)

    self.bytecode += Op.JUMPDEST

Yul

Bases: SupportsBytes, Sized

Yul compiler. Compiles Yul source code into bytecode.

Source code in src/ethereum_test_tools/code/yul.py
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
class Yul(SupportsBytes, Sized):
    """
    Yul compiler.
    Compiles Yul source code into bytecode.
    """

    source: str
    compiled: Optional[bytes] = None

    def __init__(
        self,
        source: str,
        fork: Optional[Fork] = None,
        binary: Optional[Path | str] = None,
    ):
        self.source = source
        self.evm_version = get_evm_version_from_fork(fork)
        if binary is None:
            which_path = which("solc")
            if which_path is not None:
                binary = Path(which_path)
        if binary is None or not Path(binary).exists():
            raise Exception(
                """`solc` binary executable not found, please refer to
                https://docs.soliditylang.org/en/latest/installing-solidity.html
                for help downloading and installing `solc`"""
            )
        self.binary = Path(binary)

    def __bytes__(self) -> bytes:
        """
        Assembles using `solc --assemble`.
        """
        if not self.compiled:
            solc_args: Tuple[Union[Path, str], ...] = ()
            if self.evm_version:
                solc_args = (
                    self.binary,
                    "--evm-version",
                    self.evm_version,
                    *DEFAULT_SOLC_ARGS,
                )
            else:
                solc_args = (self.binary, *DEFAULT_SOLC_ARGS)
            result = run(
                solc_args,
                input=str.encode(self.source),
                stdout=PIPE,
                stderr=PIPE,
            )

            if result.returncode != 0:
                stderr_lines = result.stderr.decode().split("\n")
                stderr_message = "\n".join(line.strip() for line in stderr_lines)
                raise Exception(f"failed to compile yul source:\n{stderr_message[7:]}")

            lines = result.stdout.decode().split("\n")

            hex_str = lines[lines.index("Binary representation:") + 1]

            self.compiled = bytes.fromhex(hex_str)
        return self.compiled

    def __len__(self) -> int:
        """
        Get the length of the Yul bytecode.
        """
        return len(bytes(self))

    def __add__(self, other: str | bytes | SupportsBytes) -> Code:
        """
        Adds two code objects together, by converting both to bytes first.
        """
        return Code(bytes(self) + to_bytes(other))

    def __radd__(self, other: str | bytes | SupportsBytes) -> Code:
        """
        Adds two code objects together, by converting both to bytes first.
        """
        return Code(to_bytes(other) + bytes(self))

    def version(self) -> Version:
        """
        Return solc's version string
        """
        result = run(
            [self.binary, "--version"],
            stdout=PIPE,
            stderr=PIPE,
        )
        solc_output = result.stdout.decode().split("\n")
        version_pattern = r"Version: (.*)"
        solc_version_string = ""
        for line in solc_output:
            if match := re.search(version_pattern, line):
                solc_version_string = match.group(1)
                break
        if not solc_version_string:
            warnings.warn("Unable to determine solc version.")
            return Version(0)
        # Sanitize
        solc_version_string = solc_version_string.replace("g++", "gpp")
        return Version.parse(solc_version_string)

__bytes__()

Assembles using solc --assemble.

Source code in src/ethereum_test_tools/code/yul.py
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
def __bytes__(self) -> bytes:
    """
    Assembles using `solc --assemble`.
    """
    if not self.compiled:
        solc_args: Tuple[Union[Path, str], ...] = ()
        if self.evm_version:
            solc_args = (
                self.binary,
                "--evm-version",
                self.evm_version,
                *DEFAULT_SOLC_ARGS,
            )
        else:
            solc_args = (self.binary, *DEFAULT_SOLC_ARGS)
        result = run(
            solc_args,
            input=str.encode(self.source),
            stdout=PIPE,
            stderr=PIPE,
        )

        if result.returncode != 0:
            stderr_lines = result.stderr.decode().split("\n")
            stderr_message = "\n".join(line.strip() for line in stderr_lines)
            raise Exception(f"failed to compile yul source:\n{stderr_message[7:]}")

        lines = result.stdout.decode().split("\n")

        hex_str = lines[lines.index("Binary representation:") + 1]

        self.compiled = bytes.fromhex(hex_str)
    return self.compiled

__len__()

Get the length of the Yul bytecode.

Source code in src/ethereum_test_tools/code/yul.py
102
103
104
105
106
def __len__(self) -> int:
    """
    Get the length of the Yul bytecode.
    """
    return len(bytes(self))

__add__(other)

Adds two code objects together, by converting both to bytes first.

Source code in src/ethereum_test_tools/code/yul.py
108
109
110
111
112
def __add__(self, other: str | bytes | SupportsBytes) -> Code:
    """
    Adds two code objects together, by converting both to bytes first.
    """
    return Code(bytes(self) + to_bytes(other))

__radd__(other)

Adds two code objects together, by converting both to bytes first.

Source code in src/ethereum_test_tools/code/yul.py
114
115
116
117
118
def __radd__(self, other: str | bytes | SupportsBytes) -> Code:
    """
    Adds two code objects together, by converting both to bytes first.
    """
    return Code(to_bytes(other) + bytes(self))

version()

Return solc's version string

Source code in src/ethereum_test_tools/code/yul.py
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
def version(self) -> Version:
    """
    Return solc's version string
    """
    result = run(
        [self.binary, "--version"],
        stdout=PIPE,
        stderr=PIPE,
    )
    solc_output = result.stdout.decode().split("\n")
    version_pattern = r"Version: (.*)"
    solc_version_string = ""
    for line in solc_output:
        if match := re.search(version_pattern, line):
            solc_version_string = match.group(1)
            break
    if not solc_version_string:
        warnings.warn("Unable to determine solc version.")
        return Version(0)
    # Sanitize
    solc_version_string = solc_version_string.replace("g++", "gpp")
    return Version.parse(solc_version_string)

AccessList dataclass

Access List for transactions.

Source code in src/ethereum_test_tools/common/types.py
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
@dataclass(kw_only=True)
class AccessList:
    """
    Access List for transactions.
    """

    address: FixedSizeBytesConvertible = field(
        json_encoder=JSONEncoder.Field(
            cast_type=Address,
        ),
    )
    storage_keys: List[FixedSizeBytesConvertible] = field(
        default_factory=list,
        json_encoder=JSONEncoder.Field(
            name="storageKeys",
            cast_type=lambda x: [str(Hash(k)) for k in x],
            skip_string_convert=True,
        ),
    )

    def to_list(self) -> List[bytes | List[bytes]]:
        """
        Returns the access list as a list of serializable elements.
        """
        return [Address(self.address), [Hash(k) for k in self.storage_keys]]

to_list()

Returns the access list as a list of serializable elements.

Source code in src/ethereum_test_tools/common/types.py
952
953
954
955
956
def to_list(self) -> List[bytes | List[bytes]]:
    """
    Returns the access list as a list of serializable elements.
    """
    return [Address(self.address), [Hash(k) for k in self.storage_keys]]

Account dataclass

State associated with an address.

Source code in src/ethereum_test_tools/common/types.py
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
@dataclass(kw_only=True)
class Account:
    """
    State associated with an address.
    """

    nonce: Optional[NumberConvertible] = field(
        default=None,
        json_encoder=JSONEncoder.Field(
            name="nonce",
            cast_type=ZeroPaddedHexNumber,
            default_value=0,
        ),
    )
    """
    The scalar value equal to a) the number of transactions sent by
    an Externally Owned Account, b) the amount of contracts created by a
    contract.
    """
    balance: Optional[NumberConvertible] = field(
        default=None,
        json_encoder=JSONEncoder.Field(
            name="balance",
            cast_type=ZeroPaddedHexNumber,
            default_value=0,
        ),
    )
    """
    The amount of Wei (10<sup>-18</sup> Eth) the account has.
    """
    code: Optional[BytesConvertible] = field(
        default=None,
        json_encoder=JSONEncoder.Field(
            name="code",
            cast_type=Bytes,
            default_value=bytes(),
        ),
    )
    """
    Bytecode contained by the account.
    """
    storage: Optional[Storage | Storage.StorageDictType] = field(
        default=None,
        json_encoder=JSONEncoder.Field(
            name="storage",
            cast_type=Storage,
            to_json=True,
            default_value={},
        ),
    )
    """
    Storage within a contract.
    """

    NONEXISTENT: ClassVar[object] = object()
    """
    Sentinel object used to specify when an account should not exist in the
    state.
    """

    @dataclass(kw_only=True)
    class NonceMismatch(Exception):
        """
        Test expected a certain nonce value for an account but a different
        value was found.
        """

        address: Address
        want: int | None
        got: int | None

        def __init__(self, address: Address, want: int | None, got: int | None, *args):
            super().__init__(args)
            self.address = address
            self.want = want
            self.got = got

        def __str__(self):
            """Print exception string"""
            return (
                f"unexpected nonce for account {self.address}: "
                + f"want {self.want}, got {self.got}"
            )

    @dataclass(kw_only=True)
    class BalanceMismatch(Exception):
        """
        Test expected a certain balance for an account but a different
        value was found.
        """

        address: Address
        want: int | None
        got: int | None

        def __init__(self, address: Address, want: int | None, got: int | None, *args):
            super().__init__(args)
            self.address = address
            self.want = want
            self.got = got

        def __str__(self):
            """Print exception string"""
            return (
                f"unexpected balance for account {self.address}: "
                + f"want {self.want}, got {self.got}"
            )

    @dataclass(kw_only=True)
    class CodeMismatch(Exception):
        """
        Test expected a certain bytecode for an account but a different
        one was found.
        """

        address: Address
        want: str | None
        got: str | None

        def __init__(self, address: Address, want: str | None, got: str | None, *args):
            super().__init__(args)
            self.address = address
            self.want = want
            self.got = got

        def __str__(self):
            """Print exception string"""
            return (
                f"unexpected code for account {self.address}: "
                + f"want {self.want}, got {self.got}"
            )

    def check_alloc(self: "Account", address: Address, alloc: dict):
        """
        Checks the returned alloc against an expected account in post state.
        Raises exception on failure.
        """
        if self.nonce is not None:
            actual_nonce = int_or_none(alloc.get("nonce"), 0)
            nonce = int(Number(self.nonce))
            if nonce != actual_nonce:
                raise Account.NonceMismatch(
                    address=address,
                    want=nonce,
                    got=actual_nonce,
                )

        if self.balance is not None:
            actual_balance = int_or_none(alloc.get("balance"), 0)
            balance = int(Number(self.balance))
            if balance != actual_balance:
                raise Account.BalanceMismatch(
                    address=address,
                    want=balance,
                    got=actual_balance,
                )

        if self.code is not None:
            expected_code = Bytes(self.code).hex()
            actual_code = str_or_none(alloc.get("code"), "0x")
            if expected_code != actual_code:
                raise Account.CodeMismatch(
                    address=address,
                    want=expected_code,
                    got=actual_code,
                )

        if self.storage is not None:
            expected_storage = (
                self.storage if isinstance(self.storage, Storage) else Storage(self.storage)
            )
            actual_storage = Storage(alloc["storage"]) if "storage" in alloc else Storage({})
            expected_storage.must_be_equal(address=address, other=actual_storage)

    def has_empty_code(self: "Account") -> bool:
        """
        Returns true if an account has no bytecode.
        """
        return not self.code or Bytes(self.code) == b""

    def is_empty(self: "Account") -> bool:
        """
        Returns true if an account deemed empty.
        """
        return (
            (self.nonce == 0 or self.nonce is None)
            and (self.balance == 0 or self.balance is None)
            and self.has_empty_code()
            and (not self.storage or self.storage == {} or self.storage is None)
        )

    @classmethod
    def from_dict(cls: Type, data: "Dict | Account") -> "Account":
        """
        Create account from dictionary.
        """
        if isinstance(data, cls):
            return data
        return cls(**data)

    @classmethod
    def with_code(cls: Type, code: BytesConvertible) -> "Account":
        """
        Create account with provided `code` and nonce of `1`.
        """
        return Account(nonce=1, code=code)

    @classmethod
    def merge(
        cls: Type, account_1: "Dict | Account | None", account_2: "Dict | Account | None"
    ) -> "Account":
        """
        Create a merged account from two sources.
        """

        def to_kwargs_dict(account: "Dict | Account | None") -> Dict:
            if account is None:
                return {}
            if isinstance(account, dict):
                return account
            elif isinstance(account, cls):
                return {
                    f.name: v for f in fields(cls) if (v := getattr(account, f.name)) is not None
                }
            raise TypeError(f"Unexpected type for account merge: {type(account)}")

        kwargs = to_kwargs_dict(account_1)
        kwargs.update(to_kwargs_dict(account_2))

        return cls(**kwargs)

nonce: Optional[NumberConvertible] = field(default=None, json_encoder=JSONEncoder.Field(name='nonce', cast_type=ZeroPaddedHexNumber, default_value=0)) class-attribute instance-attribute

The scalar value equal to a) the number of transactions sent by an Externally Owned Account, b) the amount of contracts created by a contract.

balance: Optional[NumberConvertible] = field(default=None, json_encoder=JSONEncoder.Field(name='balance', cast_type=ZeroPaddedHexNumber, default_value=0)) class-attribute instance-attribute

The amount of Wei (10-18 Eth) the account has.

code: Optional[BytesConvertible] = field(default=None, json_encoder=JSONEncoder.Field(name='code', cast_type=Bytes, default_value=bytes())) class-attribute instance-attribute

Bytecode contained by the account.

storage: Optional[Storage | Storage.StorageDictType] = field(default=None, json_encoder=JSONEncoder.Field(name='storage', cast_type=Storage, to_json=True, default_value={})) class-attribute instance-attribute

Storage within a contract.

NONEXISTENT: object = object() class-attribute

Sentinel object used to specify when an account should not exist in the state.

NonceMismatch dataclass

Bases: Exception

Test expected a certain nonce value for an account but a different value was found.

Source code in src/ethereum_test_tools/common/types.py
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
@dataclass(kw_only=True)
class NonceMismatch(Exception):
    """
    Test expected a certain nonce value for an account but a different
    value was found.
    """

    address: Address
    want: int | None
    got: int | None

    def __init__(self, address: Address, want: int | None, got: int | None, *args):
        super().__init__(args)
        self.address = address
        self.want = want
        self.got = got

    def __str__(self):
        """Print exception string"""
        return (
            f"unexpected nonce for account {self.address}: "
            + f"want {self.want}, got {self.got}"
        )

__str__()

Print exception string

Source code in src/ethereum_test_tools/common/types.py
416
417
418
419
420
421
def __str__(self):
    """Print exception string"""
    return (
        f"unexpected nonce for account {self.address}: "
        + f"want {self.want}, got {self.got}"
    )

BalanceMismatch dataclass

Bases: Exception

Test expected a certain balance for an account but a different value was found.

Source code in src/ethereum_test_tools/common/types.py
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
@dataclass(kw_only=True)
class BalanceMismatch(Exception):
    """
    Test expected a certain balance for an account but a different
    value was found.
    """

    address: Address
    want: int | None
    got: int | None

    def __init__(self, address: Address, want: int | None, got: int | None, *args):
        super().__init__(args)
        self.address = address
        self.want = want
        self.got = got

    def __str__(self):
        """Print exception string"""
        return (
            f"unexpected balance for account {self.address}: "
            + f"want {self.want}, got {self.got}"
        )

__str__()

Print exception string

Source code in src/ethereum_test_tools/common/types.py
440
441
442
443
444
445
def __str__(self):
    """Print exception string"""
    return (
        f"unexpected balance for account {self.address}: "
        + f"want {self.want}, got {self.got}"
    )

CodeMismatch dataclass

Bases: Exception

Test expected a certain bytecode for an account but a different one was found.

Source code in src/ethereum_test_tools/common/types.py
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
@dataclass(kw_only=True)
class CodeMismatch(Exception):
    """
    Test expected a certain bytecode for an account but a different
    one was found.
    """

    address: Address
    want: str | None
    got: str | None

    def __init__(self, address: Address, want: str | None, got: str | None, *args):
        super().__init__(args)
        self.address = address
        self.want = want
        self.got = got

    def __str__(self):
        """Print exception string"""
        return (
            f"unexpected code for account {self.address}: "
            + f"want {self.want}, got {self.got}"
        )

__str__()

Print exception string

Source code in src/ethereum_test_tools/common/types.py
464
465
466
467
468
469
def __str__(self):
    """Print exception string"""
    return (
        f"unexpected code for account {self.address}: "
        + f"want {self.want}, got {self.got}"
    )

check_alloc(address, alloc)

Checks the returned alloc against an expected account in post state. Raises exception on failure.

Source code in src/ethereum_test_tools/common/types.py
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
def check_alloc(self: "Account", address: Address, alloc: dict):
    """
    Checks the returned alloc against an expected account in post state.
    Raises exception on failure.
    """
    if self.nonce is not None:
        actual_nonce = int_or_none(alloc.get("nonce"), 0)
        nonce = int(Number(self.nonce))
        if nonce != actual_nonce:
            raise Account.NonceMismatch(
                address=address,
                want=nonce,
                got=actual_nonce,
            )

    if self.balance is not None:
        actual_balance = int_or_none(alloc.get("balance"), 0)
        balance = int(Number(self.balance))
        if balance != actual_balance:
            raise Account.BalanceMismatch(
                address=address,
                want=balance,
                got=actual_balance,
            )

    if self.code is not None:
        expected_code = Bytes(self.code).hex()
        actual_code = str_or_none(alloc.get("code"), "0x")
        if expected_code != actual_code:
            raise Account.CodeMismatch(
                address=address,
                want=expected_code,
                got=actual_code,
            )

    if self.storage is not None:
        expected_storage = (
            self.storage if isinstance(self.storage, Storage) else Storage(self.storage)
        )
        actual_storage = Storage(alloc["storage"]) if "storage" in alloc else Storage({})
        expected_storage.must_be_equal(address=address, other=actual_storage)

has_empty_code()

Returns true if an account has no bytecode.

Source code in src/ethereum_test_tools/common/types.py
513
514
515
516
517
def has_empty_code(self: "Account") -> bool:
    """
    Returns true if an account has no bytecode.
    """
    return not self.code or Bytes(self.code) == b""

is_empty()

Returns true if an account deemed empty.

Source code in src/ethereum_test_tools/common/types.py
519
520
521
522
523
524
525
526
527
528
def is_empty(self: "Account") -> bool:
    """
    Returns true if an account deemed empty.
    """
    return (
        (self.nonce == 0 or self.nonce is None)
        and (self.balance == 0 or self.balance is None)
        and self.has_empty_code()
        and (not self.storage or self.storage == {} or self.storage is None)
    )

from_dict(data) classmethod

Create account from dictionary.

Source code in src/ethereum_test_tools/common/types.py
530
531
532
533
534
535
536
537
@classmethod
def from_dict(cls: Type, data: "Dict | Account") -> "Account":
    """
    Create account from dictionary.
    """
    if isinstance(data, cls):
        return data
    return cls(**data)

with_code(code) classmethod

Create account with provided code and nonce of 1.

Source code in src/ethereum_test_tools/common/types.py
539
540
541
542
543
544
@classmethod
def with_code(cls: Type, code: BytesConvertible) -> "Account":
    """
    Create account with provided `code` and nonce of `1`.
    """
    return Account(nonce=1, code=code)

merge(account_1, account_2) classmethod

Create a merged account from two sources.

Source code in src/ethereum_test_tools/common/types.py
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
@classmethod
def merge(
    cls: Type, account_1: "Dict | Account | None", account_2: "Dict | Account | None"
) -> "Account":
    """
    Create a merged account from two sources.
    """

    def to_kwargs_dict(account: "Dict | Account | None") -> Dict:
        if account is None:
            return {}
        if isinstance(account, dict):
            return account
        elif isinstance(account, cls):
            return {
                f.name: v for f in fields(cls) if (v := getattr(account, f.name)) is not None
            }
        raise TypeError(f"Unexpected type for account merge: {type(account)}")

    kwargs = to_kwargs_dict(account_1)
    kwargs.update(to_kwargs_dict(account_2))

    return cls(**kwargs)

Address

Bases: FixedSizeBytes[20]

Class that helps represent Ethereum addresses in tests.

Source code in src/ethereum_test_tools/common/base_types.py
190
191
192
193
194
195
class Address(FixedSizeBytes[20]):  # type: ignore
    """
    Class that helps represent Ethereum addresses in tests.
    """

    pass

Auto

Class to use as a sentinel value for parameters that should be automatically calculated.

Source code in src/ethereum_test_tools/common/types.py
55
56
57
58
59
60
61
62
63
class Auto:
    """
    Class to use as a sentinel value for parameters that should be
    automatically calculated.
    """

    def __repr__(self) -> str:
        """Print the correct test id."""
        return "auto"

__repr__()

Print the correct test id.

Source code in src/ethereum_test_tools/common/types.py
61
62
63
def __repr__(self) -> str:
    """Print the correct test id."""
    return "auto"

EngineAPIError

Bases: IntEnum

List of Engine API errors

Source code in src/ethereum_test_tools/common/constants.py
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
class EngineAPIError(IntEnum):
    """
    List of Engine API errors
    """

    ParseError = -32700
    InvalidRequest = -32600
    MethodNotFound = -32601
    InvalidParams = -32602
    InternalError = -32603
    ServerError = -32000
    UnknownPayload = -38001
    InvalidForkchoiceState = -38002
    InvalidPayloadAttributes = -38003
    TooLargeRequest = -38004
    UnsupportedFork = -38005

Environment dataclass

Structure used to keep track of the context in which a block must be executed.

Source code in src/ethereum_test_tools/common/types.py
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
@dataclass(kw_only=True)
class Environment:
    """
    Structure used to keep track of the context in which a block
    must be executed.
    """

    coinbase: FixedSizeBytesConvertible = field(
        default="0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba",
        json_encoder=JSONEncoder.Field(
            name="currentCoinbase",
            cast_type=Address,
        ),
    )
    gas_limit: NumberConvertible = field(
        default=100000000000000000,
        json_encoder=JSONEncoder.Field(
            name="currentGasLimit",
            cast_type=Number,
        ),
    )
    number: NumberConvertible = field(
        default=1,
        json_encoder=JSONEncoder.Field(
            name="currentNumber",
            cast_type=Number,
        ),
    )
    timestamp: NumberConvertible = field(
        default=1000,
        json_encoder=JSONEncoder.Field(
            name="currentTimestamp",
            cast_type=Number,
        ),
    )
    prev_randao: Optional[NumberConvertible] = field(
        default=None,
        json_encoder=JSONEncoder.Field(
            name="currentRandom",
            cast_type=Number,
        ),
    )
    difficulty: Optional[NumberConvertible] = field(
        default=None,
        json_encoder=JSONEncoder.Field(
            name="currentDifficulty",
            cast_type=Number,
        ),
    )
    block_hashes: Dict[NumberConvertible, FixedSizeBytesConvertible] = field(
        default_factory=dict,
        json_encoder=JSONEncoder.Field(
            name="blockHashes",
            cast_type=lambda x: {str(Number(k)): str(Hash(v)) for k, v in x.items()},
            skip_string_convert=True,
        ),
    )
    ommers: List[FixedSizeBytesConvertible] = field(
        default_factory=list,
        json_encoder=JSONEncoder.Field(
            name="ommers",
            cast_type=lambda x: [str(Hash(y)) for y in x],
            skip_string_convert=True,
        ),
    )
    withdrawals: Optional[List[Withdrawal]] = field(
        default=None,
        json_encoder=JSONEncoder.Field(
            name="withdrawals",
            to_json=True,
        ),
    )
    base_fee: Optional[NumberConvertible] = field(
        default=None,
        json_encoder=JSONEncoder.Field(
            name="currentBaseFee",
            cast_type=Number,
        ),
    )
    parent_difficulty: Optional[NumberConvertible] = field(
        default=None,
        json_encoder=JSONEncoder.Field(
            name="parentDifficulty",
            cast_type=Number,
        ),
    )
    parent_timestamp: Optional[NumberConvertible] = field(
        default=None,
        json_encoder=JSONEncoder.Field(
            name="parentTimestamp",
            cast_type=Number,
        ),
    )
    parent_base_fee: Optional[NumberConvertible] = field(
        default=None,
        json_encoder=JSONEncoder.Field(
            name="parentBaseFee",
            cast_type=Number,
        ),
    )
    parent_gas_used: Optional[NumberConvertible] = field(
        default=None,
        json_encoder=JSONEncoder.Field(
            name="parentGasUsed",
            cast_type=Number,
        ),
    )
    parent_gas_limit: Optional[NumberConvertible] = field(
        default=None,
        json_encoder=JSONEncoder.Field(
            name="parentGasLimit",
            cast_type=Number,
        ),
    )
    parent_ommers_hash: FixedSizeBytesConvertible = field(
        default=0,
        json_encoder=JSONEncoder.Field(
            name="parentUncleHash",
            cast_type=Hash,
        ),
    )
    parent_blob_gas_used: Optional[NumberConvertible] = field(
        default=None,
        json_encoder=JSONEncoder.Field(
            name="parentBlobGasUsed",
            cast_type=Number,
        ),
    )
    parent_excess_blob_gas: Optional[NumberConvertible] = field(
        default=None,
        json_encoder=JSONEncoder.Field(
            name="parentExcessBlobGas",
            cast_type=Number,
        ),
    )
    blob_gas_used: Optional[NumberConvertible] = field(
        default=None,
        json_encoder=JSONEncoder.Field(
            name="currentBlobGasUsed",
            cast_type=Number,
        ),
    )
    excess_blob_gas: Optional[NumberConvertible] = field(
        default=None,
        json_encoder=JSONEncoder.Field(
            name="currentExcessBlobGas",
            cast_type=Number,
        ),
    )
    beacon_root: Optional[FixedSizeBytesConvertible] = field(
        default=None,
        json_encoder=JSONEncoder.Field(
            name="parentBeaconBlockRoot",
            cast_type=Hash,
        ),
    )
    extra_data: Optional[BytesConvertible] = field(
        default=b"\x00",
        json_encoder=JSONEncoder.Field(
            skip=True,
        ),
    )

    def parent_hash(self) -> bytes:
        """
        Obtains the latest hash according to the highest block number in
        `block_hashes`.
        """
        if len(self.block_hashes) == 0:
            return bytes([0] * 32)

        last_index = max([Number(k) for k in self.block_hashes.keys()])
        return Hash(self.block_hashes[last_index])

    def set_fork_requirements(self, fork: Fork, in_place: bool = False) -> "Environment":
        """
        Fills the required fields in an environment depending on the fork.
        """
        res = self if in_place else copy(self)
        number = Number(res.number)
        timestamp = Number(res.timestamp)
        if fork.header_prev_randao_required(number, timestamp) and res.prev_randao is None:
            res.prev_randao = 0

        if fork.header_withdrawals_required(number, timestamp) and res.withdrawals is None:
            res.withdrawals = []

        if (
            fork.header_base_fee_required(number, timestamp)
            and res.base_fee is None
            and res.parent_base_fee is None
        ):
            res.base_fee = DEFAULT_BASE_FEE

        if fork.header_zero_difficulty_required(number, timestamp):
            res.difficulty = 0
        elif res.difficulty is None and res.parent_difficulty is None:
            res.difficulty = 0x20000

        if (
            fork.header_excess_blob_gas_required(number, timestamp)
            and res.excess_blob_gas is None
            and res.parent_excess_blob_gas is None
        ):
            res.excess_blob_gas = 0

        if (
            fork.header_blob_gas_used_required(number, timestamp)
            and res.blob_gas_used is None
            and res.parent_blob_gas_used is None
        ):
            res.blob_gas_used = 0

        if fork.header_beacon_root_required(number, timestamp) and res.beacon_root is None:
            res.beacon_root = 0

        return res

parent_hash()

Obtains the latest hash according to the highest block number in block_hashes.

Source code in src/ethereum_test_tools/common/types.py
876
877
878
879
880
881
882
883
884
885
def parent_hash(self) -> bytes:
    """
    Obtains the latest hash according to the highest block number in
    `block_hashes`.
    """
    if len(self.block_hashes) == 0:
        return bytes([0] * 32)

    last_index = max([Number(k) for k in self.block_hashes.keys()])
    return Hash(self.block_hashes[last_index])

set_fork_requirements(fork, in_place=False)

Fills the required fields in an environment depending on the fork.

Source code in src/ethereum_test_tools/common/types.py
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
def set_fork_requirements(self, fork: Fork, in_place: bool = False) -> "Environment":
    """
    Fills the required fields in an environment depending on the fork.
    """
    res = self if in_place else copy(self)
    number = Number(res.number)
    timestamp = Number(res.timestamp)
    if fork.header_prev_randao_required(number, timestamp) and res.prev_randao is None:
        res.prev_randao = 0

    if fork.header_withdrawals_required(number, timestamp) and res.withdrawals is None:
        res.withdrawals = []

    if (
        fork.header_base_fee_required(number, timestamp)
        and res.base_fee is None
        and res.parent_base_fee is None
    ):
        res.base_fee = DEFAULT_BASE_FEE

    if fork.header_zero_difficulty_required(number, timestamp):
        res.difficulty = 0
    elif res.difficulty is None and res.parent_difficulty is None:
        res.difficulty = 0x20000

    if (
        fork.header_excess_blob_gas_required(number, timestamp)
        and res.excess_blob_gas is None
        and res.parent_excess_blob_gas is None
    ):
        res.excess_blob_gas = 0

    if (
        fork.header_blob_gas_used_required(number, timestamp)
        and res.blob_gas_used is None
        and res.parent_blob_gas_used is None
    ):
        res.blob_gas_used = 0

    if fork.header_beacon_root_required(number, timestamp) and res.beacon_root is None:
        res.beacon_root = 0

    return res

Hash

Bases: FixedSizeBytes[32]

Class that helps represent hashes in tests.

Source code in src/ethereum_test_tools/common/base_types.py
198
199
200
201
202
203
class Hash(FixedSizeBytes[32]):  # type: ignore
    """
    Class that helps represent hashes in tests.
    """

    pass

JSONEncoder

Bases: JSONEncoder

Custom JSON encoder for ethereum_test types.

Source code in src/ethereum_test_tools/common/json.py
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
class JSONEncoder(json.JSONEncoder):
    """
    Custom JSON encoder for `ethereum_test` types.
    """

    @dataclass(kw_only=True)
    class Field:
        """
        Settings for a field in a JSON object.
        """

        name: Optional[str] = None
        """
        The name of the field in the JSON object.
        """
        cast_type: Optional[Callable] = None
        """
        The type or function to use to cast the field to before serializing.
        """
        skip_string_convert: bool = False
        """
        By default, the fields are converted to string after serializing.
        """
        to_json: bool = False
        """
        Whether the field should be converted to JSON by itself.
        This option and `JSON_SKIP_STRING_CONVERT` are mutually exclusive.
        """
        default_value: Optional[Any] = None
        """
        Value to use if the field is not set before type casting.
        """
        default_value_skip_cast: Optional[Any] = None
        """
        Value to use if the field is not set and also skip type casting.
        """
        keep_none: bool = False
        """
        Whether to keep the field if it is `None`.
        """
        skip: bool = False
        """
        Whether to skip the field when serializing.
        """

        def apply(
            self, encoder: json.JSONEncoder, target: Dict[str, Any], field_name: str, value: Any
        ) -> None:
            """
            Applies the settings to the target dictionary.
            """
            if self.skip:
                return

            if self.name:
                field_name = self.name

            if value is None:
                if self.default_value is not None:
                    value = self.default_value
                elif self.default_value_skip_cast is not None:
                    target[field_name] = self.default_value_skip_cast
                    return

                if not self.keep_none and value is None:
                    return

            if value is not None:
                if self.cast_type is not None:
                    value = self.cast_type(value)

                if self.to_json:
                    value = encoder.default(value)
                elif not self.skip_string_convert:
                    value = str(value)

            target[field_name] = value

    def default(self, obj: Any) -> Any:
        """
        Encodes types defined in this module using basic python facilities.
        """
        if callable(getattr(obj, "__json__", False)):
            return obj.__json__(encoder=self)

        elif is_dataclass(obj):
            result: Dict[str, Any] = {}
            for object_field in fields(obj):
                field_name = object_field.name
                metadata = object_field.metadata
                if not metadata:
                    continue
                value = getattr(obj, field_name)
                field_settings = metadata.get("json_encoder")
                assert isinstance(field_settings, self.Field), (
                    f"Field {field_name} has invalid json_encoder " f"metadata: {field_settings}"
                )
                field_settings.apply(self, result, field_name, value)
            return result

        elif isinstance(obj, dict):
            return {self.default(k): self.default(v) for k, v in obj.items()}

        elif isinstance(obj, list) or isinstance(obj, tuple):
            return [self.default(item) for item in obj]

        elif isinstance(obj, str) or isinstance(obj, int) or isinstance(obj, bool) or obj is None:
            return obj

        else:
            return super().default(obj)

Field dataclass

Settings for a field in a JSON object.

Source code in src/ethereum_test_tools/common/json.py
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
@dataclass(kw_only=True)
class Field:
    """
    Settings for a field in a JSON object.
    """

    name: Optional[str] = None
    """
    The name of the field in the JSON object.
    """
    cast_type: Optional[Callable] = None
    """
    The type or function to use to cast the field to before serializing.
    """
    skip_string_convert: bool = False
    """
    By default, the fields are converted to string after serializing.
    """
    to_json: bool = False
    """
    Whether the field should be converted to JSON by itself.
    This option and `JSON_SKIP_STRING_CONVERT` are mutually exclusive.
    """
    default_value: Optional[Any] = None
    """
    Value to use if the field is not set before type casting.
    """
    default_value_skip_cast: Optional[Any] = None
    """
    Value to use if the field is not set and also skip type casting.
    """
    keep_none: bool = False
    """
    Whether to keep the field if it is `None`.
    """
    skip: bool = False
    """
    Whether to skip the field when serializing.
    """

    def apply(
        self, encoder: json.JSONEncoder, target: Dict[str, Any], field_name: str, value: Any
    ) -> None:
        """
        Applies the settings to the target dictionary.
        """
        if self.skip:
            return

        if self.name:
            field_name = self.name

        if value is None:
            if self.default_value is not None:
                value = self.default_value
            elif self.default_value_skip_cast is not None:
                target[field_name] = self.default_value_skip_cast
                return

            if not self.keep_none and value is None:
                return

        if value is not None:
            if self.cast_type is not None:
                value = self.cast_type(value)

            if self.to_json:
                value = encoder.default(value)
            elif not self.skip_string_convert:
                value = str(value)

        target[field_name] = value

name: Optional[str] = None class-attribute instance-attribute

The name of the field in the JSON object.

cast_type: Optional[Callable] = None class-attribute instance-attribute

The type or function to use to cast the field to before serializing.

skip_string_convert: bool = False class-attribute instance-attribute

By default, the fields are converted to string after serializing.

to_json: bool = False class-attribute instance-attribute

Whether the field should be converted to JSON by itself. This option and JSON_SKIP_STRING_CONVERT are mutually exclusive.

default_value: Optional[Any] = None class-attribute instance-attribute

Value to use if the field is not set before type casting.

default_value_skip_cast: Optional[Any] = None class-attribute instance-attribute

Value to use if the field is not set and also skip type casting.

keep_none: bool = False class-attribute instance-attribute

Whether to keep the field if it is None.

skip: bool = False class-attribute instance-attribute

Whether to skip the field when serializing.

apply(encoder, target, field_name, value)

Applies the settings to the target dictionary.

Source code in src/ethereum_test_tools/common/json.py
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
def apply(
    self, encoder: json.JSONEncoder, target: Dict[str, Any], field_name: str, value: Any
) -> None:
    """
    Applies the settings to the target dictionary.
    """
    if self.skip:
        return

    if self.name:
        field_name = self.name

    if value is None:
        if self.default_value is not None:
            value = self.default_value
        elif self.default_value_skip_cast is not None:
            target[field_name] = self.default_value_skip_cast
            return

        if not self.keep_none and value is None:
            return

    if value is not None:
        if self.cast_type is not None:
            value = self.cast_type(value)

        if self.to_json:
            value = encoder.default(value)
        elif not self.skip_string_convert:
            value = str(value)

    target[field_name] = value

default(obj)

Encodes types defined in this module using basic python facilities.

Source code in src/ethereum_test_tools/common/json.py
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
def default(self, obj: Any) -> Any:
    """
    Encodes types defined in this module using basic python facilities.
    """
    if callable(getattr(obj, "__json__", False)):
        return obj.__json__(encoder=self)

    elif is_dataclass(obj):
        result: Dict[str, Any] = {}
        for object_field in fields(obj):
            field_name = object_field.name
            metadata = object_field.metadata
            if not metadata:
                continue
            value = getattr(obj, field_name)
            field_settings = metadata.get("json_encoder")
            assert isinstance(field_settings, self.Field), (
                f"Field {field_name} has invalid json_encoder " f"metadata: {field_settings}"
            )
            field_settings.apply(self, result, field_name, value)
        return result

    elif isinstance(obj, dict):
        return {self.default(k): self.default(v) for k, v in obj.items()}

    elif isinstance(obj, list) or isinstance(obj, tuple):
        return [self.default(item) for item in obj]

    elif isinstance(obj, str) or isinstance(obj, int) or isinstance(obj, bool) or obj is None:
        return obj

    else:
        return super().default(obj)

Removable

Sentinel class to detect if a parameter should be removed. (None normally means "do not modify")

Source code in src/ethereum_test_tools/common/types.py
46
47
48
49
50
51
52
class Removable:
    """
    Sentinel class to detect if a parameter should be removed.
    (`None` normally means "do not modify")
    """

    pass

Storage

Bases: SupportsJSON, dict

Definition of a storage in pre or post state of a test

Source code in src/ethereum_test_tools/common/types.py
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
class Storage(SupportsJSON, dict):
    """
    Definition of a storage in pre or post state of a test
    """

    current_slot: Iterator[int]

    StorageDictType: ClassVar[TypeAlias] = Dict[
        str | int | bytes | SupportsBytes, str | int | bytes | SupportsBytes
    ]
    """
    Dictionary type to be used when defining an input to initialize a storage.
    """

    @dataclass(kw_only=True)
    class InvalidType(Exception):
        """
        Invalid type used when describing test's expected storage key or value.
        """

        key_or_value: Any

        def __init__(self, key_or_value: Any, *args):
            super().__init__(args)
            self.key_or_value = key_or_value

        def __str__(self):
            """Print exception string"""
            return f"invalid type for key/value: {self.key_or_value}"

    @dataclass(kw_only=True)
    class InvalidValue(Exception):
        """
        Invalid value used when describing test's expected storage key or
        value.
        """

        key_or_value: Any

        def __init__(self, key_or_value: Any, *args):
            super().__init__(args)
            self.key_or_value = key_or_value

        def __str__(self):
            """Print exception string"""
            return f"invalid value for key/value: {self.key_or_value}"

    @dataclass(kw_only=True)
    class AmbiguousKeyValue(Exception):
        """
        Key is represented twice in the storage.
        """

        key_1: str | int
        val_1: str | int
        key_2: str | int
        val_2: str | int

        def __init__(
            self,
            key_1: str | int,
            val_1: str | int,
            key_2: str | int,
            val_2: str | int,
            *args,
        ):
            super().__init__(args)
            self.key_1 = key_1
            self.val_1 = val_1
            self.key_2 = key_2
            self.val_2 = val_2

        def __str__(self):
            """Print exception string"""
            return f"""
            Key is represented twice (due to negative numbers) with different
            values in storage:
            s[{self.key_1}] = {self.val_1} and s[{self.key_2}] = {self.val_2}
            """

    @dataclass(kw_only=True)
    class MissingKey(Exception):
        """
        Test expected to find a storage key set but key was missing.
        """

        key: int

        def __init__(self, key: int, *args):
            super().__init__(args)
            self.key = key

        def __str__(self):
            """Print exception string"""
            return "key {0} not found in storage".format(Storage.key_value_to_string(self.key))

    @dataclass(kw_only=True)
    class KeyValueMismatch(Exception):
        """
        Test expected a certain value in a storage key but value found
        was different.
        """

        address: Address
        key: int
        want: int
        got: int

        def __init__(self, address: Address, key: int, want: int, got: int, *args):
            super().__init__(args)
            self.address = address
            self.key = key
            self.want = want
            self.got = got

        def __str__(self):
            """Print exception string"""
            return (
                f"incorrect value in address {self.address} for "
                + f"key {Storage.key_value_to_string(self.key)}:"
                + f" want {Storage.key_value_to_string(self.want)} (dec:{self.want}),"
                + f" got {Storage.key_value_to_string(self.got)} (dec:{self.got})"
            )

    @staticmethod
    def parse_key_value(input: str | int | bytes | SupportsBytes) -> int:
        """
        Parses a key or value to a valid int key for storage.
        """
        if isinstance(input, str):
            input = int(input, 0)
        elif isinstance(input, int):
            pass
        elif isinstance(input, bytes) or isinstance(input, SupportsBytes):
            input = int.from_bytes(bytes(input), "big")
        else:
            raise Storage.InvalidType(key_or_value=input)

        if input > MAX_STORAGE_KEY_VALUE or input < MIN_STORAGE_KEY_VALUE:
            raise Storage.InvalidValue(key_or_value=input)
        return input

    @staticmethod
    def key_value_to_string(value: int) -> str:
        """
        Transforms a key or value into an hex string.
        """
        hex_str = value.to_bytes(32, "big", signed=(value < 0)).hex().lstrip("0")
        if hex_str == "":
            hex_str = "00"
        if len(hex_str) % 2 != 0:
            hex_str = "0" + hex_str
        return "0x" + hex_str

    def __init__(self, input: StorageDictType | "Storage" = {}, *, start_slot: int = 0):
        """
        Initializes the storage using a given mapping which can have
        keys and values either as string or int.
        Strings must be valid decimal or hexadecimal (starting with 0x)
        numbers.
        """
        super().__init__(
            (Storage.parse_key_value(k), Storage.parse_key_value(v)) for k, v in input.items()
        )
        self.current_slot = count(start_slot)

    def __contains__(self, key: object) -> bool:
        """Checks for an item in the storage"""
        assert (
            isinstance(key, str)
            or isinstance(key, int)
            or isinstance(key, bytes)
            or isinstance(key, SupportsBytes)
        )
        return super().__contains__(Storage.parse_key_value(key))

    def __getitem__(self, key: str | int | bytes | SupportsBytes) -> int:
        """Returns an item from the storage"""
        return super().__getitem__(Storage.parse_key_value(key))

    def __setitem__(
        self, key: str | int | bytes | SupportsBytes, value: str | int | bytes | SupportsBytes
    ):  # noqa: SC200
        """Sets an item in the storage"""
        super().__setitem__(Storage.parse_key_value(key), Storage.parse_key_value(value))

    def __delitem__(self, key: str | int | bytes | SupportsBytes):
        """Deletes an item from the storage"""
        super().__delitem__(Storage.parse_key_value(key))

    def store_next(self, value: str | int | bytes | SupportsBytes) -> int:
        """
        Stores a value in the storage and returns the key where the value is stored.

        Increments the key counter so the next time this function is called,
        the next key is used.
        """
        self[slot := next(self.current_slot)] = value
        return slot

    def __json__(self, encoder: JSONEncoder) -> Mapping[str, str]:
        """
        Converts the storage into a string dict with appropriate 32-byte
        hex string formatting.
        """
        res: Dict[str, str] = {}
        for key, value in self.items():
            key_repr = Storage.key_value_to_string(key)
            val_repr = Storage.key_value_to_string(value)
            if key_repr in res and val_repr != res[key_repr]:
                raise Storage.AmbiguousKeyValue(
                    key_1=key_repr, val_1=res[key_repr], key_2=key, val_2=val_repr
                )
            res[key_repr] = val_repr
        return res

    def contains(self, other: "Storage") -> bool:
        """
        Returns True if self contains all keys with equal value as
        contained by second storage.
        Used for comparison with test expected post state and alloc returned
        by the transition tool.
        """
        for key in other:
            if key not in self:
                return False
            if self[key] != other[key]:
                return False
        return True

    def must_contain(self, address: Address, other: "Storage"):
        """
        Succeeds only if self contains all keys with equal value as
        contained by second storage.
        Used for comparison with test expected post state and alloc returned
        by the transition tool.
        Raises detailed exception when a difference is found.
        """
        for key in other:
            if key not in self:
                # storage[key]==0 is equal to missing storage
                if other[key] != 0:
                    raise Storage.MissingKey(key=key)
            elif self[key] != other[key]:
                raise Storage.KeyValueMismatch(
                    address=address, key=key, want=self[key], got=other[key]
                )

    def must_be_equal(self, address: Address, other: "Storage"):
        """
        Succeeds only if "self" is equal to "other" storage.
        """
        # Test keys contained in both storage objects
        for key in self.keys() & other.keys():
            if self[key] != other[key]:
                raise Storage.KeyValueMismatch(
                    address=address, key=key, want=self[key], got=other[key]
                )

        # Test keys contained in either one of the storage objects
        for key in self.keys() ^ other.keys():
            if key in self:
                if self[key] != 0:
                    raise Storage.KeyValueMismatch(address=address, key=key, want=self[key], got=0)

            elif other[key] != 0:
                raise Storage.KeyValueMismatch(address=address, key=key, want=0, got=other[key])

StorageDictType: TypeAlias = Dict[str | int | bytes | SupportsBytes, str | int | bytes | SupportsBytes] class-attribute

Dictionary type to be used when defining an input to initialize a storage.

InvalidType dataclass

Bases: Exception

Invalid type used when describing test's expected storage key or value.

Source code in src/ethereum_test_tools/common/types.py
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
@dataclass(kw_only=True)
class InvalidType(Exception):
    """
    Invalid type used when describing test's expected storage key or value.
    """

    key_or_value: Any

    def __init__(self, key_or_value: Any, *args):
        super().__init__(args)
        self.key_or_value = key_or_value

    def __str__(self):
        """Print exception string"""
        return f"invalid type for key/value: {self.key_or_value}"

__str__()

Print exception string

Source code in src/ethereum_test_tools/common/types.py
96
97
98
def __str__(self):
    """Print exception string"""
    return f"invalid type for key/value: {self.key_or_value}"

InvalidValue dataclass

Bases: Exception

Invalid value used when describing test's expected storage key or value.

Source code in src/ethereum_test_tools/common/types.py
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
@dataclass(kw_only=True)
class InvalidValue(Exception):
    """
    Invalid value used when describing test's expected storage key or
    value.
    """

    key_or_value: Any

    def __init__(self, key_or_value: Any, *args):
        super().__init__(args)
        self.key_or_value = key_or_value

    def __str__(self):
        """Print exception string"""
        return f"invalid value for key/value: {self.key_or_value}"

__str__()

Print exception string

Source code in src/ethereum_test_tools/common/types.py
113
114
115
def __str__(self):
    """Print exception string"""
    return f"invalid value for key/value: {self.key_or_value}"

AmbiguousKeyValue dataclass

Bases: Exception

Key is represented twice in the storage.

Source code in src/ethereum_test_tools/common/types.py
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
@dataclass(kw_only=True)
class AmbiguousKeyValue(Exception):
    """
    Key is represented twice in the storage.
    """

    key_1: str | int
    val_1: str | int
    key_2: str | int
    val_2: str | int

    def __init__(
        self,
        key_1: str | int,
        val_1: str | int,
        key_2: str | int,
        val_2: str | int,
        *args,
    ):
        super().__init__(args)
        self.key_1 = key_1
        self.val_1 = val_1
        self.key_2 = key_2
        self.val_2 = val_2

    def __str__(self):
        """Print exception string"""
        return f"""
        Key is represented twice (due to negative numbers) with different
        values in storage:
        s[{self.key_1}] = {self.val_1} and s[{self.key_2}] = {self.val_2}
        """

__str__()

Print exception string

Source code in src/ethereum_test_tools/common/types.py
142
143
144
145
146
147
148
def __str__(self):
    """Print exception string"""
    return f"""
    Key is represented twice (due to negative numbers) with different
    values in storage:
    s[{self.key_1}] = {self.val_1} and s[{self.key_2}] = {self.val_2}
    """

MissingKey dataclass

Bases: Exception

Test expected to find a storage key set but key was missing.

Source code in src/ethereum_test_tools/common/types.py
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
@dataclass(kw_only=True)
class MissingKey(Exception):
    """
    Test expected to find a storage key set but key was missing.
    """

    key: int

    def __init__(self, key: int, *args):
        super().__init__(args)
        self.key = key

    def __str__(self):
        """Print exception string"""
        return "key {0} not found in storage".format(Storage.key_value_to_string(self.key))

__str__()

Print exception string

Source code in src/ethereum_test_tools/common/types.py
162
163
164
def __str__(self):
    """Print exception string"""
    return "key {0} not found in storage".format(Storage.key_value_to_string(self.key))

KeyValueMismatch dataclass

Bases: Exception

Test expected a certain value in a storage key but value found was different.

Source code in src/ethereum_test_tools/common/types.py
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
@dataclass(kw_only=True)
class KeyValueMismatch(Exception):
    """
    Test expected a certain value in a storage key but value found
    was different.
    """

    address: Address
    key: int
    want: int
    got: int

    def __init__(self, address: Address, key: int, want: int, got: int, *args):
        super().__init__(args)
        self.address = address
        self.key = key
        self.want = want
        self.got = got

    def __str__(self):
        """Print exception string"""
        return (
            f"incorrect value in address {self.address} for "
            + f"key {Storage.key_value_to_string(self.key)}:"
            + f" want {Storage.key_value_to_string(self.want)} (dec:{self.want}),"
            + f" got {Storage.key_value_to_string(self.got)} (dec:{self.got})"
        )

__str__()

Print exception string

Source code in src/ethereum_test_tools/common/types.py
185
186
187
188
189
190
191
192
def __str__(self):
    """Print exception string"""
    return (
        f"incorrect value in address {self.address} for "
        + f"key {Storage.key_value_to_string(self.key)}:"
        + f" want {Storage.key_value_to_string(self.want)} (dec:{self.want}),"
        + f" got {Storage.key_value_to_string(self.got)} (dec:{self.got})"
    )

parse_key_value(input) staticmethod

Parses a key or value to a valid int key for storage.

Source code in src/ethereum_test_tools/common/types.py
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
@staticmethod
def parse_key_value(input: str | int | bytes | SupportsBytes) -> int:
    """
    Parses a key or value to a valid int key for storage.
    """
    if isinstance(input, str):
        input = int(input, 0)
    elif isinstance(input, int):
        pass
    elif isinstance(input, bytes) or isinstance(input, SupportsBytes):
        input = int.from_bytes(bytes(input), "big")
    else:
        raise Storage.InvalidType(key_or_value=input)

    if input > MAX_STORAGE_KEY_VALUE or input < MIN_STORAGE_KEY_VALUE:
        raise Storage.InvalidValue(key_or_value=input)
    return input

key_value_to_string(value) staticmethod

Transforms a key or value into an hex string.

Source code in src/ethereum_test_tools/common/types.py
212
213
214
215
216
217
218
219
220
221
222
@staticmethod
def key_value_to_string(value: int) -> str:
    """
    Transforms a key or value into an hex string.
    """
    hex_str = value.to_bytes(32, "big", signed=(value < 0)).hex().lstrip("0")
    if hex_str == "":
        hex_str = "00"
    if len(hex_str) % 2 != 0:
        hex_str = "0" + hex_str
    return "0x" + hex_str

__init__(input={}, *, start_slot=0)

Initializes the storage using a given mapping which can have keys and values either as string or int. Strings must be valid decimal or hexadecimal (starting with 0x) numbers.

Source code in src/ethereum_test_tools/common/types.py
224
225
226
227
228
229
230
231
232
233
234
def __init__(self, input: StorageDictType | "Storage" = {}, *, start_slot: int = 0):
    """
    Initializes the storage using a given mapping which can have
    keys and values either as string or int.
    Strings must be valid decimal or hexadecimal (starting with 0x)
    numbers.
    """
    super().__init__(
        (Storage.parse_key_value(k), Storage.parse_key_value(v)) for k, v in input.items()
    )
    self.current_slot = count(start_slot)

__contains__(key)

Checks for an item in the storage

Source code in src/ethereum_test_tools/common/types.py
236
237
238
239
240
241
242
243
244
def __contains__(self, key: object) -> bool:
    """Checks for an item in the storage"""
    assert (
        isinstance(key, str)
        or isinstance(key, int)
        or isinstance(key, bytes)
        or isinstance(key, SupportsBytes)
    )
    return super().__contains__(Storage.parse_key_value(key))

__getitem__(key)

Returns an item from the storage

Source code in src/ethereum_test_tools/common/types.py
246
247
248
def __getitem__(self, key: str | int | bytes | SupportsBytes) -> int:
    """Returns an item from the storage"""
    return super().__getitem__(Storage.parse_key_value(key))

__setitem__(key, value)

Sets an item in the storage

Source code in src/ethereum_test_tools/common/types.py
250
251
252
253
254
def __setitem__(
    self, key: str | int | bytes | SupportsBytes, value: str | int | bytes | SupportsBytes
):  # noqa: SC200
    """Sets an item in the storage"""
    super().__setitem__(Storage.parse_key_value(key), Storage.parse_key_value(value))

__delitem__(key)

Deletes an item from the storage

Source code in src/ethereum_test_tools/common/types.py
256
257
258
def __delitem__(self, key: str | int | bytes | SupportsBytes):
    """Deletes an item from the storage"""
    super().__delitem__(Storage.parse_key_value(key))

store_next(value)

Stores a value in the storage and returns the key where the value is stored.

Increments the key counter so the next time this function is called, the next key is used.

Source code in src/ethereum_test_tools/common/types.py
260
261
262
263
264
265
266
267
268
def store_next(self, value: str | int | bytes | SupportsBytes) -> int:
    """
    Stores a value in the storage and returns the key where the value is stored.

    Increments the key counter so the next time this function is called,
    the next key is used.
    """
    self[slot := next(self.current_slot)] = value
    return slot

__json__(encoder)

Converts the storage into a string dict with appropriate 32-byte hex string formatting.

Source code in src/ethereum_test_tools/common/types.py
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
def __json__(self, encoder: JSONEncoder) -> Mapping[str, str]:
    """
    Converts the storage into a string dict with appropriate 32-byte
    hex string formatting.
    """
    res: Dict[str, str] = {}
    for key, value in self.items():
        key_repr = Storage.key_value_to_string(key)
        val_repr = Storage.key_value_to_string(value)
        if key_repr in res and val_repr != res[key_repr]:
            raise Storage.AmbiguousKeyValue(
                key_1=key_repr, val_1=res[key_repr], key_2=key, val_2=val_repr
            )
        res[key_repr] = val_repr
    return res

contains(other)

Returns True if self contains all keys with equal value as contained by second storage. Used for comparison with test expected post state and alloc returned by the transition tool.

Source code in src/ethereum_test_tools/common/types.py
286
287
288
289
290
291
292
293
294
295
296
297
298
def contains(self, other: "Storage") -> bool:
    """
    Returns True if self contains all keys with equal value as
    contained by second storage.
    Used for comparison with test expected post state and alloc returned
    by the transition tool.
    """
    for key in other:
        if key not in self:
            return False
        if self[key] != other[key]:
            return False
    return True

must_contain(address, other)

Succeeds only if self contains all keys with equal value as contained by second storage. Used for comparison with test expected post state and alloc returned by the transition tool. Raises detailed exception when a difference is found.

Source code in src/ethereum_test_tools/common/types.py
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
def must_contain(self, address: Address, other: "Storage"):
    """
    Succeeds only if self contains all keys with equal value as
    contained by second storage.
    Used for comparison with test expected post state and alloc returned
    by the transition tool.
    Raises detailed exception when a difference is found.
    """
    for key in other:
        if key not in self:
            # storage[key]==0 is equal to missing storage
            if other[key] != 0:
                raise Storage.MissingKey(key=key)
        elif self[key] != other[key]:
            raise Storage.KeyValueMismatch(
                address=address, key=key, want=self[key], got=other[key]
            )

must_be_equal(address, other)

Succeeds only if "self" is equal to "other" storage.

Source code in src/ethereum_test_tools/common/types.py
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
def must_be_equal(self, address: Address, other: "Storage"):
    """
    Succeeds only if "self" is equal to "other" storage.
    """
    # Test keys contained in both storage objects
    for key in self.keys() & other.keys():
        if self[key] != other[key]:
            raise Storage.KeyValueMismatch(
                address=address, key=key, want=self[key], got=other[key]
            )

    # Test keys contained in either one of the storage objects
    for key in self.keys() ^ other.keys():
        if key in self:
            if self[key] != 0:
                raise Storage.KeyValueMismatch(address=address, key=key, want=self[key], got=0)

        elif other[key] != 0:
            raise Storage.KeyValueMismatch(address=address, key=key, want=0, got=other[key])

TestParameterGroup dataclass

Base class for grouping test parameters in a dataclass. Provides a generic repr method to generate clean test ids, including only non-default optional fields.

Source code in src/ethereum_test_tools/common/helpers.py
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
@dataclass(kw_only=True, frozen=True, repr=False)
class TestParameterGroup:
    """
    Base class for grouping test parameters in a dataclass. Provides a generic
    __repr__ method to generate clean test ids, including only non-default
    optional fields.
    """

    __test__ = False  # explicitly prevent pytest collecting this class

    def __repr__(self):
        """
        Generates a repr string, intended to be used as a test id, based on the class
        name and the values of the non-default optional fields.
        """
        class_name = self.__class__.__name__
        field_strings = []

        for field in fields(self):
            value = getattr(self, field.name)
            # Include the field only if it is not optional or not set to its default value
            if field.default is MISSING or field.default != value:
                field_strings.append(f"{field.name}_{value}")

        return f"{class_name}_{'-'.join(field_strings)}"

__repr__()

Generates a repr string, intended to be used as a test id, based on the class name and the values of the non-default optional fields.

Source code in src/ethereum_test_tools/common/helpers.py
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
def __repr__(self):
    """
    Generates a repr string, intended to be used as a test id, based on the class
    name and the values of the non-default optional fields.
    """
    class_name = self.__class__.__name__
    field_strings = []

    for field in fields(self):
        value = getattr(self, field.name)
        # Include the field only if it is not optional or not set to its default value
        if field.default is MISSING or field.default != value:
            field_strings.append(f"{field.name}_{value}")

    return f"{class_name}_{'-'.join(field_strings)}"

Transaction dataclass

Generic object that can represent all Ethereum transaction types.

Source code in src/ethereum_test_tools/common/types.py
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
@dataclass(kw_only=True)
class Transaction:
    """
    Generic object that can represent all Ethereum transaction types.
    """

    ty: Optional[int] = field(
        default=None,
        json_encoder=JSONEncoder.Field(
            name="type",
            cast_type=HexNumber,
        ),
    )
    """
    Transaction type value.
    """
    chain_id: int = field(
        default=1,
        json_encoder=JSONEncoder.Field(
            name="chainId",
            cast_type=HexNumber,
        ),
    )
    nonce: int = field(
        default=0,
        json_encoder=JSONEncoder.Field(
            cast_type=HexNumber,
        ),
    )
    gas_price: Optional[int] = field(
        default=None,
        json_encoder=JSONEncoder.Field(
            name="gasPrice",
            cast_type=HexNumber,
        ),
    )
    max_priority_fee_per_gas: Optional[int] = field(
        default=None,
        json_encoder=JSONEncoder.Field(
            name="maxPriorityFeePerGas",
            cast_type=HexNumber,
        ),
    )
    max_fee_per_gas: Optional[int] = field(
        default=None,
        json_encoder=JSONEncoder.Field(
            name="maxFeePerGas",
            cast_type=HexNumber,
        ),
    )
    gas_limit: int = field(
        default=21000,
        json_encoder=JSONEncoder.Field(
            name="gas",
            cast_type=HexNumber,
        ),
    )
    to: Optional[FixedSizeBytesConvertible | Address] = field(
        default=Address(0xAA),
        json_encoder=JSONEncoder.Field(
            cast_type=Address,
        ),
    )
    value: int = field(
        default=0,
        json_encoder=JSONEncoder.Field(
            cast_type=HexNumber,
        ),
    )
    data: BytesConvertible = field(
        default_factory=bytes,
        json_encoder=JSONEncoder.Field(
            name="input",
            cast_type=Bytes,
        ),
    )
    access_list: Optional[List[AccessList]] = field(
        default=None,
        json_encoder=JSONEncoder.Field(
            name="accessList",
            to_json=True,
        ),
    )
    max_fee_per_blob_gas: Optional[int] = field(
        default=None,
        json_encoder=JSONEncoder.Field(
            name="maxFeePerBlobGas",
            cast_type=HexNumber,
        ),
    )
    blob_versioned_hashes: Optional[Sequence[FixedSizeBytesConvertible]] = field(
        default=None,
        json_encoder=JSONEncoder.Field(
            name="blobVersionedHashes",
            cast_type=lambda x: [Hash(k) for k in x],
            to_json=True,
        ),
    )
    v: Optional[int] = field(
        default=None,
        json_encoder=JSONEncoder.Field(
            cast_type=HexNumber,
        ),
    )
    r: Optional[int] = field(
        default=None,
        json_encoder=JSONEncoder.Field(
            cast_type=HexNumber,
        ),
    )
    s: Optional[int] = field(
        default=None,
        json_encoder=JSONEncoder.Field(
            cast_type=HexNumber,
        ),
    )
    wrapped_blob_transaction: bool = field(
        default=False,
        json_encoder=JSONEncoder.Field(
            skip=True,
        ),
    )
    blobs: Optional[Sequence[bytes]] = field(
        default=None,
        json_encoder=JSONEncoder.Field(
            skip=True,
        ),
    )
    blob_kzg_commitments: Optional[Sequence[bytes]] = field(
        default=None,
        json_encoder=JSONEncoder.Field(
            skip=True,
        ),
    )
    blob_kzg_proofs: Optional[Sequence[bytes]] = field(
        default=None,
        json_encoder=JSONEncoder.Field(
            skip=True,
        ),
    )
    sender: Optional[FixedSizeBytesConvertible] = field(
        default=None,
        json_encoder=JSONEncoder.Field(
            cast_type=Address,
        ),
    )
    secret_key: Optional[FixedSizeBytesConvertible] = field(
        default=None,
        json_encoder=JSONEncoder.Field(
            name="secretKey",
            cast_type=Hash,
        ),
    )
    protected: bool = field(
        default=True,
        json_encoder=JSONEncoder.Field(
            skip=True,
        ),
    )
    error: Optional[TransactionException | ExceptionList] = field(
        default=None,
        json_encoder=JSONEncoder.Field(
            skip=True,
        ),
    )
    rlp: Optional[bytes] = field(
        default=None,
        json_encoder=JSONEncoder.Field(
            skip=True,
        ),
    )

    class InvalidFeePayment(Exception):
        """
        Transaction described more than one fee payment type.
        """

        def __str__(self):
            """Print exception string"""
            return "only one type of fee payment field can be used in a single tx"

    class InvalidSignaturePrivateKey(Exception):
        """
        Transaction describes both the signature and private key of
        source account.
        """

        def __str__(self):
            """Print exception string"""
            return "can't define both 'signature' and 'private_key'"

    def __post_init__(self) -> None:
        """
        Ensures the transaction has no conflicting properties.
        """
        if self.gas_price is not None and (
            self.max_fee_per_gas is not None
            or self.max_priority_fee_per_gas is not None
            or self.max_fee_per_blob_gas is not None
        ):
            raise Transaction.InvalidFeePayment()

        if (
            self.gas_price is None
            and self.max_fee_per_gas is None
            and self.max_priority_fee_per_gas is None
            and self.max_fee_per_blob_gas is None
        ):
            self.gas_price = 10

        if self.v is not None and self.secret_key is not None:
            raise Transaction.InvalidSignaturePrivateKey()

        if self.v is None and self.secret_key is None:
            self.secret_key = TestPrivateKey

        if self.ty is None:
            # Try to deduce transaction type from included fields
            if self.max_fee_per_blob_gas is not None:
                self.ty = 3
            elif self.max_fee_per_gas is not None:
                self.ty = 2
            elif self.access_list is not None:
                self.ty = 1
            else:
                self.ty = 0

        # Set default values for fields that are required for certain tx types
        if self.ty >= 1 and self.access_list is None:
            self.access_list = []

        if self.ty >= 2 and self.max_priority_fee_per_gas is None:
            self.max_priority_fee_per_gas = 0

    def with_error(self, error: TransactionException | ExceptionList) -> "Transaction":
        """
        Create a copy of the transaction with an added error.
        """
        tx = copy(self)
        tx.error = error
        return tx

    def with_nonce(self, nonce: int) -> "Transaction":
        """
        Create a copy of the transaction with a modified nonce.
        """
        tx = copy(self)
        tx.nonce = nonce
        return tx

    def with_fields(self, **kwargs) -> "Transaction":
        """
        Create a deepcopy of the transaction with modified fields.
        """
        tx = deepcopy(self)
        for key, value in kwargs.items():
            if hasattr(tx, key):
                setattr(tx, key, value)
            else:
                raise ValueError(f"Invalid field '{key}' for Transaction")
        return tx

    def payload_body(self) -> List[Any]:
        """
        Returns the list of values included in the transaction body.
        """
        if self.v is None or self.r is None or self.s is None:
            raise ValueError("signature must be set before serializing any tx type")

        if self.gas_limit is None:
            raise ValueError("gas_limit must be set for all tx types")
        to = Address(self.to) if self.to is not None else bytes()

        if self.ty == 3:
            # EIP-4844: https://eips.ethereum.org/EIPS/eip-4844
            if self.max_priority_fee_per_gas is None:
                raise ValueError("max_priority_fee_per_gas must be set for type 3 tx")
            if self.max_fee_per_gas is None:
                raise ValueError("max_fee_per_gas must be set for type 3 tx")
            if self.max_fee_per_blob_gas is None:
                raise ValueError("max_fee_per_blob_gas must be set for type 3 tx")
            if self.blob_versioned_hashes is None:
                raise ValueError("blob_versioned_hashes must be set for type 3 tx")
            if self.access_list is None:
                raise ValueError("access_list must be set for type 3 tx")

            if self.wrapped_blob_transaction:
                if self.blobs is None:
                    raise ValueError("blobs must be set for network version of type 3 tx")
                if self.blob_kzg_commitments is None:
                    raise ValueError(
                        "blob_kzg_commitments must be set for network version of type 3 tx"
                    )
                if self.blob_kzg_proofs is None:
                    raise ValueError(
                        "blob_kzg_proofs must be set for network version of type 3 tx"
                    )

                return [
                    [
                        Uint(self.chain_id),
                        Uint(self.nonce),
                        Uint(self.max_priority_fee_per_gas),
                        Uint(self.max_fee_per_gas),
                        Uint(self.gas_limit),
                        to,
                        Uint(self.value),
                        Bytes(self.data),
                        [a.to_list() for a in self.access_list],
                        Uint(self.max_fee_per_blob_gas),
                        [Hash(h) for h in self.blob_versioned_hashes],
                        Uint(self.v),
                        Uint(self.r),
                        Uint(self.s),
                    ],
                    self.blobs,
                    self.blob_kzg_commitments,
                    self.blob_kzg_proofs,
                ]
            else:
                return [
                    Uint(self.chain_id),
                    Uint(self.nonce),
                    Uint(self.max_priority_fee_per_gas),
                    Uint(self.max_fee_per_gas),
                    Uint(self.gas_limit),
                    to,
                    Uint(self.value),
                    Bytes(self.data),
                    [a.to_list() for a in self.access_list],
                    Uint(self.max_fee_per_blob_gas),
                    [Hash(h) for h in self.blob_versioned_hashes],
                    Uint(self.v),
                    Uint(self.r),
                    Uint(self.s),
                ]
        elif self.ty == 2:
            # EIP-1559: https://eips.ethereum.org/EIPS/eip-1559
            if self.max_priority_fee_per_gas is None:
                raise ValueError("max_priority_fee_per_gas must be set for type 2 tx")
            if self.max_fee_per_gas is None:
                raise ValueError("max_fee_per_gas must be set for type 2 tx")
            if self.access_list is None:
                raise ValueError("access_list must be set for type 2 tx")
            return [
                Uint(self.chain_id),
                Uint(self.nonce),
                Uint(self.max_priority_fee_per_gas),
                Uint(self.max_fee_per_gas),
                Uint(self.gas_limit),
                to,
                Uint(self.value),
                Bytes(self.data),
                [a.to_list() for a in self.access_list],
                Uint(self.v),
                Uint(self.r),
                Uint(self.s),
            ]
        elif self.ty == 1:
            # EIP-2930: https://eips.ethereum.org/EIPS/eip-2930
            if self.gas_price is None:
                raise ValueError("gas_price must be set for type 1 tx")
            if self.access_list is None:
                raise ValueError("access_list must be set for type 1 tx")

            return [
                Uint(self.chain_id),
                Uint(self.nonce),
                Uint(self.gas_price),
                Uint(self.gas_limit),
                to,
                Uint(self.value),
                Bytes(self.data),
                [a.to_list() for a in self.access_list],
                Uint(self.v),
                Uint(self.r),
                Uint(self.s),
            ]
        elif self.ty == 0:
            if self.gas_price is None:
                raise ValueError("gas_price must be set for type 0 tx")
            # EIP-155: https://eips.ethereum.org/EIPS/eip-155
            return [
                Uint(self.nonce),
                Uint(self.gas_price),
                Uint(self.gas_limit),
                to,
                Uint(self.value),
                Bytes(self.data),
                Uint(self.v),
                Uint(self.r),
                Uint(self.s),
            ]

        raise NotImplementedError(f"serialized_bytes not implemented for tx type {self.ty}")

    def serialized_bytes(self) -> bytes:
        """
        Returns bytes of the serialized representation of the transaction,
        which is almost always RLP encoding.
        """
        if self.rlp is not None:
            return self.rlp

        if self.ty is None:
            raise ValueError("ty must be set for all tx types")

        if self.ty > 0:
            return bytes([self.ty]) + eth_rlp.encode(self.payload_body())
        else:
            return eth_rlp.encode(self.payload_body())

    def signing_envelope(self) -> List[Any]:
        """
        Returns the list of values included in the envelope used for signing.
        """
        if self.gas_limit is None:
            raise ValueError("gas_limit must be set for all tx types")
        to = Address(self.to) if self.to is not None else bytes()

        if self.ty == 3:
            # EIP-4844: https://eips.ethereum.org/EIPS/eip-4844
            if self.max_priority_fee_per_gas is None:
                raise ValueError("max_priority_fee_per_gas must be set for type 3 tx")
            if self.max_fee_per_gas is None:
                raise ValueError("max_fee_per_gas must be set for type 3 tx")
            if self.max_fee_per_blob_gas is None:
                raise ValueError("max_fee_per_blob_gas must be set for type 3 tx")
            if self.blob_versioned_hashes is None:
                raise ValueError("blob_versioned_hashes must be set for type 3 tx")
            return [
                Uint(self.chain_id),
                Uint(self.nonce),
                Uint(self.max_priority_fee_per_gas),
                Uint(self.max_fee_per_gas),
                Uint(self.gas_limit),
                to,
                Uint(self.value),
                Bytes(self.data),
                [a.to_list() for a in self.access_list] if self.access_list is not None else [],
                Uint(self.max_fee_per_blob_gas),
                [Hash(h) for h in self.blob_versioned_hashes],
            ]
        elif self.ty == 2:
            # EIP-1559: https://eips.ethereum.org/EIPS/eip-1559
            if self.max_priority_fee_per_gas is None:
                raise ValueError("max_priority_fee_per_gas must be set for type 2 tx")
            if self.max_fee_per_gas is None:
                raise ValueError("max_fee_per_gas must be set for type 2 tx")
            return [
                Uint(self.chain_id),
                Uint(self.nonce),
                Uint(self.max_priority_fee_per_gas),
                Uint(self.max_fee_per_gas),
                Uint(self.gas_limit),
                to,
                Uint(self.value),
                Bytes(self.data),
                [a.to_list() for a in self.access_list] if self.access_list is not None else [],
            ]
        elif self.ty == 1:
            # EIP-2930: https://eips.ethereum.org/EIPS/eip-2930
            if self.gas_price is None:
                raise ValueError("gas_price must be set for type 1 tx")

            return [
                Uint(self.chain_id),
                Uint(self.nonce),
                Uint(self.gas_price),
                Uint(self.gas_limit),
                to,
                Uint(self.value),
                Bytes(self.data),
                [a.to_list() for a in self.access_list] if self.access_list is not None else [],
            ]
        elif self.ty == 0:
            if self.gas_price is None:
                raise ValueError("gas_price must be set for type 0 tx")

            if self.protected:
                # EIP-155: https://eips.ethereum.org/EIPS/eip-155
                return [
                    Uint(self.nonce),
                    Uint(self.gas_price),
                    Uint(self.gas_limit),
                    to,
                    Uint(self.value),
                    Bytes(self.data),
                    Uint(self.chain_id),
                    Uint(0),
                    Uint(0),
                ]
            else:
                return [
                    Uint(self.nonce),
                    Uint(self.gas_price),
                    Uint(self.gas_limit),
                    to,
                    Uint(self.value),
                    Bytes(self.data),
                ]
        raise NotImplementedError("signing for transaction type {self.ty} not implemented")

    def signing_bytes(self) -> bytes:
        """
        Returns the serialized bytes of the transaction used for signing.
        """
        if self.ty is None:
            raise ValueError("ty must be set for all tx types")

        if self.ty > 0:
            return bytes([self.ty]) + eth_rlp.encode(self.signing_envelope())
        else:
            return eth_rlp.encode(self.signing_envelope())

    def signature_bytes(self) -> bytes:
        """
        Returns the serialized bytes of the transaction signature.
        """
        assert self.v is not None and self.r is not None and self.s is not None
        v = self.v
        if self.ty == 0:
            if self.protected:
                assert self.chain_id is not None
                v -= 35 + (self.chain_id * 2)
            else:
                v -= 27
        return (
            self.r.to_bytes(32, byteorder="big")
            + self.s.to_bytes(32, byteorder="big")
            + bytes([v])
        )

    def with_signature_and_sender(self, *, keep_secret_key: bool = False) -> "Transaction":
        """
        Returns a signed version of the transaction using the private key.
        """
        tx = copy(self)

        if tx.v is not None:
            # Transaction already signed
            if tx.sender is None:
                public_key = PublicKey.from_signature_and_message(
                    tx.signature_bytes(), keccak256(tx.signing_bytes()), hasher=None
                )
                tx.sender = keccak256(public_key.format(compressed=False)[1:])[32 - 20 :]
            return tx

        if tx.secret_key is None:
            raise ValueError("secret_key must be set to sign a transaction")

        # Get the signing bytes
        signing_hash = keccak256(tx.signing_bytes())

        # Sign the bytes

        private_key = PrivateKey(
            secret=Hash(tx.secret_key) if tx.secret_key is not None else bytes(32)
        )
        signature_bytes = private_key.sign_recoverable(signing_hash, hasher=None)
        public_key = PublicKey.from_signature_and_message(
            signature_bytes, signing_hash, hasher=None
        )
        tx.sender = keccak256(public_key.format(compressed=False)[1:])[32 - 20 :]

        tx.v, tx.r, tx.s = (
            signature_bytes[64],
            int.from_bytes(signature_bytes[0:32], byteorder="big"),
            int.from_bytes(signature_bytes[32:64], byteorder="big"),
        )
        if tx.ty == 0:
            if tx.protected:
                tx.v += 35 + (tx.chain_id * 2)
            else:  # not protected
                tx.v += 27

        # Remove the secret key if requested
        if not keep_secret_key:
            tx.secret_key = None
        return tx

ty: Optional[int] = field(default=None, json_encoder=JSONEncoder.Field(name='type', cast_type=HexNumber)) class-attribute instance-attribute

Transaction type value.

InvalidFeePayment

Bases: Exception

Transaction described more than one fee payment type.

Source code in src/ethereum_test_tools/common/types.py
1131
1132
1133
1134
1135
1136
1137
1138
class InvalidFeePayment(Exception):
    """
    Transaction described more than one fee payment type.
    """

    def __str__(self):
        """Print exception string"""
        return "only one type of fee payment field can be used in a single tx"

__str__()

Print exception string

Source code in src/ethereum_test_tools/common/types.py
1136
1137
1138
def __str__(self):
    """Print exception string"""
    return "only one type of fee payment field can be used in a single tx"

InvalidSignaturePrivateKey

Bases: Exception

Transaction describes both the signature and private key of source account.

Source code in src/ethereum_test_tools/common/types.py
1140
1141
1142
1143
1144
1145
1146
1147
1148
class InvalidSignaturePrivateKey(Exception):
    """
    Transaction describes both the signature and private key of
    source account.
    """

    def __str__(self):
        """Print exception string"""
        return "can't define both 'signature' and 'private_key'"

__str__()

Print exception string

Source code in src/ethereum_test_tools/common/types.py
1146
1147
1148
def __str__(self):
    """Print exception string"""
    return "can't define both 'signature' and 'private_key'"

__post_init__()

Ensures the transaction has no conflicting properties.

Source code in src/ethereum_test_tools/common/types.py
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
def __post_init__(self) -> None:
    """
    Ensures the transaction has no conflicting properties.
    """
    if self.gas_price is not None and (
        self.max_fee_per_gas is not None
        or self.max_priority_fee_per_gas is not None
        or self.max_fee_per_blob_gas is not None
    ):
        raise Transaction.InvalidFeePayment()

    if (
        self.gas_price is None
        and self.max_fee_per_gas is None
        and self.max_priority_fee_per_gas is None
        and self.max_fee_per_blob_gas is None
    ):
        self.gas_price = 10

    if self.v is not None and self.secret_key is not None:
        raise Transaction.InvalidSignaturePrivateKey()

    if self.v is None and self.secret_key is None:
        self.secret_key = TestPrivateKey

    if self.ty is None:
        # Try to deduce transaction type from included fields
        if self.max_fee_per_blob_gas is not None:
            self.ty = 3
        elif self.max_fee_per_gas is not None:
            self.ty = 2
        elif self.access_list is not None:
            self.ty = 1
        else:
            self.ty = 0

    # Set default values for fields that are required for certain tx types
    if self.ty >= 1 and self.access_list is None:
        self.access_list = []

    if self.ty >= 2 and self.max_priority_fee_per_gas is None:
        self.max_priority_fee_per_gas = 0

with_error(error)

Create a copy of the transaction with an added error.

Source code in src/ethereum_test_tools/common/types.py
1193
1194
1195
1196
1197
1198
1199
def with_error(self, error: TransactionException | ExceptionList) -> "Transaction":
    """
    Create a copy of the transaction with an added error.
    """
    tx = copy(self)
    tx.error = error
    return tx

with_nonce(nonce)

Create a copy of the transaction with a modified nonce.

Source code in src/ethereum_test_tools/common/types.py
1201
1202
1203
1204
1205
1206
1207
def with_nonce(self, nonce: int) -> "Transaction":
    """
    Create a copy of the transaction with a modified nonce.
    """
    tx = copy(self)
    tx.nonce = nonce
    return tx

with_fields(**kwargs)

Create a deepcopy of the transaction with modified fields.

Source code in src/ethereum_test_tools/common/types.py
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
def with_fields(self, **kwargs) -> "Transaction":
    """
    Create a deepcopy of the transaction with modified fields.
    """
    tx = deepcopy(self)
    for key, value in kwargs.items():
        if hasattr(tx, key):
            setattr(tx, key, value)
        else:
            raise ValueError(f"Invalid field '{key}' for Transaction")
    return tx

payload_body()

Returns the list of values included in the transaction body.

Source code in src/ethereum_test_tools/common/types.py
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
def payload_body(self) -> List[Any]:
    """
    Returns the list of values included in the transaction body.
    """
    if self.v is None or self.r is None or self.s is None:
        raise ValueError("signature must be set before serializing any tx type")

    if self.gas_limit is None:
        raise ValueError("gas_limit must be set for all tx types")
    to = Address(self.to) if self.to is not None else bytes()

    if self.ty == 3:
        # EIP-4844: https://eips.ethereum.org/EIPS/eip-4844
        if self.max_priority_fee_per_gas is None:
            raise ValueError("max_priority_fee_per_gas must be set for type 3 tx")
        if self.max_fee_per_gas is None:
            raise ValueError("max_fee_per_gas must be set for type 3 tx")
        if self.max_fee_per_blob_gas is None:
            raise ValueError("max_fee_per_blob_gas must be set for type 3 tx")
        if self.blob_versioned_hashes is None:
            raise ValueError("blob_versioned_hashes must be set for type 3 tx")
        if self.access_list is None:
            raise ValueError("access_list must be set for type 3 tx")

        if self.wrapped_blob_transaction:
            if self.blobs is None:
                raise ValueError("blobs must be set for network version of type 3 tx")
            if self.blob_kzg_commitments is None:
                raise ValueError(
                    "blob_kzg_commitments must be set for network version of type 3 tx"
                )
            if self.blob_kzg_proofs is None:
                raise ValueError(
                    "blob_kzg_proofs must be set for network version of type 3 tx"
                )

            return [
                [
                    Uint(self.chain_id),
                    Uint(self.nonce),
                    Uint(self.max_priority_fee_per_gas),
                    Uint(self.max_fee_per_gas),
                    Uint(self.gas_limit),
                    to,
                    Uint(self.value),
                    Bytes(self.data),
                    [a.to_list() for a in self.access_list],
                    Uint(self.max_fee_per_blob_gas),
                    [Hash(h) for h in self.blob_versioned_hashes],
                    Uint(self.v),
                    Uint(self.r),
                    Uint(self.s),
                ],
                self.blobs,
                self.blob_kzg_commitments,
                self.blob_kzg_proofs,
            ]
        else:
            return [
                Uint(self.chain_id),
                Uint(self.nonce),
                Uint(self.max_priority_fee_per_gas),
                Uint(self.max_fee_per_gas),
                Uint(self.gas_limit),
                to,
                Uint(self.value),
                Bytes(self.data),
                [a.to_list() for a in self.access_list],
                Uint(self.max_fee_per_blob_gas),
                [Hash(h) for h in self.blob_versioned_hashes],
                Uint(self.v),
                Uint(self.r),
                Uint(self.s),
            ]
    elif self.ty == 2:
        # EIP-1559: https://eips.ethereum.org/EIPS/eip-1559
        if self.max_priority_fee_per_gas is None:
            raise ValueError("max_priority_fee_per_gas must be set for type 2 tx")
        if self.max_fee_per_gas is None:
            raise ValueError("max_fee_per_gas must be set for type 2 tx")
        if self.access_list is None:
            raise ValueError("access_list must be set for type 2 tx")
        return [
            Uint(self.chain_id),
            Uint(self.nonce),
            Uint(self.max_priority_fee_per_gas),
            Uint(self.max_fee_per_gas),
            Uint(self.gas_limit),
            to,
            Uint(self.value),
            Bytes(self.data),
            [a.to_list() for a in self.access_list],
            Uint(self.v),
            Uint(self.r),
            Uint(self.s),
        ]
    elif self.ty == 1:
        # EIP-2930: https://eips.ethereum.org/EIPS/eip-2930
        if self.gas_price is None:
            raise ValueError("gas_price must be set for type 1 tx")
        if self.access_list is None:
            raise ValueError("access_list must be set for type 1 tx")

        return [
            Uint(self.chain_id),
            Uint(self.nonce),
            Uint(self.gas_price),
            Uint(self.gas_limit),
            to,
            Uint(self.value),
            Bytes(self.data),
            [a.to_list() for a in self.access_list],
            Uint(self.v),
            Uint(self.r),
            Uint(self.s),
        ]
    elif self.ty == 0:
        if self.gas_price is None:
            raise ValueError("gas_price must be set for type 0 tx")
        # EIP-155: https://eips.ethereum.org/EIPS/eip-155
        return [
            Uint(self.nonce),
            Uint(self.gas_price),
            Uint(self.gas_limit),
            to,
            Uint(self.value),
            Bytes(self.data),
            Uint(self.v),
            Uint(self.r),
            Uint(self.s),
        ]

    raise NotImplementedError(f"serialized_bytes not implemented for tx type {self.ty}")

serialized_bytes()

Returns bytes of the serialized representation of the transaction, which is almost always RLP encoding.

Source code in src/ethereum_test_tools/common/types.py
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
def serialized_bytes(self) -> bytes:
    """
    Returns bytes of the serialized representation of the transaction,
    which is almost always RLP encoding.
    """
    if self.rlp is not None:
        return self.rlp

    if self.ty is None:
        raise ValueError("ty must be set for all tx types")

    if self.ty > 0:
        return bytes([self.ty]) + eth_rlp.encode(self.payload_body())
    else:
        return eth_rlp.encode(self.payload_body())

signing_envelope()

Returns the list of values included in the envelope used for signing.

Source code in src/ethereum_test_tools/common/types.py
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
def signing_envelope(self) -> List[Any]:
    """
    Returns the list of values included in the envelope used for signing.
    """
    if self.gas_limit is None:
        raise ValueError("gas_limit must be set for all tx types")
    to = Address(self.to) if self.to is not None else bytes()

    if self.ty == 3:
        # EIP-4844: https://eips.ethereum.org/EIPS/eip-4844
        if self.max_priority_fee_per_gas is None:
            raise ValueError("max_priority_fee_per_gas must be set for type 3 tx")
        if self.max_fee_per_gas is None:
            raise ValueError("max_fee_per_gas must be set for type 3 tx")
        if self.max_fee_per_blob_gas is None:
            raise ValueError("max_fee_per_blob_gas must be set for type 3 tx")
        if self.blob_versioned_hashes is None:
            raise ValueError("blob_versioned_hashes must be set for type 3 tx")
        return [
            Uint(self.chain_id),
            Uint(self.nonce),
            Uint(self.max_priority_fee_per_gas),
            Uint(self.max_fee_per_gas),
            Uint(self.gas_limit),
            to,
            Uint(self.value),
            Bytes(self.data),
            [a.to_list() for a in self.access_list] if self.access_list is not None else [],
            Uint(self.max_fee_per_blob_gas),
            [Hash(h) for h in self.blob_versioned_hashes],
        ]
    elif self.ty == 2:
        # EIP-1559: https://eips.ethereum.org/EIPS/eip-1559
        if self.max_priority_fee_per_gas is None:
            raise ValueError("max_priority_fee_per_gas must be set for type 2 tx")
        if self.max_fee_per_gas is None:
            raise ValueError("max_fee_per_gas must be set for type 2 tx")
        return [
            Uint(self.chain_id),
            Uint(self.nonce),
            Uint(self.max_priority_fee_per_gas),
            Uint(self.max_fee_per_gas),
            Uint(self.gas_limit),
            to,
            Uint(self.value),
            Bytes(self.data),
            [a.to_list() for a in self.access_list] if self.access_list is not None else [],
        ]
    elif self.ty == 1:
        # EIP-2930: https://eips.ethereum.org/EIPS/eip-2930
        if self.gas_price is None:
            raise ValueError("gas_price must be set for type 1 tx")

        return [
            Uint(self.chain_id),
            Uint(self.nonce),
            Uint(self.gas_price),
            Uint(self.gas_limit),
            to,
            Uint(self.value),
            Bytes(self.data),
            [a.to_list() for a in self.access_list] if self.access_list is not None else [],
        ]
    elif self.ty == 0:
        if self.gas_price is None:
            raise ValueError("gas_price must be set for type 0 tx")

        if self.protected:
            # EIP-155: https://eips.ethereum.org/EIPS/eip-155
            return [
                Uint(self.nonce),
                Uint(self.gas_price),
                Uint(self.gas_limit),
                to,
                Uint(self.value),
                Bytes(self.data),
                Uint(self.chain_id),
                Uint(0),
                Uint(0),
            ]
        else:
            return [
                Uint(self.nonce),
                Uint(self.gas_price),
                Uint(self.gas_limit),
                to,
                Uint(self.value),
                Bytes(self.data),
            ]
    raise NotImplementedError("signing for transaction type {self.ty} not implemented")

signing_bytes()

Returns the serialized bytes of the transaction used for signing.

Source code in src/ethereum_test_tools/common/types.py
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
def signing_bytes(self) -> bytes:
    """
    Returns the serialized bytes of the transaction used for signing.
    """
    if self.ty is None:
        raise ValueError("ty must be set for all tx types")

    if self.ty > 0:
        return bytes([self.ty]) + eth_rlp.encode(self.signing_envelope())
    else:
        return eth_rlp.encode(self.signing_envelope())

signature_bytes()

Returns the serialized bytes of the transaction signature.

Source code in src/ethereum_test_tools/common/types.py
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
def signature_bytes(self) -> bytes:
    """
    Returns the serialized bytes of the transaction signature.
    """
    assert self.v is not None and self.r is not None and self.s is not None
    v = self.v
    if self.ty == 0:
        if self.protected:
            assert self.chain_id is not None
            v -= 35 + (self.chain_id * 2)
        else:
            v -= 27
    return (
        self.r.to_bytes(32, byteorder="big")
        + self.s.to_bytes(32, byteorder="big")
        + bytes([v])
    )

with_signature_and_sender(*, keep_secret_key=False)

Returns a signed version of the transaction using the private key.

Source code in src/ethereum_test_tools/common/types.py
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
def with_signature_and_sender(self, *, keep_secret_key: bool = False) -> "Transaction":
    """
    Returns a signed version of the transaction using the private key.
    """
    tx = copy(self)

    if tx.v is not None:
        # Transaction already signed
        if tx.sender is None:
            public_key = PublicKey.from_signature_and_message(
                tx.signature_bytes(), keccak256(tx.signing_bytes()), hasher=None
            )
            tx.sender = keccak256(public_key.format(compressed=False)[1:])[32 - 20 :]
        return tx

    if tx.secret_key is None:
        raise ValueError("secret_key must be set to sign a transaction")

    # Get the signing bytes
    signing_hash = keccak256(tx.signing_bytes())

    # Sign the bytes

    private_key = PrivateKey(
        secret=Hash(tx.secret_key) if tx.secret_key is not None else bytes(32)
    )
    signature_bytes = private_key.sign_recoverable(signing_hash, hasher=None)
    public_key = PublicKey.from_signature_and_message(
        signature_bytes, signing_hash, hasher=None
    )
    tx.sender = keccak256(public_key.format(compressed=False)[1:])[32 - 20 :]

    tx.v, tx.r, tx.s = (
        signature_bytes[64],
        int.from_bytes(signature_bytes[0:32], byteorder="big"),
        int.from_bytes(signature_bytes[32:64], byteorder="big"),
    )
    if tx.ty == 0:
        if tx.protected:
            tx.v += 35 + (tx.chain_id * 2)
        else:  # not protected
            tx.v += 27

    # Remove the secret key if requested
    if not keep_secret_key:
        tx.secret_key = None
    return tx

Withdrawal dataclass

Structure to represent a single withdrawal of a validator's balance from the beacon chain.

Source code in src/ethereum_test_tools/common/types.py
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
@dataclass(kw_only=True)
class Withdrawal:
    """
    Structure to represent a single withdrawal of a validator's balance from
    the beacon chain.
    """

    index: NumberConvertible = field(
        json_encoder=JSONEncoder.Field(
            cast_type=HexNumber,
        ),
    )
    validator: NumberConvertible = field(
        json_encoder=JSONEncoder.Field(
            name="validatorIndex",
            cast_type=HexNumber,
        ),
    )
    address: FixedSizeBytesConvertible = field(
        json_encoder=JSONEncoder.Field(
            cast_type=Address,
        ),
    )
    amount: NumberConvertible = field(
        json_encoder=JSONEncoder.Field(
            cast_type=HexNumber,
        ),
    )

    def to_serializable_list(self) -> List[Any]:
        """
        Returns a list of the withdrawal's attributes in the order they should
        be serialized.
        """
        return [
            Uint(Number(self.index)),
            Uint(Number(self.validator)),
            Address(self.address),
            Uint(Number(self.amount)),
        ]

to_serializable_list()

Returns a list of the withdrawal's attributes in the order they should be serialized.

Source code in src/ethereum_test_tools/common/types.py
687
688
689
690
691
692
693
694
695
696
697
def to_serializable_list(self) -> List[Any]:
    """
    Returns a list of the withdrawal's attributes in the order they should
    be serialized.
    """
    return [
        Uint(Number(self.index)),
        Uint(Number(self.validator)),
        Address(self.address),
        Uint(Number(self.amount)),
    ]

add_kzg_version(b_hashes, kzg_version)

Adds the Kzg Version to each blob hash.

Source code in src/ethereum_test_tools/common/helpers.py
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
def add_kzg_version(
    b_hashes: List[bytes | SupportsBytes | int | str], kzg_version: int
) -> List[bytes]:
    """
    Adds the Kzg Version to each blob hash.
    """
    kzg_version_hex = bytes([kzg_version])
    kzg_versioned_hashes = []

    for hash in b_hashes:
        hash = bytes(Hash(hash))
        if isinstance(hash, int) or isinstance(hash, str):
            kzg_versioned_hashes.append(kzg_version_hex + hash[1:])
        elif isinstance(hash, bytes) or isinstance(hash, SupportsBytes):
            if isinstance(hash, SupportsBytes):
                hash = bytes(hash)
            kzg_versioned_hashes.append(kzg_version_hex + hash[1:])
        else:
            raise TypeError("Blob hash must be either an integer, string or bytes")
    return kzg_versioned_hashes

ceiling_division(a, b)

Calculates the ceil without using floating point. Used by many of the EVM's formulas

Source code in src/ethereum_test_tools/common/helpers.py
19
20
21
22
23
24
def ceiling_division(a: int, b: int) -> int:
    """
    Calculates the ceil without using floating point.
    Used by many of the EVM's formulas
    """
    return -(a // -b)

compute_create2_address(address, salt, initcode)

Compute address of the resulting contract created using the CREATE2 opcode.

Source code in src/ethereum_test_tools/common/helpers.py
37
38
39
40
41
42
43
44
45
def compute_create2_address(
    address: FixedSizeBytesConvertible, salt: FixedSizeBytesConvertible, initcode: BytesConvertible
) -> Address:
    """
    Compute address of the resulting contract created using the `CREATE2`
    opcode.
    """
    hash = keccak256(b"\xff" + Address(address) + Hash(salt) + keccak256(Bytes(initcode)))
    return Address(hash[-20:])

compute_create_address(address, nonce)

Compute address of the resulting contract created using a transaction or the CREATE opcode.

Source code in src/ethereum_test_tools/common/helpers.py
27
28
29
30
31
32
33
34
def compute_create_address(address: FixedSizeBytesConvertible, nonce: int) -> Address:
    """
    Compute address of the resulting contract created using a transaction
    or the `CREATE` opcode.
    """
    nonce_bytes = bytes() if nonce == 0 else nonce.to_bytes(length=1, byteorder="big")
    hash = keccak256(encode([Address(address), nonce_bytes]))
    return Address(hash[-20:])

copy_opcode_cost(length)

Calculates the cost of the COPY opcodes, assuming memory expansion from empty memory, based on the costs specified in the yellow paper: https://ethereum.github.io/yellowpaper/paper.pdf

Source code in src/ethereum_test_tools/common/helpers.py
65
66
67
68
69
70
71
def copy_opcode_cost(length: int) -> int:
    """
    Calculates the cost of the COPY opcodes, assuming memory expansion from
    empty memory, based on the costs specified in the yellow paper:
    https://ethereum.github.io/yellowpaper/paper.pdf
    """
    return 3 + (ceiling_division(length, 32) * 3) + cost_memory_bytes(length, 0)

cost_memory_bytes(new_bytes, previous_bytes)

Calculates the cost of memory expansion, based on the costs specified in the yellow paper: https://ethereum.github.io/yellowpaper/paper.pdf

Source code in src/ethereum_test_tools/common/helpers.py
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
def cost_memory_bytes(new_bytes: int, previous_bytes: int) -> int:
    """
    Calculates the cost of memory expansion, based on the costs specified in
    the yellow paper: https://ethereum.github.io/yellowpaper/paper.pdf
    """
    if new_bytes <= previous_bytes:
        return 0
    new_words = ceiling_division(new_bytes, 32)
    previous_words = ceiling_division(previous_bytes, 32)

    def c(w: int) -> int:
        g_memory = 3
        return (g_memory * w) + ((w * w) // 512)

    return c(new_words) - c(previous_words)

eip_2028_transaction_data_cost(data)

Calculates the cost of a given data as part of a transaction, based on the costs specified in EIP-2028: https://eips.ethereum.org/EIPS/eip-2028

Source code in src/ethereum_test_tools/common/helpers.py
74
75
76
77
78
79
80
81
82
83
84
85
def eip_2028_transaction_data_cost(data: BytesConvertible) -> int:
    """
    Calculates the cost of a given data as part of a transaction, based on the
    costs specified in EIP-2028: https://eips.ethereum.org/EIPS/eip-2028
    """
    cost = 0
    for b in Bytes(data):
        if b == 0:
            cost += 4
        else:
            cost += 16
    return cost

transaction_list_root(input_txs)

Returns the transactions root of a list of transactions.

Source code in src/ethereum_test_tools/common/types.py
1541
1542
1543
1544
1545
1546
1547
1548
def transaction_list_root(input_txs: List[Transaction] | None) -> Hash:
    """
    Returns the transactions root of a list of transactions.
    """
    t = HexaryTrie(db={})
    for i, tx in enumerate(input_txs or []):
        t.set(eth_rlp.encode(Uint(i)), tx.serialized_bytes())
    return Hash(t.root_hash)

BlockException

Bases: ExceptionBase

Exception raised when a block is invalid, but not due to a transaction.

E.g. all transactions in the block are valid, and can be applied to the state, but the block header contains an invalid field.

Source code in src/ethereum_test_tools/exceptions/exceptions.py
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
@unique
class BlockException(ExceptionBase):
    """
    Exception raised when a block is invalid, but not due to a transaction.

    E.g. all transactions in the block are valid, and can be applied to the state, but the
    block header contains an invalid field.
    """

    INCORRECT_BLOCK_FORMAT = auto()
    """
    Block's format is incorrect, contains invalid fields, is missing fields, or contains fields of
    a fork that is not active yet.
    """
    BLOB_GAS_USED_ABOVE_LIMIT = auto()
    """
    Block's blob gas used in header is above the limit.
    """
    INCORRECT_BLOB_GAS_USED = auto()
    """
    Block's blob gas used in header is incorrect.
    """
    INCORRECT_EXCESS_BLOB_GAS = auto()
    """
    Block's excess blob gas in header is incorrect.
    """
    RLP_STRUCTURES_ENCODING = auto()
    """
    Block's rlp encoding is valid but ethereum structures in it are invalid
    """

INCORRECT_BLOCK_FORMAT = auto() class-attribute instance-attribute

Block's format is incorrect, contains invalid fields, is missing fields, or contains fields of a fork that is not active yet.

BLOB_GAS_USED_ABOVE_LIMIT = auto() class-attribute instance-attribute

Block's blob gas used in header is above the limit.

INCORRECT_BLOB_GAS_USED = auto() class-attribute instance-attribute

Block's blob gas used in header is incorrect.

INCORRECT_EXCESS_BLOB_GAS = auto() class-attribute instance-attribute

Block's excess blob gas in header is incorrect.

RLP_STRUCTURES_ENCODING = auto() class-attribute instance-attribute

Block's rlp encoding is valid but ethereum structures in it are invalid

ExceptionList

Bases: list

A list of exceptions.

Source code in src/ethereum_test_tools/exceptions/exceptions.py
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class ExceptionList(list):
    """
    A list of exceptions.
    """

    def __init__(self, *exceptions: "ExceptionBase") -> None:
        """
        Create a new ExceptionList.
        """
        exceptions_set: List[ExceptionBase] = []
        for exception in exceptions:
            if not isinstance(exception, ExceptionBase):
                raise TypeError(f"Expected ExceptionBase, got {type(exception)}")
            if exception not in exceptions_set:
                exceptions_set.append(exception)
        super().__init__(exceptions_set)

    def __or__(self, other: Union["ExceptionBase", "ExceptionList"]) -> "ExceptionList":
        """
        Combine two ExceptionLists.
        """
        if isinstance(other, list):
            return ExceptionList(*(self + other))
        return ExceptionList(*(self + [other]))

    def __str__(self) -> str:
        """
        String representation of the ExceptionList.
        """
        return "|".join(str(exception) for exception in self)

__init__(*exceptions)

Create a new ExceptionList.

Source code in src/ethereum_test_tools/exceptions/exceptions.py
14
15
16
17
18
19
20
21
22
23
24
def __init__(self, *exceptions: "ExceptionBase") -> None:
    """
    Create a new ExceptionList.
    """
    exceptions_set: List[ExceptionBase] = []
    for exception in exceptions:
        if not isinstance(exception, ExceptionBase):
            raise TypeError(f"Expected ExceptionBase, got {type(exception)}")
        if exception not in exceptions_set:
            exceptions_set.append(exception)
    super().__init__(exceptions_set)

__or__(other)

Combine two ExceptionLists.

Source code in src/ethereum_test_tools/exceptions/exceptions.py
26
27
28
29
30
31
32
def __or__(self, other: Union["ExceptionBase", "ExceptionList"]) -> "ExceptionList":
    """
    Combine two ExceptionLists.
    """
    if isinstance(other, list):
        return ExceptionList(*(self + other))
    return ExceptionList(*(self + [other]))

__str__()

String representation of the ExceptionList.

Source code in src/ethereum_test_tools/exceptions/exceptions.py
34
35
36
37
38
def __str__(self) -> str:
    """
    String representation of the ExceptionList.
    """
    return "|".join(str(exception) for exception in self)

TransactionException

Bases: ExceptionBase

Exception raised when a transaction is invalid, and thus cannot be executed.

If a transaction with any of these exceptions is included in a block, the block is invalid.

Source code in src/ethereum_test_tools/exceptions/exceptions.py
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
@unique
class TransactionException(ExceptionBase):
    """
    Exception raised when a transaction is invalid, and thus cannot be executed.

    If a transaction with any of these exceptions is included in a block, the block is invalid.
    """

    INSUFFICIENT_ACCOUNT_FUNDS = auto()
    """
    Transaction's sender does not have enough funds to pay for the transaction.
    """
    INSUFFICIENT_MAX_FEE_PER_GAS = auto()
    """
    Transaction's max-fee-per-gas is lower than the block base-fee.
    """
    PRIORITY_GREATER_THAN_MAX_FEE_PER_GAS = auto()
    """
    Transaction's max-priority-fee-per-gas is greater than the max-fee-per-gas.
    """
    INSUFFICIENT_MAX_FEE_PER_BLOB_GAS = auto()
    """
    Transaction's max-fee-per-blob-gas is lower than the block's blob-gas price.
    """
    INTRINSIC_GAS_TOO_LOW = auto()
    """
    Transaction's gas limit is too low.
    """
    INITCODE_SIZE_EXCEEDED = auto()
    """
    Transaction's initcode for a contract-creating transaction is too large.
    """
    TYPE_3_TX_PRE_FORK = auto()
    """
    Transaction type 3 included before activation fork.
    """
    TYPE_3_TX_ZERO_BLOBS_PRE_FORK = auto()
    """
    Transaction type 3, with zero blobs, included before activation fork.
    """
    TYPE_3_TX_INVALID_BLOB_VERSIONED_HASH = auto()
    """
    Transaction contains a blob versioned hash with an invalid version.
    """
    TYPE_3_TX_WITH_FULL_BLOBS = auto()
    """
    Transaction contains full blobs (network-version of the transaction).
    """
    TYPE_3_TX_BLOB_COUNT_EXCEEDED = auto()
    """
    Transaction contains too many blob versioned hashes.
    """
    TYPE_3_TX_CONTRACT_CREATION = auto()
    """
    Transaction is a type 3 transaction and has an empty `to`.
    """
    TYPE_3_TX_MAX_BLOB_GAS_ALLOWANCE_EXCEEDED = auto()
    """
    Transaction causes block to go over blob gas limit.
    """
    TYPE_3_TX_ZERO_BLOBS = auto()
    """
    Transaction is type 3, but has no blobs.
    """

INSUFFICIENT_ACCOUNT_FUNDS = auto() class-attribute instance-attribute

Transaction's sender does not have enough funds to pay for the transaction.

INSUFFICIENT_MAX_FEE_PER_GAS = auto() class-attribute instance-attribute

Transaction's max-fee-per-gas is lower than the block base-fee.

PRIORITY_GREATER_THAN_MAX_FEE_PER_GAS = auto() class-attribute instance-attribute

Transaction's max-priority-fee-per-gas is greater than the max-fee-per-gas.

INSUFFICIENT_MAX_FEE_PER_BLOB_GAS = auto() class-attribute instance-attribute

Transaction's max-fee-per-blob-gas is lower than the block's blob-gas price.

INTRINSIC_GAS_TOO_LOW = auto() class-attribute instance-attribute

Transaction's gas limit is too low.

INITCODE_SIZE_EXCEEDED = auto() class-attribute instance-attribute

Transaction's initcode for a contract-creating transaction is too large.

TYPE_3_TX_PRE_FORK = auto() class-attribute instance-attribute

Transaction type 3 included before activation fork.

TYPE_3_TX_ZERO_BLOBS_PRE_FORK = auto() class-attribute instance-attribute

Transaction type 3, with zero blobs, included before activation fork.

TYPE_3_TX_INVALID_BLOB_VERSIONED_HASH = auto() class-attribute instance-attribute

Transaction contains a blob versioned hash with an invalid version.

TYPE_3_TX_WITH_FULL_BLOBS = auto() class-attribute instance-attribute

Transaction contains full blobs (network-version of the transaction).

TYPE_3_TX_BLOB_COUNT_EXCEEDED = auto() class-attribute instance-attribute

Transaction contains too many blob versioned hashes.

TYPE_3_TX_CONTRACT_CREATION = auto() class-attribute instance-attribute

Transaction is a type 3 transaction and has an empty to.

TYPE_3_TX_MAX_BLOB_GAS_ALLOWANCE_EXCEEDED = auto() class-attribute instance-attribute

Transaction causes block to go over blob gas limit.

TYPE_3_TX_ZERO_BLOBS = auto() class-attribute instance-attribute

Transaction is type 3, but has no blobs.

ReferenceSpec

Reference Specification Description Abstract Class.

Source code in src/ethereum_test_tools/reference_spec/reference_spec.py
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
class ReferenceSpec:
    """
    Reference Specification Description Abstract Class.
    """

    @abstractmethod
    def name(self) -> str:
        """
        Returns the name of the spec.
        """
        pass

    @abstractmethod
    def has_known_version(self) -> bool:
        """
        Returns true if the reference spec object is hard-coded with a latest
        known version.
        """
        pass

    @abstractmethod
    def known_version(self) -> str:
        """
        Returns the latest known version in the reference.
        """
        pass

    @abstractmethod
    def api_url(self) -> str:
        """
        Returns the URL required to poll the version from an API, if needed.
        """
        pass

    @abstractmethod
    def latest_version(self) -> str:
        """
        Returns a digest that points to the latest version of the spec.
        """
        pass

    @abstractmethod
    def is_outdated(self) -> bool:
        """
        Checks whether the reference specification has been updated since the
        test was last updated.
        """
        pass

    @abstractmethod
    def write_info(self, info: Dict[str, str]):
        """
        Writes info about the reference specification used into the output
        fixture.
        """
        pass

    @staticmethod
    @abstractmethod
    def parseable_from_module(module_dict: Dict[str, Any]) -> bool:
        """
        Checks whether the module's dict contains required reference spec
        information.
        """
        pass

    @staticmethod
    @abstractmethod
    def parse_from_module(module_dict: Dict[str, Any]) -> "ReferenceSpec":
        """
        Parses the module's dict into a reference spec.
        """
        pass

name() abstractmethod

Returns the name of the spec.

Source code in src/ethereum_test_tools/reference_spec/reference_spec.py
35
36
37
38
39
40
@abstractmethod
def name(self) -> str:
    """
    Returns the name of the spec.
    """
    pass

has_known_version() abstractmethod

Returns true if the reference spec object is hard-coded with a latest known version.

Source code in src/ethereum_test_tools/reference_spec/reference_spec.py
42
43
44
45
46
47
48
@abstractmethod
def has_known_version(self) -> bool:
    """
    Returns true if the reference spec object is hard-coded with a latest
    known version.
    """
    pass

known_version() abstractmethod

Returns the latest known version in the reference.

Source code in src/ethereum_test_tools/reference_spec/reference_spec.py
50
51
52
53
54
55
@abstractmethod
def known_version(self) -> str:
    """
    Returns the latest known version in the reference.
    """
    pass

api_url() abstractmethod

Returns the URL required to poll the version from an API, if needed.

Source code in src/ethereum_test_tools/reference_spec/reference_spec.py
57
58
59
60
61
62
@abstractmethod
def api_url(self) -> str:
    """
    Returns the URL required to poll the version from an API, if needed.
    """
    pass

latest_version() abstractmethod

Returns a digest that points to the latest version of the spec.

Source code in src/ethereum_test_tools/reference_spec/reference_spec.py
64
65
66
67
68
69
@abstractmethod
def latest_version(self) -> str:
    """
    Returns a digest that points to the latest version of the spec.
    """
    pass

is_outdated() abstractmethod

Checks whether the reference specification has been updated since the test was last updated.

Source code in src/ethereum_test_tools/reference_spec/reference_spec.py
71
72
73
74
75
76
77
@abstractmethod
def is_outdated(self) -> bool:
    """
    Checks whether the reference specification has been updated since the
    test was last updated.
    """
    pass

write_info(info) abstractmethod

Writes info about the reference specification used into the output fixture.

Source code in src/ethereum_test_tools/reference_spec/reference_spec.py
79
80
81
82
83
84
85
@abstractmethod
def write_info(self, info: Dict[str, str]):
    """
    Writes info about the reference specification used into the output
    fixture.
    """
    pass

parseable_from_module(module_dict) abstractmethod staticmethod

Checks whether the module's dict contains required reference spec information.

Source code in src/ethereum_test_tools/reference_spec/reference_spec.py
87
88
89
90
91
92
93
94
@staticmethod
@abstractmethod
def parseable_from_module(module_dict: Dict[str, Any]) -> bool:
    """
    Checks whether the module's dict contains required reference spec
    information.
    """
    pass

parse_from_module(module_dict) abstractmethod staticmethod

Parses the module's dict into a reference spec.

Source code in src/ethereum_test_tools/reference_spec/reference_spec.py
 96
 97
 98
 99
100
101
102
@staticmethod
@abstractmethod
def parse_from_module(module_dict: Dict[str, Any]) -> "ReferenceSpec":
    """
    Parses the module's dict into a reference spec.
    """
    pass

BaseFixture dataclass

Represents a base Ethereum test fixture of any type.

Source code in src/ethereum_test_tools/spec/base/base_test.py
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
@dataclass(kw_only=True)
class BaseFixture:
    """
    Represents a base Ethereum test fixture of any type.
    """

    info: Dict[str, str] = json_field(
        default_factory=dict,
        json_encoder=JSONEncoder.Field(
            name="_info",
            to_json=True,
        ),
    )

    _json: Optional[Dict[str, Any]] = None

    def fill_info(
        self,
        t8n: TransitionTool,
        ref_spec: ReferenceSpec | None,
    ):
        """
        Fill the info field for this fixture
        """
        if "comment" not in self.info:
            self.info["comment"] = "`execution-spec-tests` generated test"
        self.info["filling-transition-tool"] = t8n.version()
        if ref_spec is not None:
            ref_spec.write_info(self.info)

    def __post_init__(self):
        """
        Post init hook to convert to JSON after instantiation.
        """
        self._json = to_json(self)
        json_str = json.dumps(self._json, sort_keys=True, separators=(",", ":"))
        h = hashlib.sha256(json_str.encode("utf-8")).hexdigest()
        self.info["hash"] = f"0x{h}"

    def to_json(self) -> Dict[str, Any]:
        """
        Convert to JSON.
        """
        assert self._json is not None, "Fixture not initialized"
        self._json["_info"] = self.info
        return self._json

    @classmethod
    @abstractmethod
    def format(cls) -> FixtureFormats:
        """
        Returns the fixture format which the evm tool can use to determine how to verify the
        fixture.
        """
        pass

    @classmethod
    @abstractmethod
    def collect_into_file(cls, fd: TextIO, fixtures: Dict[str, "BaseFixture"]):
        """
        Returns the name of the subdirectory where this type of fixture should be dumped to.
        """
        pass

    @classmethod
    @abstractmethod
    def output_base_dir_name(cls) -> Path:
        """
        Returns the name of the subdirectory where this type of fixture should be dumped to.
        """
        pass

    @classmethod
    def output_file_extension(cls) -> str:
        """
        Returns the file extension for this type of fixture.

        By default, fixtures are dumped as JSON files.
        """
        return ".json"

fill_info(t8n, ref_spec)

Fill the info field for this fixture

Source code in src/ethereum_test_tools/spec/base/base_test.py
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
def fill_info(
    self,
    t8n: TransitionTool,
    ref_spec: ReferenceSpec | None,
):
    """
    Fill the info field for this fixture
    """
    if "comment" not in self.info:
        self.info["comment"] = "`execution-spec-tests` generated test"
    self.info["filling-transition-tool"] = t8n.version()
    if ref_spec is not None:
        ref_spec.write_info(self.info)

__post_init__()

Post init hook to convert to JSON after instantiation.

Source code in src/ethereum_test_tools/spec/base/base_test.py
110
111
112
113
114
115
116
117
def __post_init__(self):
    """
    Post init hook to convert to JSON after instantiation.
    """
    self._json = to_json(self)
    json_str = json.dumps(self._json, sort_keys=True, separators=(",", ":"))
    h = hashlib.sha256(json_str.encode("utf-8")).hexdigest()
    self.info["hash"] = f"0x{h}"

to_json()

Convert to JSON.

Source code in src/ethereum_test_tools/spec/base/base_test.py
119
120
121
122
123
124
125
def to_json(self) -> Dict[str, Any]:
    """
    Convert to JSON.
    """
    assert self._json is not None, "Fixture not initialized"
    self._json["_info"] = self.info
    return self._json

format() abstractmethod classmethod

Returns the fixture format which the evm tool can use to determine how to verify the fixture.

Source code in src/ethereum_test_tools/spec/base/base_test.py
127
128
129
130
131
132
133
134
@classmethod
@abstractmethod
def format(cls) -> FixtureFormats:
    """
    Returns the fixture format which the evm tool can use to determine how to verify the
    fixture.
    """
    pass

collect_into_file(fd, fixtures) abstractmethod classmethod

Returns the name of the subdirectory where this type of fixture should be dumped to.

Source code in src/ethereum_test_tools/spec/base/base_test.py
136
137
138
139
140
141
142
@classmethod
@abstractmethod
def collect_into_file(cls, fd: TextIO, fixtures: Dict[str, "BaseFixture"]):
    """
    Returns the name of the subdirectory where this type of fixture should be dumped to.
    """
    pass

output_base_dir_name() abstractmethod classmethod

Returns the name of the subdirectory where this type of fixture should be dumped to.

Source code in src/ethereum_test_tools/spec/base/base_test.py
144
145
146
147
148
149
150
@classmethod
@abstractmethod
def output_base_dir_name(cls) -> Path:
    """
    Returns the name of the subdirectory where this type of fixture should be dumped to.
    """
    pass

output_file_extension() classmethod

Returns the file extension for this type of fixture.

By default, fixtures are dumped as JSON files.

Source code in src/ethereum_test_tools/spec/base/base_test.py
152
153
154
155
156
157
158
159
@classmethod
def output_file_extension(cls) -> str:
    """
    Returns the file extension for this type of fixture.

    By default, fixtures are dumped as JSON files.
    """
    return ".json"

BaseTest dataclass

Represents a base Ethereum test which must return a single test fixture.

Source code in src/ethereum_test_tools/spec/base/base_test.py
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
@dataclass(kw_only=True)
class BaseTest:
    """
    Represents a base Ethereum test which must return a single test fixture.
    """

    pre: Mapping
    tag: str = ""
    # Setting a default here is just for type checking, the correct value is automatically set
    # by pytest.
    fixture_format: FixtureFormats = FixtureFormats.UNSET_TEST_FORMAT

    # Transition tool specific fields
    t8n_dump_dir: Optional[str] = ""
    t8n_call_counter: Iterator[int] = field(init=False, default_factory=count)

    @abstractmethod
    def generate(
        self,
        t8n: TransitionTool,
        fork: Fork,
        eips: Optional[List[int]] = None,
    ) -> BaseFixture:
        """
        Generate the list of test fixtures.
        """
        pass

    @classmethod
    @abstractmethod
    def pytest_parameter_name(cls) -> str:
        """
        Must return the name of the parameter used in pytest to select this
        spec type as filler for the test.
        """
        pass

    @classmethod
    @abstractmethod
    def fixture_formats(cls) -> List[FixtureFormats]:
        """
        Returns a list of fixture formats that can be output to the test spec.
        """
        pass

    def __post_init__(self) -> None:
        """
        Validate the fixture format.
        """
        if self.fixture_format not in self.fixture_formats():
            raise ValueError(
                f"Invalid fixture format {self.fixture_format} for {self.__class__.__name__}."
            )

    def get_next_transition_tool_output_path(self) -> str:
        """
        Returns the path to the next transition tool output file.
        """
        if not self.t8n_dump_dir:
            return ""
        return path.join(
            self.t8n_dump_dir,
            str(next(self.t8n_call_counter)),
        )

generate(t8n, fork, eips=None) abstractmethod

Generate the list of test fixtures.

Source code in src/ethereum_test_tools/spec/base/base_test.py
178
179
180
181
182
183
184
185
186
187
188
@abstractmethod
def generate(
    self,
    t8n: TransitionTool,
    fork: Fork,
    eips: Optional[List[int]] = None,
) -> BaseFixture:
    """
    Generate the list of test fixtures.
    """
    pass

pytest_parameter_name() abstractmethod classmethod

Must return the name of the parameter used in pytest to select this spec type as filler for the test.

Source code in src/ethereum_test_tools/spec/base/base_test.py
190
191
192
193
194
195
196
197
@classmethod
@abstractmethod
def pytest_parameter_name(cls) -> str:
    """
    Must return the name of the parameter used in pytest to select this
    spec type as filler for the test.
    """
    pass

fixture_formats() abstractmethod classmethod

Returns a list of fixture formats that can be output to the test spec.

Source code in src/ethereum_test_tools/spec/base/base_test.py
199
200
201
202
203
204
205
@classmethod
@abstractmethod
def fixture_formats(cls) -> List[FixtureFormats]:
    """
    Returns a list of fixture formats that can be output to the test spec.
    """
    pass

__post_init__()

Validate the fixture format.

Source code in src/ethereum_test_tools/spec/base/base_test.py
207
208
209
210
211
212
213
214
def __post_init__(self) -> None:
    """
    Validate the fixture format.
    """
    if self.fixture_format not in self.fixture_formats():
        raise ValueError(
            f"Invalid fixture format {self.fixture_format} for {self.__class__.__name__}."
        )

get_next_transition_tool_output_path()

Returns the path to the next transition tool output file.

Source code in src/ethereum_test_tools/spec/base/base_test.py
216
217
218
219
220
221
222
223
224
225
def get_next_transition_tool_output_path(self) -> str:
    """
    Returns the path to the next transition tool output file.
    """
    if not self.t8n_dump_dir:
        return ""
    return path.join(
        self.t8n_dump_dir,
        str(next(self.t8n_call_counter)),
    )

BlockchainTest dataclass

Bases: BaseTest

Filler type that tests multiple blocks (valid or invalid) in a chain.

Source code in src/ethereum_test_tools/spec/blockchain/blockchain_test.py
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
@dataclass(kw_only=True)
class BlockchainTest(BaseTest):
    """
    Filler type that tests multiple blocks (valid or invalid) in a chain.
    """

    pre: Mapping
    post: Mapping
    blocks: List[Block]
    genesis_environment: Environment = field(default_factory=Environment)
    verify_sync: Optional[bool] = None
    tag: str = ""
    chain_id: int = 1

    @classmethod
    def pytest_parameter_name(cls) -> str:
        """
        Returns the parameter name used to identify this filler in a test.
        """
        return "blockchain_test"

    @classmethod
    def fixture_formats(cls) -> List[FixtureFormats]:
        """
        Returns a list of fixture formats that can be output to the test spec.
        """
        return [
            FixtureFormats.BLOCKCHAIN_TEST,
            FixtureFormats.BLOCKCHAIN_TEST_HIVE,
        ]

    def make_genesis(
        self,
        t8n: TransitionTool,
        fork: Fork,
    ) -> Tuple[Alloc, Bytes, FixtureHeader]:
        """
        Create a genesis block from the blockchain test definition.
        """
        env = self.genesis_environment.set_fork_requirements(fork)
        if env.withdrawals is not None:
            assert len(env.withdrawals) == 0, "withdrawals must be empty at genesis"
        if env.beacon_root is not None:
            assert Hash(env.beacon_root) == Hash(0), "beacon_root must be empty at genesis"

        pre_alloc = Alloc.merge(
            Alloc(fork.pre_allocation_blockchain()),
            Alloc(self.pre),
        )
        if empty_accounts := pre_alloc.empty_accounts():
            raise Exception(f"Empty accounts in pre state: {empty_accounts}")
        state_root = pre_alloc.state_root()
        genesis = FixtureHeader(
            parent_hash=Hash(0),
            ommers_hash=Hash(EmptyOmmersRoot),
            coinbase=Address(0),
            state_root=Hash(state_root),
            transactions_root=Hash(EmptyTrieRoot),
            receipt_root=Hash(EmptyTrieRoot),
            bloom=Bloom(0),
            difficulty=ZeroPaddedHexNumber(0x20000 if env.difficulty is None else env.difficulty),
            number=0,
            gas_limit=ZeroPaddedHexNumber(env.gas_limit),
            gas_used=0,
            timestamp=0,
            extra_data=Bytes([0]),
            mix_digest=Hash(0),
            nonce=HeaderNonce(0),
            base_fee=ZeroPaddedHexNumber.or_none(env.base_fee),
            blob_gas_used=ZeroPaddedHexNumber.or_none(env.blob_gas_used),
            excess_blob_gas=ZeroPaddedHexNumber.or_none(env.excess_blob_gas),
            withdrawals_root=Hash.or_none(
                withdrawals_root(env.withdrawals) if env.withdrawals is not None else None
            ),
            beacon_root=Hash.or_none(env.beacon_root),
        )

        genesis_rlp, genesis.hash = genesis.build(
            txs=[],
            ommers=[],
            withdrawals=env.withdrawals,
        )

        return pre_alloc, genesis_rlp, genesis

    def generate_block_data(
        self,
        t8n: TransitionTool,
        fork: Fork,
        block: Block,
        previous_env: Environment,
        previous_alloc: Dict[str, Any],
        eips: Optional[List[int]] = None,
    ) -> Tuple[FixtureHeader, Bytes, List[Transaction], Dict[str, Any], Environment]:
        """
        Generate common block data for both make_fixture and make_hive_fixture.
        """
        if block.rlp and block.exception is not None:
            raise Exception(
                "test correctness: post-state cannot be verified if the "
                + "block's rlp is supplied and the block is not supposed "
                + "to produce an exception"
            )

        env = block.set_environment(previous_env)
        env = env.set_fork_requirements(fork)

        txs = [tx.with_signature_and_sender() for tx in block.txs] if block.txs is not None else []

        if failing_tx_count := len([tx for tx in txs if tx.error]) > 0:
            if failing_tx_count > 1:
                raise Exception(
                    "test correctness: only one transaction can produce an exception in a block"
                )
            if not txs[-1].error:
                raise Exception(
                    "test correctness: the transaction that produces an exception "
                    + "must be the last transaction in the block"
                )

        next_alloc, result = t8n.evaluate(
            alloc=previous_alloc,
            txs=to_json(txs),
            env=to_json(env),
            fork_name=fork.transition_tool_name(
                block_number=Number(env.number), timestamp=Number(env.timestamp)
            ),
            chain_id=self.chain_id,
            reward=fork.get_reward(Number(env.number), Number(env.timestamp)),
            eips=eips,
            debug_output_path=self.get_next_transition_tool_output_path(),
        )

        try:
            rejected_txs = verify_transactions(txs, result)
            verify_result(result, env)
        except Exception as e:
            print_traces(t8n.get_traces())
            pprint(result)
            pprint(previous_alloc)
            pprint(next_alloc)
            raise e

        if len(rejected_txs) > 0 and block.exception is None:
            print_traces(t8n.get_traces())
            raise Exception(
                "one or more transactions in `BlockchainTest` are "
                + "intrinsically invalid, but the block was not expected "
                + "to be invalid. Please verify whether the transaction "
                + "was indeed expected to fail and add the proper "
                + "`block.exception`"
            )

        env.extra_data = block.extra_data
        header = FixtureHeader.collect(
            fork=fork,
            transition_tool_result=result,
            environment=env,
        )

        # Update the transactions root to the one calculated locally.
        header.transactions_root = transaction_list_root(txs)

        # One special case of the invalid transactions is the blob gas used, since this value
        # is not included in the transition tool result, but it is included in the block header,
        # and some clients check it before executing the block by simply counting the type-3 txs,
        # we need to set the correct value by default.
        if (
            blob_gas_per_blob := fork.blob_gas_per_blob(Number(env.number), Number(env.timestamp))
        ) > 0:
            header.blob_gas_used = blob_gas_per_blob * count_blobs(txs)

        if block.header_verify is not None:
            # Verify the header after transition tool processing.
            header.verify(block.header_verify)

        if block.rlp_modifier is not None:
            # Modify any parameter specified in the `rlp_modifier` after
            # transition tool processing.
            header = header.join(block.rlp_modifier)

        rlp, header.hash = header.build(
            txs=txs,
            ommers=[],
            withdrawals=env.withdrawals,
        )

        return header, rlp, txs, next_alloc, env

    def network_info(self, fork: Fork, eips: Optional[List[int]] = None):
        """
        Returns fixture network information for the fork & EIP/s.
        """
        return (
            "+".join([fork.blockchain_test_network_name()] + [str(eip) for eip in eips])
            if eips
            else fork.blockchain_test_network_name()
        )

    def verify_post_state(self, t8n, alloc):
        """
        Verifies the post alloc after all block/s or payload/s are generated.
        """
        try:
            verify_post_alloc(self.post, alloc)
        except Exception as e:
            print_traces(t8n.get_traces())
            raise e

    def make_fixture(
        self,
        t8n: TransitionTool,
        fork: Fork,
        eips: Optional[List[int]] = None,
    ) -> Fixture:
        """
        Create a fixture from the blockchain test definition.
        """
        fixture_blocks: List[FixtureBlock | InvalidFixtureBlock] = []

        pre, genesis_rlp, genesis = self.make_genesis(t8n, fork)

        alloc = to_json(pre)
        env = environment_from_parent_header(genesis)
        head = genesis.hash if genesis.hash is not None else Hash(0)

        for block in self.blocks:
            if block.rlp is None:
                # This is the most common case, the RLP needs to be constructed
                # based on the transactions to be included in the block.
                # Set the environment according to the block to execute.
                header, rlp, txs, new_alloc, new_env = self.generate_block_data(
                    t8n=t8n,
                    fork=fork,
                    block=block,
                    previous_env=env,
                    previous_alloc=alloc,
                    eips=eips,
                )
                fixture_block = FixtureBlock(
                    rlp=rlp,
                    block_header=header,
                    block_number=Number(header.number),
                    txs=txs,
                    ommers=[],
                    withdrawals=new_env.withdrawals,
                )
                if block.exception is None:
                    fixture_blocks.append(fixture_block)
                    # Update env, alloc and last block hash for the next block.
                    alloc = new_alloc
                    env = apply_new_parent(new_env, header)
                    head = header.hash if header.hash is not None else Hash(0)
                else:
                    fixture_blocks.append(
                        InvalidFixtureBlock(
                            rlp=rlp,
                            expected_exception=block.exception,
                            rlp_decoded=(
                                None
                                if BlockException.RLP_STRUCTURES_ENCODING in block.exception
                                else replace(fixture_block, rlp=None)
                            ),
                        ),
                    )
            else:
                assert block.exception is not None, (
                    "test correctness: if the block's rlp is hard-coded, "
                    + "the block is expected to produce an exception"
                )
                fixture_blocks.append(
                    InvalidFixtureBlock(
                        rlp=Bytes(block.rlp),
                        expected_exception=block.exception,
                    ),
                )

        self.verify_post_state(t8n, alloc)
        return Fixture(
            fork=self.network_info(fork, eips),
            genesis=genesis,
            genesis_rlp=genesis_rlp,
            blocks=fixture_blocks,
            last_block_hash=head,
            pre_state=pre,
            post_state=alloc_to_accounts(alloc),
            name=self.tag,
        )

    def make_hive_fixture(
        self,
        t8n: TransitionTool,
        fork: Fork,
        eips: Optional[List[int]] = None,
    ) -> HiveFixture:
        """
        Create a hive fixture from the blocktest definition.
        """
        fixture_payloads: List[FixtureEngineNewPayload] = []

        pre, _, genesis = self.make_genesis(t8n, fork)
        alloc = to_json(pre)
        env = environment_from_parent_header(genesis)
        head_hash = genesis.hash

        for block in self.blocks:
            header, _, txs, new_alloc, new_env = self.generate_block_data(
                t8n=t8n, fork=fork, block=block, previous_env=env, previous_alloc=alloc, eips=eips
            )
            if block.rlp is None:
                fixture_payloads.append(
                    FixtureEngineNewPayload.from_fixture_header(
                        fork=fork,
                        header=header,
                        transactions=txs,
                        withdrawals=new_env.withdrawals,
                        validation_error=block.exception,
                        error_code=block.engine_api_error_code,
                    )
                )
                if block.exception is None:
                    alloc = new_alloc
                    env = apply_new_parent(env, header)
                    head_hash = header.hash
        fcu_version = fork.engine_forkchoice_updated_version(header.number, header.timestamp)
        assert (
            fcu_version is not None
        ), "A hive fixture was requested but no forkchoice update is defined. The framework should"
        " never try to execute this test case."

        self.verify_post_state(t8n, alloc)

        sync_payload: Optional[FixtureEngineNewPayload] = None
        if self.verify_sync:
            # Test is marked for syncing verification.
            assert (
                genesis.hash != head_hash
            ), "Invalid payload tests negative test via sync is not supported yet."

            # Most clients require the header to start the sync process, so we create an empty
            # block on top of the last block of the test to send it as new payload and trigger the
            # sync process.
            sync_header, _, _, _, _ = self.generate_block_data(
                t8n=t8n,
                fork=fork,
                block=Block(),
                previous_env=env,
                previous_alloc=alloc,
                eips=eips,
            )
            sync_payload = FixtureEngineNewPayload.from_fixture_header(
                fork=fork,
                header=sync_header,
                transactions=[],
                withdrawals=[],
                validation_error=None,
                error_code=None,
            )

        return HiveFixture(
            fork=self.network_info(fork, eips),
            genesis=genesis,
            payloads=fixture_payloads,
            fcu_version=fcu_version,
            pre_state=pre,
            post_state=alloc_to_accounts(alloc),
            sync_payload=sync_payload,
            name=self.tag,
        )

    def generate(
        self,
        t8n: TransitionTool,
        fork: Fork,
        eips: Optional[List[int]] = None,
    ) -> BaseFixture:
        """
        Generate the BlockchainTest fixture.
        """
        t8n.reset_traces()
        if self.fixture_format == FixtureFormats.BLOCKCHAIN_TEST_HIVE:
            if fork.engine_forkchoice_updated_version() is None:
                raise Exception(
                    "A hive fixture was requested but no forkchoice update is defined. "
                    "The framework should never try to execute this test case."
                )
            return self.make_hive_fixture(t8n, fork, eips)
        elif self.fixture_format == FixtureFormats.BLOCKCHAIN_TEST:
            return self.make_fixture(t8n, fork, eips)

        raise Exception(f"Unknown fixture format: {self.fixture_format}")

pytest_parameter_name() classmethod

Returns the parameter name used to identify this filler in a test.

Source code in src/ethereum_test_tools/spec/blockchain/blockchain_test.py
108
109
110
111
112
113
@classmethod
def pytest_parameter_name(cls) -> str:
    """
    Returns the parameter name used to identify this filler in a test.
    """
    return "blockchain_test"

fixture_formats() classmethod

Returns a list of fixture formats that can be output to the test spec.

Source code in src/ethereum_test_tools/spec/blockchain/blockchain_test.py
115
116
117
118
119
120
121
122
123
@classmethod
def fixture_formats(cls) -> List[FixtureFormats]:
    """
    Returns a list of fixture formats that can be output to the test spec.
    """
    return [
        FixtureFormats.BLOCKCHAIN_TEST,
        FixtureFormats.BLOCKCHAIN_TEST_HIVE,
    ]

make_genesis(t8n, fork)

Create a genesis block from the blockchain test definition.

Source code in src/ethereum_test_tools/spec/blockchain/blockchain_test.py
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
def make_genesis(
    self,
    t8n: TransitionTool,
    fork: Fork,
) -> Tuple[Alloc, Bytes, FixtureHeader]:
    """
    Create a genesis block from the blockchain test definition.
    """
    env = self.genesis_environment.set_fork_requirements(fork)
    if env.withdrawals is not None:
        assert len(env.withdrawals) == 0, "withdrawals must be empty at genesis"
    if env.beacon_root is not None:
        assert Hash(env.beacon_root) == Hash(0), "beacon_root must be empty at genesis"

    pre_alloc = Alloc.merge(
        Alloc(fork.pre_allocation_blockchain()),
        Alloc(self.pre),
    )
    if empty_accounts := pre_alloc.empty_accounts():
        raise Exception(f"Empty accounts in pre state: {empty_accounts}")
    state_root = pre_alloc.state_root()
    genesis = FixtureHeader(
        parent_hash=Hash(0),
        ommers_hash=Hash(EmptyOmmersRoot),
        coinbase=Address(0),
        state_root=Hash(state_root),
        transactions_root=Hash(EmptyTrieRoot),
        receipt_root=Hash(EmptyTrieRoot),
        bloom=Bloom(0),
        difficulty=ZeroPaddedHexNumber(0x20000 if env.difficulty is None else env.difficulty),
        number=0,
        gas_limit=ZeroPaddedHexNumber(env.gas_limit),
        gas_used=0,
        timestamp=0,
        extra_data=Bytes([0]),
        mix_digest=Hash(0),
        nonce=HeaderNonce(0),
        base_fee=ZeroPaddedHexNumber.or_none(env.base_fee),
        blob_gas_used=ZeroPaddedHexNumber.or_none(env.blob_gas_used),
        excess_blob_gas=ZeroPaddedHexNumber.or_none(env.excess_blob_gas),
        withdrawals_root=Hash.or_none(
            withdrawals_root(env.withdrawals) if env.withdrawals is not None else None
        ),
        beacon_root=Hash.or_none(env.beacon_root),
    )

    genesis_rlp, genesis.hash = genesis.build(
        txs=[],
        ommers=[],
        withdrawals=env.withdrawals,
    )

    return pre_alloc, genesis_rlp, genesis

generate_block_data(t8n, fork, block, previous_env, previous_alloc, eips=None)

Generate common block data for both make_fixture and make_hive_fixture.

Source code in src/ethereum_test_tools/spec/blockchain/blockchain_test.py
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
def generate_block_data(
    self,
    t8n: TransitionTool,
    fork: Fork,
    block: Block,
    previous_env: Environment,
    previous_alloc: Dict[str, Any],
    eips: Optional[List[int]] = None,
) -> Tuple[FixtureHeader, Bytes, List[Transaction], Dict[str, Any], Environment]:
    """
    Generate common block data for both make_fixture and make_hive_fixture.
    """
    if block.rlp and block.exception is not None:
        raise Exception(
            "test correctness: post-state cannot be verified if the "
            + "block's rlp is supplied and the block is not supposed "
            + "to produce an exception"
        )

    env = block.set_environment(previous_env)
    env = env.set_fork_requirements(fork)

    txs = [tx.with_signature_and_sender() for tx in block.txs] if block.txs is not None else []

    if failing_tx_count := len([tx for tx in txs if tx.error]) > 0:
        if failing_tx_count > 1:
            raise Exception(
                "test correctness: only one transaction can produce an exception in a block"
            )
        if not txs[-1].error:
            raise Exception(
                "test correctness: the transaction that produces an exception "
                + "must be the last transaction in the block"
            )

    next_alloc, result = t8n.evaluate(
        alloc=previous_alloc,
        txs=to_json(txs),
        env=to_json(env),
        fork_name=fork.transition_tool_name(
            block_number=Number(env.number), timestamp=Number(env.timestamp)
        ),
        chain_id=self.chain_id,
        reward=fork.get_reward(Number(env.number), Number(env.timestamp)),
        eips=eips,
        debug_output_path=self.get_next_transition_tool_output_path(),
    )

    try:
        rejected_txs = verify_transactions(txs, result)
        verify_result(result, env)
    except Exception as e:
        print_traces(t8n.get_traces())
        pprint(result)
        pprint(previous_alloc)
        pprint(next_alloc)
        raise e

    if len(rejected_txs) > 0 and block.exception is None:
        print_traces(t8n.get_traces())
        raise Exception(
            "one or more transactions in `BlockchainTest` are "
            + "intrinsically invalid, but the block was not expected "
            + "to be invalid. Please verify whether the transaction "
            + "was indeed expected to fail and add the proper "
            + "`block.exception`"
        )

    env.extra_data = block.extra_data
    header = FixtureHeader.collect(
        fork=fork,
        transition_tool_result=result,
        environment=env,
    )

    # Update the transactions root to the one calculated locally.
    header.transactions_root = transaction_list_root(txs)

    # One special case of the invalid transactions is the blob gas used, since this value
    # is not included in the transition tool result, but it is included in the block header,
    # and some clients check it before executing the block by simply counting the type-3 txs,
    # we need to set the correct value by default.
    if (
        blob_gas_per_blob := fork.blob_gas_per_blob(Number(env.number), Number(env.timestamp))
    ) > 0:
        header.blob_gas_used = blob_gas_per_blob * count_blobs(txs)

    if block.header_verify is not None:
        # Verify the header after transition tool processing.
        header.verify(block.header_verify)

    if block.rlp_modifier is not None:
        # Modify any parameter specified in the `rlp_modifier` after
        # transition tool processing.
        header = header.join(block.rlp_modifier)

    rlp, header.hash = header.build(
        txs=txs,
        ommers=[],
        withdrawals=env.withdrawals,
    )

    return header, rlp, txs, next_alloc, env

network_info(fork, eips=None)

Returns fixture network information for the fork & EIP/s.

Source code in src/ethereum_test_tools/spec/blockchain/blockchain_test.py
283
284
285
286
287
288
289
290
291
def network_info(self, fork: Fork, eips: Optional[List[int]] = None):
    """
    Returns fixture network information for the fork & EIP/s.
    """
    return (
        "+".join([fork.blockchain_test_network_name()] + [str(eip) for eip in eips])
        if eips
        else fork.blockchain_test_network_name()
    )

verify_post_state(t8n, alloc)

Verifies the post alloc after all block/s or payload/s are generated.

Source code in src/ethereum_test_tools/spec/blockchain/blockchain_test.py
293
294
295
296
297
298
299
300
301
def verify_post_state(self, t8n, alloc):
    """
    Verifies the post alloc after all block/s or payload/s are generated.
    """
    try:
        verify_post_alloc(self.post, alloc)
    except Exception as e:
        print_traces(t8n.get_traces())
        raise e

make_fixture(t8n, fork, eips=None)

Create a fixture from the blockchain test definition.

Source code in src/ethereum_test_tools/spec/blockchain/blockchain_test.py
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
def make_fixture(
    self,
    t8n: TransitionTool,
    fork: Fork,
    eips: Optional[List[int]] = None,
) -> Fixture:
    """
    Create a fixture from the blockchain test definition.
    """
    fixture_blocks: List[FixtureBlock | InvalidFixtureBlock] = []

    pre, genesis_rlp, genesis = self.make_genesis(t8n, fork)

    alloc = to_json(pre)
    env = environment_from_parent_header(genesis)
    head = genesis.hash if genesis.hash is not None else Hash(0)

    for block in self.blocks:
        if block.rlp is None:
            # This is the most common case, the RLP needs to be constructed
            # based on the transactions to be included in the block.
            # Set the environment according to the block to execute.
            header, rlp, txs, new_alloc, new_env = self.generate_block_data(
                t8n=t8n,
                fork=fork,
                block=block,
                previous_env=env,
                previous_alloc=alloc,
                eips=eips,
            )
            fixture_block = FixtureBlock(
                rlp=rlp,
                block_header=header,
                block_number=Number(header.number),
                txs=txs,
                ommers=[],
                withdrawals=new_env.withdrawals,
            )
            if block.exception is None:
                fixture_blocks.append(fixture_block)
                # Update env, alloc and last block hash for the next block.
                alloc = new_alloc
                env = apply_new_parent(new_env, header)
                head = header.hash if header.hash is not None else Hash(0)
            else:
                fixture_blocks.append(
                    InvalidFixtureBlock(
                        rlp=rlp,
                        expected_exception=block.exception,
                        rlp_decoded=(
                            None
                            if BlockException.RLP_STRUCTURES_ENCODING in block.exception
                            else replace(fixture_block, rlp=None)
                        ),
                    ),
                )
        else:
            assert block.exception is not None, (
                "test correctness: if the block's rlp is hard-coded, "
                + "the block is expected to produce an exception"
            )
            fixture_blocks.append(
                InvalidFixtureBlock(
                    rlp=Bytes(block.rlp),
                    expected_exception=block.exception,
                ),
            )

    self.verify_post_state(t8n, alloc)
    return Fixture(
        fork=self.network_info(fork, eips),
        genesis=genesis,
        genesis_rlp=genesis_rlp,
        blocks=fixture_blocks,
        last_block_hash=head,
        pre_state=pre,
        post_state=alloc_to_accounts(alloc),
        name=self.tag,
    )

make_hive_fixture(t8n, fork, eips=None)

Create a hive fixture from the blocktest definition.

Source code in src/ethereum_test_tools/spec/blockchain/blockchain_test.py
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
def make_hive_fixture(
    self,
    t8n: TransitionTool,
    fork: Fork,
    eips: Optional[List[int]] = None,
) -> HiveFixture:
    """
    Create a hive fixture from the blocktest definition.
    """
    fixture_payloads: List[FixtureEngineNewPayload] = []

    pre, _, genesis = self.make_genesis(t8n, fork)
    alloc = to_json(pre)
    env = environment_from_parent_header(genesis)
    head_hash = genesis.hash

    for block in self.blocks:
        header, _, txs, new_alloc, new_env = self.generate_block_data(
            t8n=t8n, fork=fork, block=block, previous_env=env, previous_alloc=alloc, eips=eips
        )
        if block.rlp is None:
            fixture_payloads.append(
                FixtureEngineNewPayload.from_fixture_header(
                    fork=fork,
                    header=header,
                    transactions=txs,
                    withdrawals=new_env.withdrawals,
                    validation_error=block.exception,
                    error_code=block.engine_api_error_code,
                )
            )
            if block.exception is None:
                alloc = new_alloc
                env = apply_new_parent(env, header)
                head_hash = header.hash
    fcu_version = fork.engine_forkchoice_updated_version(header.number, header.timestamp)
    assert (
        fcu_version is not None
    ), "A hive fixture was requested but no forkchoice update is defined. The framework should"
    " never try to execute this test case."

    self.verify_post_state(t8n, alloc)

    sync_payload: Optional[FixtureEngineNewPayload] = None
    if self.verify_sync:
        # Test is marked for syncing verification.
        assert (
            genesis.hash != head_hash
        ), "Invalid payload tests negative test via sync is not supported yet."

        # Most clients require the header to start the sync process, so we create an empty
        # block on top of the last block of the test to send it as new payload and trigger the
        # sync process.
        sync_header, _, _, _, _ = self.generate_block_data(
            t8n=t8n,
            fork=fork,
            block=Block(),
            previous_env=env,
            previous_alloc=alloc,
            eips=eips,
        )
        sync_payload = FixtureEngineNewPayload.from_fixture_header(
            fork=fork,
            header=sync_header,
            transactions=[],
            withdrawals=[],
            validation_error=None,
            error_code=None,
        )

    return HiveFixture(
        fork=self.network_info(fork, eips),
        genesis=genesis,
        payloads=fixture_payloads,
        fcu_version=fcu_version,
        pre_state=pre,
        post_state=alloc_to_accounts(alloc),
        sync_payload=sync_payload,
        name=self.tag,
    )

generate(t8n, fork, eips=None)

Generate the BlockchainTest fixture.

Source code in src/ethereum_test_tools/spec/blockchain/blockchain_test.py
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
def generate(
    self,
    t8n: TransitionTool,
    fork: Fork,
    eips: Optional[List[int]] = None,
) -> BaseFixture:
    """
    Generate the BlockchainTest fixture.
    """
    t8n.reset_traces()
    if self.fixture_format == FixtureFormats.BLOCKCHAIN_TEST_HIVE:
        if fork.engine_forkchoice_updated_version() is None:
            raise Exception(
                "A hive fixture was requested but no forkchoice update is defined. "
                "The framework should never try to execute this test case."
            )
        return self.make_hive_fixture(t8n, fork, eips)
    elif self.fixture_format == FixtureFormats.BLOCKCHAIN_TEST:
        return self.make_fixture(t8n, fork, eips)

    raise Exception(f"Unknown fixture format: {self.fixture_format}")

FixtureCollector dataclass

Collects all fixtures generated by the test cases.

Source code in src/ethereum_test_tools/spec/fixture_collector.py
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
@dataclass(kw_only=True)
class FixtureCollector:
    """
    Collects all fixtures generated by the test cases.
    """

    output_dir: str
    flat_output: bool
    single_fixture_per_file: bool
    filler_path: Path
    base_dump_dir: Optional[Path] = None

    # Internal state
    all_fixtures: Dict[Path, Dict[str, BaseFixture]] = field(default_factory=dict)
    json_path_to_fixture_type: Dict[Path, FixtureFormats] = field(default_factory=dict)
    json_path_to_test_item: Dict[Path, TestInfo] = field(default_factory=dict)

    def get_fixture_basename(self, info: TestInfo) -> Path:
        """
        Returns the basename of the fixture file for a given test case.
        """
        if self.flat_output:
            if self.single_fixture_per_file:
                return Path(strip_test_prefix(info.get_single_test_name()))
            return Path(strip_test_prefix(info.original_name))
        else:
            relative_fixture_output_dir = Path(info.path).parent / strip_test_prefix(
                Path(info.path).stem
            )
            module_relative_output_dir = get_module_relative_output_dir(
                relative_fixture_output_dir, self.filler_path
            )

            if self.single_fixture_per_file:
                return module_relative_output_dir / strip_test_prefix(info.get_single_test_name())
            return module_relative_output_dir / strip_test_prefix(info.original_name)

    def add_fixture(self, info: TestInfo, fixture: BaseFixture) -> None:
        """
        Adds a fixture to the list of fixtures of a given test case.
        """
        fixture_basename = self.get_fixture_basename(info)

        fixture_path = (
            self.output_dir
            / fixture.output_base_dir_name()
            / fixture_basename.with_suffix(fixture.output_file_extension())
        )
        if fixture_path not in self.all_fixtures:  # relevant when we group by test function
            self.all_fixtures[fixture_path] = {}
            if fixture_path in self.json_path_to_fixture_type:
                if self.json_path_to_fixture_type[fixture_path] != fixture.format():
                    raise Exception(
                        f"Fixture {fixture_path} has two different types: "
                        f"{self.json_path_to_fixture_type[fixture_path]} "
                        f"and {fixture.format()}"
                    )
            else:
                self.json_path_to_fixture_type[fixture_path] = fixture.format()
            self.json_path_to_test_item[fixture_path] = info

        self.all_fixtures[fixture_path][info.id] = fixture

    def dump_fixtures(self) -> None:
        """
        Dumps all collected fixtures to their respective files.
        """
        os.makedirs(self.output_dir, exist_ok=True)
        for fixture_path, fixtures in self.all_fixtures.items():
            os.makedirs(fixture_path.parent, exist_ok=True)

            # Get the first fixture to dump to get its type
            fixture = next(iter(fixtures.values()))
            # Call class method to dump all the fixtures
            with open(fixture_path, "w") as fd:
                fixture.collect_into_file(fd, fixtures)

    def verify_fixture_files(self, evm_fixture_verification: TransitionTool) -> None:
        """
        Runs `evm [state|block]test` on each fixture.
        """
        for fixture_path, fixture_format in self.json_path_to_fixture_type.items():
            if FixtureFormats.is_verifiable(fixture_format):
                info = self.json_path_to_test_item[fixture_path]
                verify_fixtures_dump_dir = self._get_verify_fixtures_dump_dir(info)
                evm_fixture_verification.verify_fixture(
                    fixture_format, fixture_path, verify_fixtures_dump_dir
                )

    def _get_verify_fixtures_dump_dir(
        self,
        info: TestInfo,
    ):
        """
        The directory to dump the current test function's fixture.json and fixture
        verification debug output.
        """
        if not self.base_dump_dir:
            return None
        if self.single_fixture_per_file:
            return info.get_dump_dir_path(
                self.base_dump_dir, self.filler_path, level="test_parameter"
            )
        else:
            return info.get_dump_dir_path(
                self.base_dump_dir, self.filler_path, level="test_function"
            )

get_fixture_basename(info)

Returns the basename of the fixture file for a given test case.

Source code in src/ethereum_test_tools/spec/fixture_collector.py
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
def get_fixture_basename(self, info: TestInfo) -> Path:
    """
    Returns the basename of the fixture file for a given test case.
    """
    if self.flat_output:
        if self.single_fixture_per_file:
            return Path(strip_test_prefix(info.get_single_test_name()))
        return Path(strip_test_prefix(info.original_name))
    else:
        relative_fixture_output_dir = Path(info.path).parent / strip_test_prefix(
            Path(info.path).stem
        )
        module_relative_output_dir = get_module_relative_output_dir(
            relative_fixture_output_dir, self.filler_path
        )

        if self.single_fixture_per_file:
            return module_relative_output_dir / strip_test_prefix(info.get_single_test_name())
        return module_relative_output_dir / strip_test_prefix(info.original_name)

add_fixture(info, fixture)

Adds a fixture to the list of fixtures of a given test case.

Source code in src/ethereum_test_tools/spec/fixture_collector.py
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
def add_fixture(self, info: TestInfo, fixture: BaseFixture) -> None:
    """
    Adds a fixture to the list of fixtures of a given test case.
    """
    fixture_basename = self.get_fixture_basename(info)

    fixture_path = (
        self.output_dir
        / fixture.output_base_dir_name()
        / fixture_basename.with_suffix(fixture.output_file_extension())
    )
    if fixture_path not in self.all_fixtures:  # relevant when we group by test function
        self.all_fixtures[fixture_path] = {}
        if fixture_path in self.json_path_to_fixture_type:
            if self.json_path_to_fixture_type[fixture_path] != fixture.format():
                raise Exception(
                    f"Fixture {fixture_path} has two different types: "
                    f"{self.json_path_to_fixture_type[fixture_path]} "
                    f"and {fixture.format()}"
                )
        else:
            self.json_path_to_fixture_type[fixture_path] = fixture.format()
        self.json_path_to_test_item[fixture_path] = info

    self.all_fixtures[fixture_path][info.id] = fixture

dump_fixtures()

Dumps all collected fixtures to their respective files.

Source code in src/ethereum_test_tools/spec/fixture_collector.py
156
157
158
159
160
161
162
163
164
165
166
167
168
def dump_fixtures(self) -> None:
    """
    Dumps all collected fixtures to their respective files.
    """
    os.makedirs(self.output_dir, exist_ok=True)
    for fixture_path, fixtures in self.all_fixtures.items():
        os.makedirs(fixture_path.parent, exist_ok=True)

        # Get the first fixture to dump to get its type
        fixture = next(iter(fixtures.values()))
        # Call class method to dump all the fixtures
        with open(fixture_path, "w") as fd:
            fixture.collect_into_file(fd, fixtures)

verify_fixture_files(evm_fixture_verification)

Runs evm [state|block]test on each fixture.

Source code in src/ethereum_test_tools/spec/fixture_collector.py
170
171
172
173
174
175
176
177
178
179
180
def verify_fixture_files(self, evm_fixture_verification: TransitionTool) -> None:
    """
    Runs `evm [state|block]test` on each fixture.
    """
    for fixture_path, fixture_format in self.json_path_to_fixture_type.items():
        if FixtureFormats.is_verifiable(fixture_format):
            info = self.json_path_to_test_item[fixture_path]
            verify_fixtures_dump_dir = self._get_verify_fixtures_dump_dir(info)
            evm_fixture_verification.verify_fixture(
                fixture_format, fixture_path, verify_fixtures_dump_dir
            )

StateTest dataclass

Bases: BaseTest

Filler type that tests transactions over the period of a single block.

Source code in src/ethereum_test_tools/spec/state/state_test.py
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
@dataclass(kw_only=True)
class StateTest(BaseTest):
    """
    Filler type that tests transactions over the period of a single block.
    """

    env: Environment
    pre: Mapping
    post: Mapping
    tx: Transaction
    engine_api_error_code: Optional[EngineAPIError] = None
    blockchain_test_header_verify: Optional[Header] = None
    blockchain_test_rlp_modifier: Optional[Header] = None
    tag: str = ""
    chain_id: int = 1

    @classmethod
    def pytest_parameter_name(cls) -> str:
        """
        Returns the parameter name used to identify this filler in a test.
        """
        return "state_test"

    @classmethod
    def fixture_formats(cls) -> List[FixtureFormats]:
        """
        Returns a list of fixture formats that can be output to the test spec.
        """
        return [
            FixtureFormats.BLOCKCHAIN_TEST,
            FixtureFormats.BLOCKCHAIN_TEST_HIVE,
            FixtureFormats.STATE_TEST,
        ]

    def _generate_blockchain_genesis_environment(self) -> Environment:
        """
        Generate the genesis environment for the BlockchainTest formatted test.
        """
        genesis_env = copy(self.env)

        # Modify values to the proper values for the genesis block
        # TODO: All of this can be moved to a new method in `Fork`
        genesis_env.withdrawals = None
        genesis_env.beacon_root = None
        genesis_env.number = Number(genesis_env.number) - 1
        assert (
            genesis_env.number >= 0
        ), "genesis block number cannot be negative, set state test env.number to 1"
        if genesis_env.excess_blob_gas:
            # The excess blob gas environment value means the value of the context (block header)
            # where the transaction is executed. In a blockchain test, we need to indirectly
            # set the excess blob gas by setting the excess blob gas of the genesis block
            # to the expected value plus the TARGET_BLOB_GAS_PER_BLOCK, which is the value
            # that will be subtracted from the excess blob gas when the first block is mined.
            genesis_env.excess_blob_gas = (
                Number(genesis_env.excess_blob_gas) + TARGET_BLOB_GAS_PER_BLOCK
            )

        return genesis_env

    def _generate_blockchain_blocks(self) -> List[Block]:
        """
        Generate the single block that represents this state test in a BlockchainTest format.
        """
        return [
            Block(
                number=self.env.number,
                timestamp=self.env.timestamp,
                coinbase=self.env.coinbase,
                difficulty=self.env.difficulty,
                gas_limit=self.env.gas_limit,
                extra_data=self.env.extra_data,
                withdrawals=self.env.withdrawals,
                beacon_root=self.env.beacon_root,
                txs=[self.tx],
                ommers=[],
                exception=self.tx.error,
                header_verify=self.blockchain_test_header_verify,
                rlp_modifier=self.blockchain_test_rlp_modifier,
            )
        ]

    def generate_blockchain_test(self) -> BlockchainTest:
        """
        Generate a BlockchainTest fixture from this StateTest fixture.
        """
        return BlockchainTest(
            genesis_environment=self._generate_blockchain_genesis_environment(),
            pre=self.pre,
            post=self.post,
            blocks=self._generate_blockchain_blocks(),
            fixture_format=self.fixture_format,
            t8n_dump_dir=self.t8n_dump_dir,
        )

    def make_state_test_fixture(
        self,
        t8n: TransitionTool,
        fork: Fork,
        eips: Optional[List[int]] = None,
    ) -> Fixture:
        """
        Create a fixture from the state test definition.
        """
        env = self.env.set_fork_requirements(fork)
        tx = self.tx.with_signature_and_sender(keep_secret_key=True)
        pre_alloc = Alloc.merge(
            Alloc(fork.pre_allocation()),
            Alloc(self.pre),
        )
        if empty_accounts := pre_alloc.empty_accounts():
            raise Exception(f"Empty accounts in pre state: {empty_accounts}")
        transition_tool_name = fork.transition_tool_name(
            block_number=Number(self.env.number),
            timestamp=Number(self.env.timestamp),
        )
        fork_name = (
            "+".join([transition_tool_name] + [str(eip) for eip in eips])
            if eips
            else transition_tool_name
        )
        next_alloc, result = t8n.evaluate(
            alloc=to_json(pre_alloc),
            txs=to_json([tx]),
            env=to_json(env),
            fork_name=fork_name,
            chain_id=self.chain_id,
            reward=0,  # Reward on state tests is always zero
            eips=eips,
            debug_output_path=self.get_next_transition_tool_output_path(),
        )

        try:
            verify_post_alloc(self.post, next_alloc)
        except Exception as e:
            print_traces(t8n.get_traces())
            raise e

        return Fixture(
            env=env,
            pre_state=pre_alloc,
            post={
                fork.blockchain_test_network_name(): [
                    FixtureForkPost.collect(
                        transition_tool_result=result,
                        transaction=tx.with_signature_and_sender(),
                    )
                ]
            },
            transaction=tx,
        )

    def generate(
        self,
        t8n: TransitionTool,
        fork: Fork,
        eips: Optional[List[int]] = None,
    ) -> BaseFixture:
        """
        Generate the BlockchainTest fixture.
        """
        if self.fixture_format in BlockchainTest.fixture_formats():
            return self.generate_blockchain_test().generate(t8n, fork, eips)
        elif self.fixture_format == FixtureFormats.STATE_TEST:
            # We can't generate a state test fixture that names a transition fork,
            # so we get the fork at the block number and timestamp of the state test
            fork = fork.fork_at(Number(self.env.number), Number(self.env.timestamp))
            return self.make_state_test_fixture(t8n, fork, eips)

        raise Exception(f"Unknown fixture format: {self.fixture_format}")

pytest_parameter_name() classmethod

Returns the parameter name used to identify this filler in a test.

Source code in src/ethereum_test_tools/spec/state/state_test.py
41
42
43
44
45
46
@classmethod
def pytest_parameter_name(cls) -> str:
    """
    Returns the parameter name used to identify this filler in a test.
    """
    return "state_test"

fixture_formats() classmethod

Returns a list of fixture formats that can be output to the test spec.

Source code in src/ethereum_test_tools/spec/state/state_test.py
48
49
50
51
52
53
54
55
56
57
@classmethod
def fixture_formats(cls) -> List[FixtureFormats]:
    """
    Returns a list of fixture formats that can be output to the test spec.
    """
    return [
        FixtureFormats.BLOCKCHAIN_TEST,
        FixtureFormats.BLOCKCHAIN_TEST_HIVE,
        FixtureFormats.STATE_TEST,
    ]

generate_blockchain_test()

Generate a BlockchainTest fixture from this StateTest fixture.

Source code in src/ethereum_test_tools/spec/state/state_test.py
107
108
109
110
111
112
113
114
115
116
117
118
def generate_blockchain_test(self) -> BlockchainTest:
    """
    Generate a BlockchainTest fixture from this StateTest fixture.
    """
    return BlockchainTest(
        genesis_environment=self._generate_blockchain_genesis_environment(),
        pre=self.pre,
        post=self.post,
        blocks=self._generate_blockchain_blocks(),
        fixture_format=self.fixture_format,
        t8n_dump_dir=self.t8n_dump_dir,
    )

make_state_test_fixture(t8n, fork, eips=None)

Create a fixture from the state test definition.

Source code in src/ethereum_test_tools/spec/state/state_test.py
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
def make_state_test_fixture(
    self,
    t8n: TransitionTool,
    fork: Fork,
    eips: Optional[List[int]] = None,
) -> Fixture:
    """
    Create a fixture from the state test definition.
    """
    env = self.env.set_fork_requirements(fork)
    tx = self.tx.with_signature_and_sender(keep_secret_key=True)
    pre_alloc = Alloc.merge(
        Alloc(fork.pre_allocation()),
        Alloc(self.pre),
    )
    if empty_accounts := pre_alloc.empty_accounts():
        raise Exception(f"Empty accounts in pre state: {empty_accounts}")
    transition_tool_name = fork.transition_tool_name(
        block_number=Number(self.env.number),
        timestamp=Number(self.env.timestamp),
    )
    fork_name = (
        "+".join([transition_tool_name] + [str(eip) for eip in eips])
        if eips
        else transition_tool_name
    )
    next_alloc, result = t8n.evaluate(
        alloc=to_json(pre_alloc),
        txs=to_json([tx]),
        env=to_json(env),
        fork_name=fork_name,
        chain_id=self.chain_id,
        reward=0,  # Reward on state tests is always zero
        eips=eips,
        debug_output_path=self.get_next_transition_tool_output_path(),
    )

    try:
        verify_post_alloc(self.post, next_alloc)
    except Exception as e:
        print_traces(t8n.get_traces())
        raise e

    return Fixture(
        env=env,
        pre_state=pre_alloc,
        post={
            fork.blockchain_test_network_name(): [
                FixtureForkPost.collect(
                    transition_tool_result=result,
                    transaction=tx.with_signature_and_sender(),
                )
            ]
        },
        transaction=tx,
    )

generate(t8n, fork, eips=None)

Generate the BlockchainTest fixture.

Source code in src/ethereum_test_tools/spec/state/state_test.py
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
def generate(
    self,
    t8n: TransitionTool,
    fork: Fork,
    eips: Optional[List[int]] = None,
) -> BaseFixture:
    """
    Generate the BlockchainTest fixture.
    """
    if self.fixture_format in BlockchainTest.fixture_formats():
        return self.generate_blockchain_test().generate(t8n, fork, eips)
    elif self.fixture_format == FixtureFormats.STATE_TEST:
        # We can't generate a state test fixture that names a transition fork,
        # so we get the fork at the block number and timestamp of the state test
        fork = fork.fork_at(Number(self.env.number), Number(self.env.timestamp))
        return self.make_state_test_fixture(t8n, fork, eips)

    raise Exception(f"Unknown fixture format: {self.fixture_format}")

TestInfo dataclass

Contains test information from the current node.

Source code in src/ethereum_test_tools/spec/fixture_collector.py
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
@dataclass(kw_only=True)
class TestInfo:
    """
    Contains test information from the current node.
    """

    name: str  # pytest: Item.name
    id: str  # pytest: Item.nodeid
    original_name: str  # pytest: Item.originalname
    path: Path  # pytest: Item.path

    def get_name_and_parameters(self) -> Tuple[str, str]:
        """
        Converts a test name to a tuple containing the test name and test parameters.

        Example:
        test_push0_key_sstore[fork_Shanghai] -> test_push0_key_sstore, fork_Shanghai
        """
        test_name, parameters = self.name.split("[")
        return test_name, re.sub(r"[\[\-]", "_", parameters).replace("]", "")

    def get_single_test_name(self) -> str:
        """
        Converts a test name to a single test name.
        """
        test_name, test_parameters = self.get_name_and_parameters()
        return f"{test_name}__{test_parameters}"

    def get_dump_dir_path(
        self,
        base_dump_dir: Optional[Path],
        filler_path: Path,
        level: Literal["test_module", "test_function", "test_parameter"] = "test_parameter",
    ) -> Optional[Path]:
        """
        The path to dump the debug output as defined by the level to dump at.
        """
        if not base_dump_dir:
            return None
        test_module_relative_dir = get_module_relative_output_dir(self.path, filler_path)
        if level == "test_module":
            return Path(base_dump_dir) / Path(str(test_module_relative_dir).replace(os.sep, "__"))
        test_name, test_parameter_string = self.get_name_and_parameters()
        flat_path = f"{str(test_module_relative_dir).replace(os.sep, '__')}__{test_name}"
        if level == "test_function":
            return Path(base_dump_dir) / flat_path
        elif level == "test_parameter":
            return Path(base_dump_dir) / flat_path / test_parameter_string
        raise Exception("Unexpected level.")

get_name_and_parameters()

Converts a test name to a tuple containing the test name and test parameters.

Example: test_push0_key_sstore[fork_Shanghai] -> test_push0_key_sstore, fork_Shanghai

Source code in src/ethereum_test_tools/spec/fixture_collector.py
53
54
55
56
57
58
59
60
61
def get_name_and_parameters(self) -> Tuple[str, str]:
    """
    Converts a test name to a tuple containing the test name and test parameters.

    Example:
    test_push0_key_sstore[fork_Shanghai] -> test_push0_key_sstore, fork_Shanghai
    """
    test_name, parameters = self.name.split("[")
    return test_name, re.sub(r"[\[\-]", "_", parameters).replace("]", "")

get_single_test_name()

Converts a test name to a single test name.

Source code in src/ethereum_test_tools/spec/fixture_collector.py
63
64
65
66
67
68
def get_single_test_name(self) -> str:
    """
    Converts a test name to a single test name.
    """
    test_name, test_parameters = self.get_name_and_parameters()
    return f"{test_name}__{test_parameters}"

get_dump_dir_path(base_dump_dir, filler_path, level='test_parameter')

The path to dump the debug output as defined by the level to dump at.

Source code in src/ethereum_test_tools/spec/fixture_collector.py
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
def get_dump_dir_path(
    self,
    base_dump_dir: Optional[Path],
    filler_path: Path,
    level: Literal["test_module", "test_function", "test_parameter"] = "test_parameter",
) -> Optional[Path]:
    """
    The path to dump the debug output as defined by the level to dump at.
    """
    if not base_dump_dir:
        return None
    test_module_relative_dir = get_module_relative_output_dir(self.path, filler_path)
    if level == "test_module":
        return Path(base_dump_dir) / Path(str(test_module_relative_dir).replace(os.sep, "__"))
    test_name, test_parameter_string = self.get_name_and_parameters()
    flat_path = f"{str(test_module_relative_dir).replace(os.sep, '__')}__{test_name}"
    if level == "test_function":
        return Path(base_dump_dir) / flat_path
    elif level == "test_parameter":
        return Path(base_dump_dir) / flat_path / test_parameter_string
    raise Exception("Unexpected level.")

Block dataclass

Bases: Header

Block type used to describe block properties in test specs

Source code in src/ethereum_test_tools/spec/blockchain/types.py
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
@dataclass(kw_only=True)
class Block(Header):
    """
    Block type used to describe block properties in test specs
    """

    rlp: Optional[BytesConvertible] = None
    """
    If set, blockchain test will skip generating the block and will pass this value directly to
    the Fixture.

    Only meant to be used to simulate blocks with bad formats, and therefore
    requires the block to produce an exception.
    """
    header_verify: Optional[Header] = None
    """
    If set, the block header will be verified against the specified values.
    """
    rlp_modifier: Optional[Header] = None
    """
    An RLP modifying header which values would be used to override the ones
    returned by the  `evm_transition_tool`.
    """
    exception: Optional[BlockException | TransactionException | ExceptionList] = None
    """
    If set, the block is expected to be rejected by the client.
    """
    engine_api_error_code: Optional[EngineAPIError] = None
    """
    If set, the block is expected to produce an error response from the Engine API.
    """
    txs: Optional[List[Transaction]] = None
    """
    List of transactions included in the block.
    """
    ommers: Optional[List[Header]] = None
    """
    List of ommer headers included in the block.
    """
    withdrawals: Optional[List[Withdrawal]] = None
    """
    List of withdrawals to perform for this block.
    """

    def set_environment(self, env: Environment) -> Environment:
        """
        Creates a copy of the environment with the characteristics of this
        specific block.
        """
        new_env = copy(env)

        """
        Values that need to be set in the environment and are `None` for
        this block need to be set to their defaults.
        """
        environment_default = Environment()
        new_env.difficulty = self.difficulty
        new_env.coinbase = (
            self.coinbase if self.coinbase is not None else environment_default.coinbase
        )
        new_env.gas_limit = self.gas_limit or env.parent_gas_limit or environment_default.gas_limit
        if not isinstance(self.base_fee, Removable):
            new_env.base_fee = self.base_fee
        new_env.withdrawals = self.withdrawals
        if not isinstance(self.excess_blob_gas, Removable):
            new_env.excess_blob_gas = self.excess_blob_gas
        if not isinstance(self.blob_gas_used, Removable):
            new_env.blob_gas_used = self.blob_gas_used
        if not isinstance(self.beacon_root, Removable):
            new_env.beacon_root = self.beacon_root
        """
        These values are required, but they depend on the previous environment,
        so they can be calculated here.
        """
        if self.number is not None:
            new_env.number = self.number
        else:
            # calculate the next block number for the environment
            if len(new_env.block_hashes) == 0:
                new_env.number = 0
            else:
                new_env.number = max([Number(n) for n in new_env.block_hashes.keys()]) + 1

        if self.timestamp is not None:
            new_env.timestamp = self.timestamp
        else:
            assert new_env.parent_timestamp is not None
            new_env.timestamp = int(Number(new_env.parent_timestamp) + 12)

        return new_env

    def copy_with_rlp(self, rlp: Bytes | BytesConvertible | None) -> "Block":
        """
        Creates a copy of the block and adds the specified RLP.
        """
        new_block = deepcopy(self)
        new_block.rlp = Bytes.or_none(rlp)
        return new_block

rlp: Optional[BytesConvertible] = None class-attribute instance-attribute

If set, blockchain test will skip generating the block and will pass this value directly to the Fixture.

Only meant to be used to simulate blocks with bad formats, and therefore requires the block to produce an exception.

header_verify: Optional[Header] = None class-attribute instance-attribute

If set, the block header will be verified against the specified values.

rlp_modifier: Optional[Header] = None class-attribute instance-attribute

An RLP modifying header which values would be used to override the ones returned by the evm_transition_tool.

exception: Optional[BlockException | TransactionException | ExceptionList] = None class-attribute instance-attribute

If set, the block is expected to be rejected by the client.

engine_api_error_code: Optional[EngineAPIError] = None class-attribute instance-attribute

If set, the block is expected to produce an error response from the Engine API.

txs: Optional[List[Transaction]] = None class-attribute instance-attribute

List of transactions included in the block.

ommers: Optional[List[Header]] = None class-attribute instance-attribute

List of ommer headers included in the block.

withdrawals: Optional[List[Withdrawal]] = None class-attribute instance-attribute

List of withdrawals to perform for this block.

set_environment(env)

Creates a copy of the environment with the characteristics of this specific block.

Source code in src/ethereum_test_tools/spec/blockchain/types.py
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
def set_environment(self, env: Environment) -> Environment:
    """
    Creates a copy of the environment with the characteristics of this
    specific block.
    """
    new_env = copy(env)

    """
    Values that need to be set in the environment and are `None` for
    this block need to be set to their defaults.
    """
    environment_default = Environment()
    new_env.difficulty = self.difficulty
    new_env.coinbase = (
        self.coinbase if self.coinbase is not None else environment_default.coinbase
    )
    new_env.gas_limit = self.gas_limit or env.parent_gas_limit or environment_default.gas_limit
    if not isinstance(self.base_fee, Removable):
        new_env.base_fee = self.base_fee
    new_env.withdrawals = self.withdrawals
    if not isinstance(self.excess_blob_gas, Removable):
        new_env.excess_blob_gas = self.excess_blob_gas
    if not isinstance(self.blob_gas_used, Removable):
        new_env.blob_gas_used = self.blob_gas_used
    if not isinstance(self.beacon_root, Removable):
        new_env.beacon_root = self.beacon_root
    """
    These values are required, but they depend on the previous environment,
    so they can be calculated here.
    """
    if self.number is not None:
        new_env.number = self.number
    else:
        # calculate the next block number for the environment
        if len(new_env.block_hashes) == 0:
            new_env.number = 0
        else:
            new_env.number = max([Number(n) for n in new_env.block_hashes.keys()]) + 1

    if self.timestamp is not None:
        new_env.timestamp = self.timestamp
    else:
        assert new_env.parent_timestamp is not None
        new_env.timestamp = int(Number(new_env.parent_timestamp) + 12)

    return new_env

copy_with_rlp(rlp)

Creates a copy of the block and adds the specified RLP.

Source code in src/ethereum_test_tools/spec/blockchain/types.py
582
583
584
585
586
587
588
def copy_with_rlp(self, rlp: Bytes | BytesConvertible | None) -> "Block":
    """
    Creates a copy of the block and adds the specified RLP.
    """
    new_block = deepcopy(self)
    new_block.rlp = Bytes.or_none(rlp)
    return new_block

Header dataclass

Header type used to describe block header properties in test specs.

Source code in src/ethereum_test_tools/spec/blockchain/types.py
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
@dataclass(kw_only=True)
class Header:
    """
    Header type used to describe block header properties in test specs.
    """

    parent_hash: Optional[FixedSizeBytesConvertible] = None
    ommers_hash: Optional[FixedSizeBytesConvertible] = None
    coinbase: Optional[FixedSizeBytesConvertible] = None
    state_root: Optional[FixedSizeBytesConvertible] = None
    transactions_root: Optional[FixedSizeBytesConvertible] = None
    receipt_root: Optional[FixedSizeBytesConvertible] = None
    bloom: Optional[FixedSizeBytesConvertible] = None
    difficulty: Optional[NumberConvertible] = None
    number: Optional[NumberConvertible] = None
    gas_limit: Optional[NumberConvertible] = None
    gas_used: Optional[NumberConvertible] = None
    timestamp: Optional[NumberConvertible] = None
    extra_data: Optional[BytesConvertible] = None
    mix_digest: Optional[FixedSizeBytesConvertible] = None
    nonce: Optional[FixedSizeBytesConvertible] = None
    base_fee: Optional[NumberConvertible | Removable] = None
    withdrawals_root: Optional[FixedSizeBytesConvertible | Removable] = None
    blob_gas_used: Optional[NumberConvertible | Removable] = None
    excess_blob_gas: Optional[NumberConvertible | Removable] = None
    beacon_root: Optional[FixedSizeBytesConvertible | Removable] = None
    hash: Optional[FixedSizeBytesConvertible] = None

    REMOVE_FIELD: ClassVar[Removable] = Removable()
    """
    Sentinel object used to specify that a header field should be removed.
    """
    EMPTY_FIELD: ClassVar[Removable] = Removable()
    """
    Sentinel object used to specify that a header field must be empty during verification.
    """

REMOVE_FIELD: Removable = Removable() class-attribute

Sentinel object used to specify that a header field should be removed.

EMPTY_FIELD: Removable = Removable() class-attribute

Sentinel object used to specify that a header field must be empty during verification.

Opcode

Bases: bytes

Represents a single Opcode instruction in the EVM, with extra metadata useful to parametrize tests.

Parameters

  • popped_stack_items: number of items the opcode pops from the stack
  • pushed_stack_items: number of items the opcode pushes to the stack
  • min_stack_height: minimum stack height required by the opcode
  • data_portion_length: number of bytes after the opcode in the bytecode that represent data
Source code in src/ethereum_test_tools/vm/opcode.py
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
class Opcode(bytes):
    """
    Represents a single Opcode instruction in the EVM, with extra metadata useful to parametrize
    tests.

    Parameters
    ----------
    - popped_stack_items: number of items the opcode pops from the stack
    - pushed_stack_items: number of items the opcode pushes to the stack
    - min_stack_height: minimum stack height required by the opcode
    - data_portion_length: number of bytes after the opcode in the bytecode
        that represent data
    """

    popped_stack_items: int
    pushed_stack_items: int
    min_stack_height: int
    data_portion_length: int
    _name_: str

    def __new__(
        cls,
        opcode_or_byte: Union[int, "Opcode"],
        *,
        popped_stack_items: int = 0,
        pushed_stack_items: int = 0,
        min_stack_height: int = 0,
        data_portion_length: int = 0,
    ):
        """
        Creates a new opcode instance.
        """
        if type(opcode_or_byte) is Opcode:
            # Required because Enum class calls the base class with the instantiated object as
            # parameter.
            return opcode_or_byte
        elif isinstance(opcode_or_byte, int):
            obj = super().__new__(cls, [opcode_or_byte])
            obj.popped_stack_items = popped_stack_items
            obj.pushed_stack_items = pushed_stack_items
            obj.min_stack_height = min_stack_height
            obj.data_portion_length = data_portion_length
            return obj

    def __call__(self, *args_t: Union[int, bytes, str, "Opcode", FixedSizeBytes]) -> bytes:
        """
        Makes all opcode instances callable to return formatted bytecode, which constitutes a data
        portion, that is located after the opcode byte, and pre-opcode bytecode, which is normally
        used to set up the stack.

        This useful to automatically format, e.g., push opcodes and their data sections as
        `Opcodes.PUSH1(0x00)`.

        Data sign is automatically detected but for this reason the range of the input must be:
        `[-2^(data_portion_bits-1), 2^(data_portion_bits)]` where: `data_portion_bits ==
        data_portion_length * 8`

        For the stack, the arguments are set up in the opposite order they are given, so the first
        argument is the last item pushed to the stack.

        The resulting stack arrangement does not take into account opcode stack element
        consumption, so the stack height is not guaranteed to be correct and the user must take
        this into consideration.

        Integers can also be used as stack elements, in which case they are automatically converted
        to PUSH operations, and negative numbers always use a PUSH32 operation.

        `FixedSizeBytes` can also be used as stack elements, which includes `Address` and `Hash`
        types, for each of which a PUSH operation is automatically generated, `PUSH20` and `PUSH32`
        respectively.

        Hex-strings will automatically be converted to bytes.

        """
        args: List[Union[int, bytes, str, "Opcode", FixedSizeBytes]] = list(args_t)
        pre_opcode_bytecode = bytes()
        data_portion = bytes()

        if self.data_portion_length > 0:
            # For opcodes with a data portion, the first argument is the data and the rest of the
            # arguments form the stack.
            if len(args) == 0:
                raise ValueError("Opcode with data portion requires at least one argument")
            data = args.pop(0)
            if isinstance(data, bytes) or isinstance(data, str):
                if isinstance(data, str):
                    if data.startswith("0x"):
                        data = data[2:]
                    data = bytes.fromhex(data)
                assert len(data) <= self.data_portion_length
                data_portion = data.rjust(self.data_portion_length, b"\x00")
            elif isinstance(data, int):
                signed = data < 0
                data_portion = data.to_bytes(
                    length=self.data_portion_length,
                    byteorder="big",
                    signed=signed,
                )
            else:
                raise TypeError("Opcode data portion must be either an int or bytes/hex string")

        # The rest of the arguments conform the stack.
        while len(args) > 0:
            data = args.pop()
            if isinstance(data, int) or isinstance(data, FixedSizeBytes):
                # We are going to push a constant to the stack.
                data_size = 0
                if isinstance(data, int):
                    signed = data < 0
                    data_size = _get_int_size(data)
                    if data_size > 32:
                        raise ValueError("Opcode stack data must be less than 32 bytes")
                    elif data_size == 0:
                        # Pushing 0 is done with the PUSH1 opcode for compatibility reasons.
                        data_size = 1
                    data = data.to_bytes(
                        length=data_size,
                        byteorder="big",
                        signed=signed,
                    )
                elif isinstance(data, FixedSizeBytes):
                    data_size = data.byte_length

                assert isinstance(data, bytes)
                assert data_size > 0
                pre_opcode_bytecode += _push_opcodes_byte_list[data_size]
                pre_opcode_bytecode += data
            elif isinstance(data, bytes) or isinstance(data, str):
                if isinstance(data, str):
                    if data.startswith("0x"):
                        data = data[2:]
                    data = bytes.fromhex(data)
                pre_opcode_bytecode += data

            else:
                raise TypeError("Opcode stack data must be either an int or a bytes/hex string")

        return pre_opcode_bytecode + self + data_portion

    def __len__(self) -> int:
        """
        Returns the total bytecode length of the opcode, taking into account its data portion.
        """
        return self.data_portion_length + 1

    def int(self) -> int:
        """
        Returns the integer representation of the opcode.
        """
        return int.from_bytes(self, byteorder="big")

    def __str__(self) -> str:
        """
        Return the name of the opcode, assigned at Enum creation.
        """
        return self._name_

__new__(opcode_or_byte, *, popped_stack_items=0, pushed_stack_items=0, min_stack_height=0, data_portion_length=0)

Creates a new opcode instance.

Source code in src/ethereum_test_tools/vm/opcode.py
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
def __new__(
    cls,
    opcode_or_byte: Union[int, "Opcode"],
    *,
    popped_stack_items: int = 0,
    pushed_stack_items: int = 0,
    min_stack_height: int = 0,
    data_portion_length: int = 0,
):
    """
    Creates a new opcode instance.
    """
    if type(opcode_or_byte) is Opcode:
        # Required because Enum class calls the base class with the instantiated object as
        # parameter.
        return opcode_or_byte
    elif isinstance(opcode_or_byte, int):
        obj = super().__new__(cls, [opcode_or_byte])
        obj.popped_stack_items = popped_stack_items
        obj.pushed_stack_items = pushed_stack_items
        obj.min_stack_height = min_stack_height
        obj.data_portion_length = data_portion_length
        return obj

__call__(*args_t)

Makes all opcode instances callable to return formatted bytecode, which constitutes a data portion, that is located after the opcode byte, and pre-opcode bytecode, which is normally used to set up the stack.

This useful to automatically format, e.g., push opcodes and their data sections as Opcodes.PUSH1(0x00).

Data sign is automatically detected but for this reason the range of the input must be: [-2^(data_portion_bits-1), 2^(data_portion_bits)] where: data_portion_bits == data_portion_length * 8

For the stack, the arguments are set up in the opposite order they are given, so the first argument is the last item pushed to the stack.

The resulting stack arrangement does not take into account opcode stack element consumption, so the stack height is not guaranteed to be correct and the user must take this into consideration.

Integers can also be used as stack elements, in which case they are automatically converted to PUSH operations, and negative numbers always use a PUSH32 operation.

FixedSizeBytes can also be used as stack elements, which includes Address and Hash types, for each of which a PUSH operation is automatically generated, PUSH20 and PUSH32 respectively.

Hex-strings will automatically be converted to bytes.

Source code in src/ethereum_test_tools/vm/opcode.py
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
def __call__(self, *args_t: Union[int, bytes, str, "Opcode", FixedSizeBytes]) -> bytes:
    """
    Makes all opcode instances callable to return formatted bytecode, which constitutes a data
    portion, that is located after the opcode byte, and pre-opcode bytecode, which is normally
    used to set up the stack.

    This useful to automatically format, e.g., push opcodes and their data sections as
    `Opcodes.PUSH1(0x00)`.

    Data sign is automatically detected but for this reason the range of the input must be:
    `[-2^(data_portion_bits-1), 2^(data_portion_bits)]` where: `data_portion_bits ==
    data_portion_length * 8`

    For the stack, the arguments are set up in the opposite order they are given, so the first
    argument is the last item pushed to the stack.

    The resulting stack arrangement does not take into account opcode stack element
    consumption, so the stack height is not guaranteed to be correct and the user must take
    this into consideration.

    Integers can also be used as stack elements, in which case they are automatically converted
    to PUSH operations, and negative numbers always use a PUSH32 operation.

    `FixedSizeBytes` can also be used as stack elements, which includes `Address` and `Hash`
    types, for each of which a PUSH operation is automatically generated, `PUSH20` and `PUSH32`
    respectively.

    Hex-strings will automatically be converted to bytes.

    """
    args: List[Union[int, bytes, str, "Opcode", FixedSizeBytes]] = list(args_t)
    pre_opcode_bytecode = bytes()
    data_portion = bytes()

    if self.data_portion_length > 0:
        # For opcodes with a data portion, the first argument is the data and the rest of the
        # arguments form the stack.
        if len(args) == 0:
            raise ValueError("Opcode with data portion requires at least one argument")
        data = args.pop(0)
        if isinstance(data, bytes) or isinstance(data, str):
            if isinstance(data, str):
                if data.startswith("0x"):
                    data = data[2:]
                data = bytes.fromhex(data)
            assert len(data) <= self.data_portion_length
            data_portion = data.rjust(self.data_portion_length, b"\x00")
        elif isinstance(data, int):
            signed = data < 0
            data_portion = data.to_bytes(
                length=self.data_portion_length,
                byteorder="big",
                signed=signed,
            )
        else:
            raise TypeError("Opcode data portion must be either an int or bytes/hex string")

    # The rest of the arguments conform the stack.
    while len(args) > 0:
        data = args.pop()
        if isinstance(data, int) or isinstance(data, FixedSizeBytes):
            # We are going to push a constant to the stack.
            data_size = 0
            if isinstance(data, int):
                signed = data < 0
                data_size = _get_int_size(data)
                if data_size > 32:
                    raise ValueError("Opcode stack data must be less than 32 bytes")
                elif data_size == 0:
                    # Pushing 0 is done with the PUSH1 opcode for compatibility reasons.
                    data_size = 1
                data = data.to_bytes(
                    length=data_size,
                    byteorder="big",
                    signed=signed,
                )
            elif isinstance(data, FixedSizeBytes):
                data_size = data.byte_length

            assert isinstance(data, bytes)
            assert data_size > 0
            pre_opcode_bytecode += _push_opcodes_byte_list[data_size]
            pre_opcode_bytecode += data
        elif isinstance(data, bytes) or isinstance(data, str):
            if isinstance(data, str):
                if data.startswith("0x"):
                    data = data[2:]
                data = bytes.fromhex(data)
            pre_opcode_bytecode += data

        else:
            raise TypeError("Opcode stack data must be either an int or a bytes/hex string")

    return pre_opcode_bytecode + self + data_portion

__len__()

Returns the total bytecode length of the opcode, taking into account its data portion.

Source code in src/ethereum_test_tools/vm/opcode.py
172
173
174
175
176
def __len__(self) -> int:
    """
    Returns the total bytecode length of the opcode, taking into account its data portion.
    """
    return self.data_portion_length + 1

int()

Returns the integer representation of the opcode.

Source code in src/ethereum_test_tools/vm/opcode.py
178
179
180
181
182
def int(self) -> int:
    """
    Returns the integer representation of the opcode.
    """
    return int.from_bytes(self, byteorder="big")

__str__()

Return the name of the opcode, assigned at Enum creation.

Source code in src/ethereum_test_tools/vm/opcode.py
184
185
186
187
188
def __str__(self) -> str:
    """
    Return the name of the opcode, assigned at Enum creation.
    """
    return self._name_

Opcodes

Bases: Opcode, Enum

Enum containing all known opcodes.

Contains deprecated and not yet implemented opcodes.

This enum is !! NOT !! meant to be iterated over by the tests. Instead, create a list with cherry-picked opcodes from this Enum within the test if iteration is needed.

Do !! NOT !! remove or modify existing opcodes from this list.

Source code in src/ethereum_test_tools/vm/opcode.py
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
class Opcodes(Opcode, Enum):
    """
    Enum containing all known opcodes.

    Contains deprecated and not yet implemented opcodes.

    This enum is !! NOT !! meant to be iterated over by the tests. Instead, create a list with
    cherry-picked opcodes from this Enum within the test if iteration is needed.

    Do !! NOT !! remove or modify existing opcodes from this list.
    """

    STOP = Opcode(0x00)
    """
    STOP()
    ----

    Description
    ----
    Stop execution

    Inputs
    ----
    - None

    Outputs
    ----
    - None

    Fork
    ----
    Frontier

    Gas
    ----
    0

    Source: [evm.codes/#00](https://www.evm.codes/#00)
    """

    ADD = Opcode(0x01, popped_stack_items=2, pushed_stack_items=1)
    """
    ADD(a, b) = c
    ----

    Description
    ----
    Addition operation

    Inputs
    ----
    - a: first integer value to add
    - b: second integer value to add

    Outputs
    ----
    - c: integer result of the addition modulo 2**256

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#01](https://www.evm.codes/#01)
    """

    MUL = Opcode(0x02, popped_stack_items=2, pushed_stack_items=1)
    """
    MUL(a, b) = c
    ----

    Description
    ----
    Multiplication operation

    Inputs
    ----
    - a: first integer value to multiply
    - b: second integer value to multiply

    Outputs
    ----
    - c: integer result of the multiplication modulo 2**256

    Fork
    ----
    Frontier

    Gas
    ----
    5

    Source: [evm.codes/#02](https://www.evm.codes/#02)
    """

    SUB = Opcode(0x03, popped_stack_items=2, pushed_stack_items=1)
    """
    SUB(a, b) = c
    ----

    Description
    ----
    Subtraction operation

    Inputs
    ----
    - a: first integer value
    - b: second integer value

    Outputs
    ----
    - c: integer result of the subtraction modulo 2**256

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#03](https://www.evm.codes/#03)
    """

    DIV = Opcode(0x04, popped_stack_items=2, pushed_stack_items=1)
    """
    DIV(a, b) = c
    ----

    Description
    ----
    Division operation

    Inputs
    ----
    - a: numerator
    - b: denominator (must be non-zero)

    Outputs
    ----
    - c: integer result of the division

    Fork
    ----
    Frontier

    Gas
    ----
    5

    Source: [evm.codes/#04](https://www.evm.codes/#04)
    """

    SDIV = Opcode(0x05, popped_stack_items=2, pushed_stack_items=1)
    """
    SDIV(a, b) = c
    ----

    Description
    ----
    Signed division operation

    Inputs
    ----
    - a: signed numerator
    - b: signed denominator

    Outputs
    ----
    - c: signed integer result of the division. If the denominator is 0, the result will be 0
    ----

    Fork
    ----
    Frontier

    Gas
    ----
    5

    Source: [evm.codes/#05](https://www.evm.codes/#05)
    """

    MOD = Opcode(0x06, popped_stack_items=2, pushed_stack_items=1)
    """
    MOD(a, b) = c
    ----

    Description
    ----
    Modulo operation

    Inputs
    ----
    - a: integer numerator
    - b: integer denominator

    Outputs
    ----
    - a % b: integer result of the integer modulo. If the denominator is 0, the result will be 0

    Fork
    ----
    Frontier

    Gas
    ----
    5

    Source: [evm.codes/#06](https://www.evm.codes/#06)
    """

    SMOD = Opcode(0x07, popped_stack_items=2, pushed_stack_items=1)
    """
    SMOD(a, b) = c
    ----

    Description
    ----
    Signed modulo remainder operation

    Inputs
    ----
    - a: integer numerator
    - b: integer denominator

    Outputs
    ----
    - a % b: integer result of the signed integer modulo. If the denominator is 0, the result will
        be 0

    Fork
    ----
    Frontier

    Gas
    ----
    5

    Source: [evm.codes/#07](https://www.evm.codes/#07)
    """

    ADDMOD = Opcode(0x08, popped_stack_items=3, pushed_stack_items=1)
    """
    ADDMOD(a, b, c) = d
    ----

    Description
    ----
    Modular addition operation with overflow check

    Inputs
    ----
    - a: first integer value
    - b: second integer value
    - c: integer denominator

    Outputs
    ----
    - (a + b) % N: integer result of the addition followed by a modulo. If the denominator is 0,
        the result will be 0

    Fork
    ----
    Frontier

    Gas
    ----
    8

    Source: [evm.codes/#08](https://www.evm.codes/#08)
    """

    MULMOD = Opcode(0x09, popped_stack_items=3, pushed_stack_items=1)
    """
    MULMOD(a, b, N) = d
    ----

    Description
    ----
    Modulo multiplication operation

    Inputs
    ----
    - a: first integer value to multiply
    - b: second integer value to multiply
    - N: integer denominator

    Outputs
    ----
    - (a * b) % N: integer result of the multiplication followed by a modulo. If the denominator
        is 0, the result will be 0

    Fork
    ----
    Frontier

    Gas
    ----
    8

    Source: [evm.codes/#09](https://www.evm.codes/#09)
    """

    EXP = Opcode(0x0A, popped_stack_items=2, pushed_stack_items=1)
    """
    EXP(a, exponent) = a ** exponent
    ----

    Description
    ----
    Exponential operation

    Inputs
    ----
    - a: integer base
    - exponent: integer exponent

    Outputs
    ----
    - a ** exponent: integer result of the exponential operation modulo 2**256

    Fork
    ----
    Frontier

    Gas
    ----
    - static_gas = 10
    - dynamic_gas = 50 * exponent_byte_size

    Source: [evm.codes/#0A](https://www.evm.codes/#0A)
    """

    SIGNEXTEND = Opcode(0x0B, popped_stack_items=2, pushed_stack_items=1)
    """
    SIGNEXTEND(b, x) = y
    ----

    Description
    ----
    Sign extension operation

    Inputs
    ----
    - b: size in byte - 1 of the integer to sign extend
    - x: integer value to sign extend

    Outputs
    ----
    - y: integer result of the sign extend

    Fork
    ----
    Frontier

    Gas
    ----
    5

    Source: [evm.codes/#0B](https://www.evm.codes/#0B)
    """

    LT = Opcode(0x10, popped_stack_items=2, pushed_stack_items=1)
    """
    LT(a, b) = a < b
    ----

    Description
    ----
    Less-than comparison

    Inputs
    ----
    - a: left side integer value
    - b: right side integer value

    Outputs
    ----
    - a < b: 1 if the left side is smaller, 0 otherwise

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#10](https://www.evm.codes/#10)
    """

    GT = Opcode(0x11, popped_stack_items=2, pushed_stack_items=1)
    """
    GT(a, b) = a > b
    ----

    Description
    ----
    Greater-than comparison

    Inputs
    ----
    - a: left side integer
    - b: right side integer

    Outputs
    ----
    - a > b: 1 if the left side is bigger, 0 otherwise

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#11](https://www.evm.codes/#11)
    """

    SLT = Opcode(0x12, popped_stack_items=2, pushed_stack_items=1)
    """
    SLT(a, b) = a < b
    ----

    Description
    ----
    Signed less-than comparison

    Inputs
    ----
    - a: left side signed integer
    - b: right side signed integer

    Outputs
    ----
    - a < b: 1 if the left side is smaller, 0 otherwise

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#12](https://www.evm.codes/#12)
    """

    SGT = Opcode(0x13, popped_stack_items=2, pushed_stack_items=1)
    """
    SGT(a, b) = a > b
    ----

    Description
    ----
    Signed greater-than comparison

    Inputs
    ----
    - a: left side signed integer
    - b: right side signed integer

    Outputs
    ----
    - a > b: 1 if the left side is bigger, 0 otherwise

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#13](https://www.evm.codes/#13)
    """

    EQ = Opcode(0x14, popped_stack_items=2, pushed_stack_items=1)
    """
    EQ(a, b) = a == b
    ----

    Description
    ----
    Equality comparison

    Inputs
    ----
    - a: left side integer
    - b: right side integer

    Outputs
    ----
    - a == b: 1 if the left side is equal to the right side, 0 otherwise

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#14](https://www.evm.codes/#14)
    """

    ISZERO = Opcode(0x15, popped_stack_items=1, pushed_stack_items=1)
    """
    ISZERO(a) = a == 0
    ----

    Description
    ----
    Is-zero comparison

    Inputs
    ----
    - a: integer

    Outputs
    ----
    - a == 0: 1 if a is 0, 0 otherwise

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#15](https://www.evm.codes/#15)
    """

    AND = Opcode(0x16, popped_stack_items=2, pushed_stack_items=1)
    """
    AND(a, b) = a & b
    ----

    Description
    ----
    Bitwise AND operation

    Inputs
    ----
    - a: first binary value
    - b: second binary value

    Outputs
    ----
    - a & b: the bitwise AND result

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#16](https://www.evm.codes/#16)
    """

    OR = Opcode(0x17, popped_stack_items=2, pushed_stack_items=1)
    """
    OR(a, b) = a | b
    ----

    Description
    ----
    Bitwise OR operation

    Inputs
    ----
    - a: first binary value
    - b: second binary value

    Outputs
    ----
    - a | b: the bitwise OR result

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#17](https://www.evm.codes/#17)
    """

    XOR = Opcode(0x18, popped_stack_items=2, pushed_stack_items=1)
    """
    XOR(a, b) = a ^ b
    ----

    Description
    ----
    Bitwise XOR operation

    Inputs
    ----
    - a: first binary value
    - b: second binary value

    Outputs
    ----
    - a ^ b: the bitwise XOR result

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#18](https://www.evm.codes/#18)
    """

    NOT = Opcode(0x19, popped_stack_items=1, pushed_stack_items=1)
    """
    NOT(a) = ~a
    ----

    Description
    ----
    Bitwise NOT operation

    Inputs
    ----
    - a: binary value

    Outputs
    ----
    - ~a: the bitwise NOT result

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#19](https://www.evm.codes/#19)
    """

    BYTE = Opcode(0x1A, popped_stack_items=2, pushed_stack_items=1)
    """
    BYTE(i, x) = y
    ----

    Description
    ----
    Extract a byte from the given position in the value

    Inputs
    ----
    - i: byte offset starting from the most significant byte
    - x: 32-byte value

    Outputs
    ----
    - y: the indicated byte at the least significant position. If the byte offset is out of range,
        the result is 0

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#1A](https://www.evm.codes/#1A)
    """

    SHL = Opcode(0x1B, popped_stack_items=2, pushed_stack_items=1)
    """
    SHL(shift, value) = value << shift
    ----

    Description
    ----
    Shift left operation

    Inputs
    ----
    - shift: number of bits to shift to the left
    - value: 32 bytes to shift

    Outputs
    ----
    - value << shift: the shifted value. If shift is bigger than 255, returns 0

    Fork
    ----
    Constantinople

    Gas
    ----
    3

    Source: [evm.codes/#1B](https://www.evm.codes/#1B)
    """

    SHR = Opcode(0x1C, popped_stack_items=2, pushed_stack_items=1)
    """
    SHR(shift, value) = value >> shift
    ----

    Description
    ----
    Logical shift right operation

    Inputs
    ----
    - shift: number of bits to shift to the right.
    - value: 32 bytes to shift

    Outputs
    ----
    - value >> shift: the shifted value. If shift is bigger than 255, returns 0

    Fork
    ----
    Constantinople

    Gas
    ----
    3

    Source: [evm.codes/#1C](https://www.evm.codes/#1C)
    """

    SAR = Opcode(0x1D, popped_stack_items=2, pushed_stack_items=1)
    """
    SAR(shift, value) = value >> shift
    ----

    Description
    ----
    Arithmetic shift right operation

    Inputs
    ----
    - shift: number of bits to shift to the right
    - value: integer to shift

    Outputs
    ----
    - value >> shift: the shifted value

    Fork
    ----
    Constantinople

    Gas
    ----
    3

    Source: [evm.codes/#1D](https://www.evm.codes/#1D)
    """

    SHA3 = Opcode(0x20, popped_stack_items=2, pushed_stack_items=1)
    """
    SHA3(start, length) = hash
    ----

    Description
    ----
    Compute Keccak-256 hash

    Inputs
    ----
    - offset: byte offset in the memory
    - size: byte size to read in the memory

    Outputs
    ----
    - hash: Keccak-256 hash of the given data in memory

    Fork
    ----
    Frontier

    Gas
    ----
    - minimum_word_size = (size + 31) / 32
    - static_gas = 30
    - dynamic_gas = 6 * minimum_word_size + memory_expansion_cost

    Source: [evm.codes/#20](https://www.evm.codes/#20)
    """

    ADDRESS = Opcode(0x30, pushed_stack_items=1)
    """
    ADDRESS() = address
    ----

    Description
    ----
    Get address of currently executing account

    Inputs
    ----
    - None

    Outputs
    ----
    - address: the 20-byte address of the current account

    Fork
    ----
    Frontier

    Gas
    ----
    2

    Source: [evm.codes/#30](https://www.evm.codes/#30)
    """

    BALANCE = Opcode(0x31, popped_stack_items=1, pushed_stack_items=1)
    """
    BALANCE(address) = balance
    ----

    Description
    ----
    Get the balance of the specified account

    Inputs
    ----
    - address: 20-byte address of the account to check

    Outputs
    ----
    - balance: balance of the given account in wei. Returns 0 if the account doesn't exist

    Fork
    ----
    Frontier

    Gas
    ----
    - static_gas = 0
    - dynamic_gas = 100 if warm_address, 2600 if cold_address

    Source: [evm.codes/#31](https://www.evm.codes/#31)
    """

    ORIGIN = Opcode(0x32, pushed_stack_items=1)
    """
    ORIGIN() = address
    ----

    Description
    ----
    Get execution origination address

    Inputs
    ----
    - None

    Outputs
    ----
    - address: the 20-byte address of the sender of the transaction. It can only be an account
        without code

    Fork
    ----
    Frontier

    Gas
    ----
    2

    Source: [evm.codes/#32](https://www.evm.codes/#32)
    """

    CALLER = Opcode(0x33, pushed_stack_items=1)
    """
    CALLER() = address
    ----

    Description
    ----
    Get caller address

    Inputs
    ----
    - None

    Outputs
    ----
    - address: the 20-byte address of the caller account. This is the account that did the last
        call (except delegate call)

    Fork
    ----
    Frontier

    Gas
    ----
    2

    Source: [evm.codes/#33](https://www.evm.codes/#33)
    """

    CALLVALUE = Opcode(0x34, pushed_stack_items=1)
    """
    CALLVALUE() = value
    ----

    Description
    ----
    Get deposited value by the instruction/transaction responsible for this execution

    Inputs
    ----
    - None

    Outputs
    ----
    - value: the value of the current call in wei

    Fork
    ----
    Frontier

    Gas
    ----
    2

    Source: [evm.codes/#34](https://www.evm.codes/#34)
    """

    CALLDATALOAD = Opcode(0x35, popped_stack_items=1, pushed_stack_items=1)
    """
    CALLDATALOAD(i) = data[i]
    ----

    Description
    ----
    Get input data of current environment

    Inputs
    ----
    - i: byte offset in the calldata

    Outputs
    ----
    - data[i]: 32-byte value starting from the given offset of the calldata. All bytes after the
        end of the calldata are set to 0

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#35](https://www.evm.codes/#35)
    """

    CALLDATASIZE = Opcode(0x36, pushed_stack_items=1)
    """
    CALLDATASIZE() = size
    ----

    Description
    ----
    Get size of input data in current environment

    Inputs
    ----
    - None

    Outputs
    ----
    - size: byte size of the calldata

    Fork
    ----
    Frontier

    Gas
    ----
    2

    Source: [evm.codes/#36](https://www.evm.codes/#36)
    """

    CALLDATACOPY = Opcode(0x37, popped_stack_items=3)
    """
    CALLDATACOPY(destOffset, offset, size)
    ----

    Description
    ----
    Copy input data in current environment to memory

    Inputs
    ----
    - destOffset: byte offset in the memory where the result will be copied
    - offset: byte offset in the calldata to copy
    - size: byte size to copy

    Outputs
    ----
    - None

    Fork
    ----
    Frontier

    Gas
    ----
    - minimum_word_size = (size + 31) / 32
    - static_gas = 3
    - dynamic_gas = 3 * minimum_word_size + memory_expansion_cost

    Source: [evm.codes/#37](https://www.evm.codes/#37)
    """

    CODESIZE = Opcode(0x38, pushed_stack_items=1)
    """
    CODESIZE() = size
    ----

    Description
    ----
    Get size of code running in current environment

    Inputs
    ----
    - None

    Outputs
    ----
    - size: byte size of the code

    Fork
    ----
    Frontier

    Gas
    ----
    2

    Source: [evm.codes/#38](https://www.evm.codes/#38)
    """

    CODECOPY = Opcode(0x39, popped_stack_items=3)
    """
    CODECOPY(destOffset, offset, size)
    ----

    Description
    ----
    Copy code running in current environment to memory

    Inputs
    ----
    - destOffset: byte offset in the memory where the result will be copied.
    - offset: byte offset in the code to copy.
    - size: byte size to copy

    Fork
    ----
    Frontier

    Gas
    ----
    - minimum_word_size = (size + 31) / 32
    - static_gas = 3
    - dynamic_gas = 3 * minimum_word_size + memory_expansion_cost

    Source: [evm.codes/#39](https://www.evm.codes/#39)
    """

    GASPRICE = Opcode(0x3A, pushed_stack_items=1)
    """
    GASPRICE() = price
    ----

    Description
    ----
    Get price of gas in current environment

    Outputs
    ----
    - price: gas price in wei per gas

    Fork
    ----
    Frontier

    Gas
    ----
    2

    Source: [evm.codes/#3A](https://www.evm.codes/#3A)
    """

    EXTCODESIZE = Opcode(0x3B, popped_stack_items=1, pushed_stack_items=1)
    """
    EXTCODESIZE(account) = size
    ----

    Description
    ----
    Get size of an account's code

    Inputs
    ----
    - address: 20-byte address of the contract to query

    Outputs
    ----
    - size: byte size of the code

    Fork
    ----
    Frontier

    Gas
    ----
    - static_gas = 0
    - dynamic_gas = 100 if warm_address, 2600 if cold_address

    Source: [evm.codes/#3B](https://www.evm.codes/#3B)
    """

    EXTCODECOPY = Opcode(0x3C, popped_stack_items=4)
    """
    EXTCODECOPY(addr, destOffset, offset, size)
    ----

    Description
    ----
    Copy an account's code to memory

    Inputs
    ----
    - address: 20-byte address of the contract to query
    - destOffset: byte offset in the memory where the result will be copied
    - offset: byte offset in the code to copy
    - size: byte size to copy

    Outputs
    ----
    - None

    Fork
    ----
    Frontier

    Gas
    ----
    - minimum_word_size = (size + 31) / 32
    - static_gas = 0
    - dynamic_gas = 3 * minimum_word_size + memory_expansion_cost + address_access_cost

    Source: [evm.codes/#3C](https://www.evm.codes/#3C)
    """

    RETURNDATASIZE = Opcode(0x3D, pushed_stack_items=1)
    """
    RETURNDATASIZE() = size
    ----

    Description
    ----
    Get size of output data from the previous call from the current environment

    Outputs
    ----
    - size: byte size of the return data from the last executed sub context

    Fork
    ----
    Byzantium

    Gas
    ----
    2

    Source: [evm.codes/#3D](https://www.evm.codes/#3D)
    """

    RETURNDATACOPY = Opcode(0x3E, popped_stack_items=3)
    """
    RETURNDATACOPY(destOffset, offset, size)
    ----

    Description
    ----
    Copy output data from the previous call to memory

    Inputs
    ----
    - destOffset: byte offset in the memory where the result will be copied
    - offset: byte offset in the return data from the last executed sub context to copy
    - size: byte size to copy

    Fork
    ----
    Byzantium

    Gas
    ----
    - minimum_word_size = (size + 31) / 32
    - static_gas = 3
    - dynamic_gas = 3 * minimum_word_size + memory_expansion_cost

    Source: [evm.codes/#3E](https://www.evm.codes/#3E)
    """

    EXTCODEHASH = Opcode(0x3F, popped_stack_items=1, pushed_stack_items=1)
    """
    EXTCODEHASH(address) = hash
    ----

    Description
    ----
    Get hash of an account's code

    Inputs
    ----
    - address: 20-byte address of the account

    Outputs
    ----
    - hash: hash of the chosen account's code, the empty hash (0xc5d24601...) if the account has no
        code, or 0 if the account does not exist or has been destroyed

    Fork
    ----
    Constantinople

    Gas
    ----
    - static_gas = 0
    - dynamic_gas = 100 if warm_address, 2600 if cold_address

    Source: [evm.codes/#3F](https://www.evm.codes/#3F)
    """

    BLOCKHASH = Opcode(0x40, popped_stack_items=1, pushed_stack_items=1)
    """
    BLOCKHASH(block_number) = hash
    ----

    Description
    ----
    Get the hash of one of the 256 most recent complete blocks

    Inputs
    ----
    - blockNumber: block number to get the hash from. Valid range is the last 256 blocks (not
        including the current one). Current block number can be queried with NUMBER

    Outputs
    ----
    - hash: hash of the chosen block, or 0 if the block number is not in the valid range

    Fork
    ----
    Frontier

    Gas
    ----
    20

    Source: [evm.codes/#40](https://www.evm.codes/#40)
    """

    COINBASE = Opcode(0x41, pushed_stack_items=1)
    """
    COINBASE() = address
    ----

    Description
    ----
    Get the block's beneficiary address

    Inputs
    ----
    - None

    Outputs
    ----
    - address: miner's 20-byte address

    Fork
    ----
    Frontier

    Gas
    ----
    2

    Source: [evm.codes/#41](https://www.evm.codes/#41)
    """

    TIMESTAMP = Opcode(0x42, pushed_stack_items=1)
    """
    TIMESTAMP() = timestamp
    ----

    Description
    ----
    Get the block's timestamp

    Inputs
    ----
    - None

    Outputs
    ----
    - timestamp: unix timestamp of the current block

    Fork
    ----
    Frontier

    Gas
    ----
    2

    Source: [evm.codes/#42](https://www.evm.codes/#42)
    """

    NUMBER = Opcode(0x43, pushed_stack_items=1)
    """
    NUMBER() = blockNumber
    ----

    Description
    ----
    Get the block's number

    Inputs
    ----
    - None

    Outputs
    ----
    - blockNumber: current block number

    Fork
    ----
    Frontier

    Gas
    ----
    2

    Source: [evm.codes/#43](https://www.evm.codes/#43)
    """

    PREVRANDAO = Opcode(0x44, pushed_stack_items=1)
    """
    PREVRANDAO() = prevRandao
    ----

    Description
    ----
    Get the previous block's RANDAO mix

    Inputs
    ----
    - None

    Outputs
    ----
    - prevRandao: previous block's RANDAO mix

    Fork
    ----
    Merge

    Gas
    ----
    2

    Source: [evm.codes/#44](https://www.evm.codes/#44)
    """

    GASLIMIT = Opcode(0x45, pushed_stack_items=1)
    """
    GASLIMIT() = gasLimit
    ----

    Description
    ----
    Get the block's gas limit

    Inputs
    ----
    - None

    Outputs
    ----
    - gasLimit: gas limit

    Fork
    ----
    Frontier

    Gas
    ----
    2

    Source: [evm.codes/#45](https://www.evm.codes/#45)
    """

    CHAINID = Opcode(0x46, pushed_stack_items=1)
    """
    CHAINID() = chainId
    ----

    Description
    ----
    Get the chain ID

    Inputs
    ----
    - None

    Outputs
    ----
    - chainId: chain id of the network

    Fork
    ----
    Istanbul

    Gas
    ----
    2

    Source: [evm.codes/#46](https://www.evm.codes/#46)
    """

    SELFBALANCE = Opcode(0x47, pushed_stack_items=1)
    """
    SELFBALANCE() = balance
    ----

    Description
    ----
    Get balance of currently executing account

    Inputs
    ----
    - None

    Outputs
    ----
    - balance: balance of the current account in wei

    Fork
    ----
    Istanbul

    Gas
    ----
    5

    Source: [evm.codes/#47](https://www.evm.codes/#47)
    """

    BASEFEE = Opcode(0x48, pushed_stack_items=1)
    """
    BASEFEE() = baseFee
    ----

    Description
    ----
    Get the base fee

    Outputs
    ----
    - baseFee: base fee in wei

    Fork
    ----
    London

    Gas
    ----
    2

    Source: [evm.codes/#48](https://www.evm.codes/#48)
    """

    BLOBHASH = Opcode(0x49, popped_stack_items=1, pushed_stack_items=1)
    """
    BLOBHASH(index) = versionedHash
    ----

    Description
    ----
    Returns the versioned hash of a single blob contained in the type-3 transaction

    Inputs
    ----
    - index: index of the blob

    Outputs
    ----
    - versionedHash: versioned hash of the blob

    Fork
    ----
    Cancun

    Gas
    ----
    3

    Source: [eips.ethereum.org/EIPS/eip-4844](https://eips.ethereum.org/EIPS/eip-4844)
    """

    BLOBBASEFEE = Opcode(0x4A, popped_stack_items=0, pushed_stack_items=1)
    """
    BLOBBASEFEE() = fee
    ----

    Description
    ----
    Returns the value of the blob base fee of the block it is executing in

    Inputs
    ----
    - None

    Outputs
    ----
    - baseFeePerBlobGas: base fee for the blob gas in wei

    Fork
    ----
    Cancun

    Gas
    ----
    2

    Source: [eips.ethereum.org/EIPS/eip-7516](https://eips.ethereum.org/EIPS/eip-7516)
    """

    POP = Opcode(0x50, popped_stack_items=1)
    """
    POP()
    ----

    Description
    ----
    Remove item from stack

    Inputs
    ----
    - None

    Outputs
    ----
    - None

    Fork
    ----
    Frontier

    Gas
    ----
    2

    Source: [evm.codes/#50](https://www.evm.codes/#50)
    """

    MLOAD = Opcode(0x51, popped_stack_items=1, pushed_stack_items=1)
    """
    MLOAD(offset) = value
    ----

    Description
    ----
    Load word from memory

    Inputs
    ----
    - offset: offset in the memory in bytes

    Outputs
    ----
    - value: the 32 bytes in memory starting at that offset. If it goes beyond its current size
        (see MSIZE), writes 0s

    Fork
    ----
    Frontier

    Gas
    ----
    - static_gas = 3
    - dynamic_gas = memory_expansion_cost

    Source: [evm.codes/#51](https://www.evm.codes/#51)
    """

    MSTORE = Opcode(0x52, popped_stack_items=2)
    """
    MSTORE(offset, value)
    ----

    Description
    ----
    Save word to memory

    Inputs
    ----
    - offset: offset in the memory in bytes
    - value: 32-byte value to write in the memory

    Outputs
    ----
    - None

    Fork
    ----
    Frontier

    Gas
    ----
    - static_gas = 3
    - dynamic_gas = memory_expansion_cost

    Source: [evm.codes/#52](https://www.evm.codes/#52)
    """

    MSTORE8 = Opcode(0x53, popped_stack_items=2)
    """
    MSTORE8(offset, value)
    ----

    Description
    ----
    Save byte to memory

    Inputs
    ----
    - offset: offset in the memory in bytes
    - value: 1-byte value to write in the memory (the least significant byte of the 32-byte stack
        value)

    Fork
    ----
    Frontier

    Gas
    ----
    - static_gas = 3
    - dynamic_gas = memory_expansion_cost

    Source: [evm.codes/#53](https://www.evm.codes/#53)
    """

    SLOAD = Opcode(0x54, popped_stack_items=1, pushed_stack_items=1)
    """
    SLOAD(key) = value
    ----

    Description
    ----
    Load word from storage

    Inputs
    ----
    - key: 32-byte key in storage

    Outputs
    ----
    - value: 32-byte value corresponding to that key. 0 if that key was never written before

    Fork
    ----
    Frontier

    Gas
    ----
    - static_gas = 0
    - dynamic_gas = 100 if warm_address, 2600 if cold_address

    Source: [evm.codes/#54](https://www.evm.codes/#54)
    """

    SSTORE = Opcode(0x55, popped_stack_items=2)
    """
    SSTORE(key, value)
    ----

    Description
    ----
    Save word to storage

    Inputs
    ----
    - key: 32-byte key in storage
    - value: 32-byte value to store

    Outputs
    ----
    - None

    Fork
    ----
    Frontier

    Gas
    ----
    ```
    static_gas = 0

    if value == current_value
        if key is warm
            base_dynamic_gas = 100
        else
            base_dynamic_gas = 100
    else if current_value == original_value
        if original_value == 0
            base_dynamic_gas = 20000
        else
            base_dynamic_gas = 2900
    else
        base_dynamic_gas = 100

    if key is cold:
        base_dynamic_gas += 2100
    ```

    Source: [evm.codes/#55](https://www.evm.codes/#55)
    """

    JUMP = Opcode(0x56, popped_stack_items=1)
    """
    JUMP(counter)
    ----

    Description
    ----
    Alter the program counter

    Inputs
    ----
    - counter: byte offset in the deployed code where execution will continue from. Must be a
        JUMPDEST instruction

    Outputs
    ----
    - None

    Fork
    ----
    Frontier

    Gas
    ----
    8

    Source: [evm.codes/#56](https://www.evm.codes/#56)
    """

    JUMPI = Opcode(0x57, popped_stack_items=2)
    """
    JUMPI(counter, b)
    ----

    Description
    ----
    Conditionally alter the program counter

    Inputs
    ----
    - counter: byte offset in the deployed code where execution will continue from. Must be a
        JUMPDEST instruction
    - b: the program counter will be altered with the new value only if this value is different
        from 0. Otherwise, the program counter is simply incremented and the next instruction will
        be executed

    Fork
    ----
    Frontier

    Gas
    ----
    10

    Source: [evm.codes/#57](https://www.evm.codes/#57)
    """

    PC = Opcode(0x58, pushed_stack_items=1)
    """
    PC() = counter
    ----

    Description
    ----
    Get the value of the program counter prior to the increment corresponding to this instruction

    Inputs
    ----
    - None

    Outputs
    ----
    - counter: PC of this instruction in the current program.

    Fork
    ----
    Frontier

    Gas
    ----
    2

    Source: [evm.codes/#58](https://www.evm.codes/#58)
    """

    MSIZE = Opcode(0x59, pushed_stack_items=1)
    """
    MSIZE() = size
    ----

    Description
    ----
    Get the size of active memory in bytes

    Outputs
    ----
    - size: current memory size in bytes (higher offset accessed until now + 1)

    Fork
    ----
    Frontier

    Gas
    ----
    2

    Source: [evm.codes/#59](https://www.evm.codes/#59)
    """

    GAS = Opcode(0x5A, pushed_stack_items=1)
    """
    GAS() = gas_remaining
    ----

    Description
    ----
    Get the amount of available gas, including the corresponding reduction for the cost of this
    instruction

    Inputs
    ----
    - None

    Outputs
    ----
    - gas: remaining gas (after this instruction)

    Fork
    ----
    Frontier

    Gas
    ----
    2

    Source: [evm.codes/#5A](https://www.evm.codes/#5A)
    """

    JUMPDEST = Opcode(0x5B)
    """
    JUMPDEST()
    ----

    Description
    ----
    Mark a valid destination for jumps

    Inputs
    ----
    - None

    Outputs
    ----
    - None

    Fork
    ----
    Frontier

    Gas
    ----
    1

    Source: [evm.codes/#5B](https://www.evm.codes/#5B)
    """

    TLOAD = Opcode(0x5C, popped_stack_items=1, pushed_stack_items=1)
    """
    TLOAD(key) = value
    ----

    Description
    ----
    Load word from transient storage

    Inputs
    ----
    - key: 32-byte key in transient storage

    Outputs
    ----
    - value: 32-byte value corresponding to that key. 0 if that key was never written

    Fork
    ----
    Cancun

    Gas
    ----
    100

    Source: [eips.ethereum.org/EIPS/eip-1153](https://eips.ethereum.org/EIPS/eip-1153)
    """

    TSTORE = Opcode(0x5D, popped_stack_items=2)
    """
    TSTORE(key, value)
    ----

    Description
    ----
    Save word to transient storage

    Inputs
    ----
    - key: 32-byte key in transient storage
    - value: 32-byte value to store

    Fork
    ----
    Cancun

    Gas
    ----
    100

    Source: [eips.ethereum.org/EIPS/eip-1153](https://eips.ethereum.org/EIPS/eip-1153)
    """

    MCOPY = Opcode(0x5E, popped_stack_items=3)
    """
    MCOPY(dst, src, length)
    ----

    Description
    ----
    Copies areas in memory

    Inputs
    ----
    - dst: byte offset in the memory where the result will be copied
    - src: byte offset in the calldata to copy
    - length: byte size to copy

    Outputs
    ----
    - None

    Fork
    ----
    Cancun

    Gas
    ----
    - minimum_word_size = (length + 31) / 32
    - static_gas = 3
    - dynamic_gas = 3 * minimum_word_size + memory_expansion_cost

    Source: [eips.ethereum.org/EIPS/eip-5656](https://eips.ethereum.org/EIPS/eip-5656)
    """

    PUSH0 = Opcode(0x5F, pushed_stack_items=1)
    """
    PUSH0() = value
    ----

    Description
    ----
    Place value 0 on stack

    Inputs
    ----
    - None

    Outputs
    ----
    - value: pushed value, equal to 0

    Fork
    ----
    Shanghai

    Gas
    ----
    2

    Source: [evm.codes/#5F](https://www.evm.codes/#5F)
    """

    PUSH1 = Opcode(0x60, pushed_stack_items=1, data_portion_length=1)
    """
    PUSH1() = value
    ----

    Description
    ----
    Place 1 byte item on stack

    Inputs
    ----
    - None

    Outputs
    ----
    - value: pushed value, aligned to the right (put in the lowest significant bytes)

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#60](https://www.evm.codes/#60)
    """

    PUSH2 = Opcode(0x61, pushed_stack_items=1, data_portion_length=2)
    """
    PUSH2() = value
    ----

    Description
    ----
    Place 2 byte item on stack

    Inputs
    ----
    - None

    Outputs
    ----
    - value: pushed value, aligned to the right (put in the lowest significant bytes)

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#61](https://www.evm.codes/#61)
    """

    PUSH3 = Opcode(0x62, pushed_stack_items=1, data_portion_length=3)
    """
    PUSH3() = value
    ----

    Description
    ----
    Place 3 byte item on stack

    Inputs
    ----
    - None

    Outputs
    ----
    - value: pushed value, aligned to the right (put in the lowest significant bytes)

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#62](https://www.evm.codes/#62)
    """

    PUSH4 = Opcode(0x63, pushed_stack_items=1, data_portion_length=4)
    """
    PUSH4() = value
    ----

    Description
    ----
    Place 4 byte item on stack

    Inputs
    ----
    - None

    Outputs
    ----
    - value: pushed value, aligned to the right (put in the lowest significant bytes)

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#63](https://www.evm.codes/#63)
    """

    PUSH5 = Opcode(0x64, pushed_stack_items=1, data_portion_length=5)
    """
    PUSH5() = value
    ----

    Description
    ----
    Place 5 byte item on stack

    Inputs
    ----
    - None

    Outputs
    ----
    - value: pushed value, aligned to the right (put in the lowest significant bytes)

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#64](https://www.evm.codes/#64)
    """

    PUSH6 = Opcode(0x65, pushed_stack_items=1, data_portion_length=6)
    """
    PUSH6() = value
    ----

    Description
    ----
    Place 6 byte item on stack

    Inputs
    ----
    - None

    Outputs
    ----
    - value: pushed value, aligned to the right (put in the lowest significant bytes)

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#65](https://www.evm.codes/#65)
    """

    PUSH7 = Opcode(0x66, pushed_stack_items=1, data_portion_length=7)
    """
    PUSH7() = value
    ----

    Description
    ----
    Place 7 byte item on stack

    Inputs
    ----
    - None

    Outputs
    ----
    - value: pushed value, aligned to the right (put in the lowest significant bytes)

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#66](https://www.evm.codes/#66)
    """

    PUSH8 = Opcode(0x67, pushed_stack_items=1, data_portion_length=8)
    """
    PUSH8() = value
    ----

    Description
    ----
    Place 8 byte item on stack

    Inputs
    ----
    - None

    Outputs
    ----
    - value: pushed value, aligned to the right (put in the lowest significant bytes)

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#67](https://www.evm.codes/#67)
    """

    PUSH9 = Opcode(0x68, pushed_stack_items=1, data_portion_length=9)
    """
    PUSH9() = value
    ----

    Description
    ----
    Place 9 byte item on stack

    Inputs
    ----
    - None

    Outputs
    ----
    - value: pushed value, aligned to the right (put in the lowest significant bytes)

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#68](https://www.evm.codes/#68)
    """

    PUSH10 = Opcode(0x69, pushed_stack_items=1, data_portion_length=10)
    """
    PUSH10() = value
    ----

    Description
    ----
    Place 10 byte item on stack

    Inputs
    ----
    - None

    Outputs
    ----
    - value: pushed value, aligned to the right (put in the lowest significant bytes)

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#69](https://www.evm.codes/#69)
    """

    PUSH11 = Opcode(0x6A, pushed_stack_items=1, data_portion_length=11)
    """
    PUSH11() = value
    ----

    Description
    ----
    Place 11 byte item on stack

    Inputs
    ----
    - None

    Outputs
    ----
    - value: pushed value, aligned to the right (put in the lowest significant bytes)

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#6A](https://www.evm.codes/#6A)
    """

    PUSH12 = Opcode(0x6B, pushed_stack_items=1, data_portion_length=12)
    """
    PUSH12() = value
    ----

    Description
    ----
    Place 12 byte item on stack

    Inputs
    ----
    - None

    Outputs
    ----
    - value: pushed value, aligned to the right (put in the lowest significant bytes)

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#6B](https://www.evm.codes/#6B)
    """

    PUSH13 = Opcode(0x6C, pushed_stack_items=1, data_portion_length=13)
    """
    PUSH13() = value
    ----

    Description
    ----
    Place 13 byte item on stack

    Inputs
    ----
    - None

    Outputs
    ----
    - value: pushed value, aligned to the right (put in the lowest significant bytes)

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#6C](https://www.evm.codes/#6C)
    """

    PUSH14 = Opcode(0x6D, pushed_stack_items=1, data_portion_length=14)
    """
    PUSH14() = value
    ----

    Description
    ----
    Place 14 byte item on stack

    Inputs
    ----
    - None

    Outputs
    ----
    - value: pushed value, aligned to the right (put in the lowest significant bytes)

    Fork
    ----
    Frontier


    Gas
    ----
    3

    Source: [evm.codes/#6D](https://www.evm.codes/#6D)
    """

    PUSH15 = Opcode(0x6E, pushed_stack_items=1, data_portion_length=15)
    """
    PUSH15() = value
    ----

    Description
    ----
    Place 15 byte item on stack

    Inputs
    ----
    - None

    Outputs
    ----
    - value: pushed value, aligned to the right (put in the lowest significant bytes)

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#6E](https://www.evm.codes/#6E)
    """

    PUSH16 = Opcode(0x6F, pushed_stack_items=1, data_portion_length=16)
    """
    PUSH16() = value
    ----

    Description
    ----
    Place 16 byte item on stack

    Inputs
    ----
    - None

    Outputs
    ----
    - value: pushed value, aligned to the right (put in the lowest significant bytes)

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#6F](https://www.evm.codes/#6F)
    """

    PUSH17 = Opcode(0x70, pushed_stack_items=1, data_portion_length=17)
    """
    PUSH17() = value
    ----

    Description
    ----
    Place 17 byte item on stack

    Inputs
    ----
    - None

    Outputs
    ----
    - value: pushed value, aligned to the right (put in the lowest significant bytes)

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#70](https://www.evm.codes/#70)
    """

    PUSH18 = Opcode(0x71, pushed_stack_items=1, data_portion_length=18)
    """
    PUSH18() = value
    ----

    Description
    ----
    Place 18 byte item on stack

    Inputs
    ----
    - None

    Outputs
    ----
    - value: pushed value, aligned to the right (put in the lowest significant bytes)

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#71](https://www.evm.codes/#71)
    """

    PUSH19 = Opcode(0x72, pushed_stack_items=1, data_portion_length=19)
    """
    PUSH19() = value
    ----

    Description
    ----
    Place 19 byte item on stack

    Inputs
    ----
    - None

    Outputs
    ----
    - value: pushed value, aligned to the right (put in the lowest significant bytes)

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#72](https://www.evm.codes/#72)
    """

    PUSH20 = Opcode(0x73, pushed_stack_items=1, data_portion_length=20)
    """
    PUSH20() = value
    ----

    Description
    ----
    Place 20 byte item on stack

    Inputs
    ----
    - None

    Outputs
    ----
    - value: pushed value, aligned to the right (put in the lowest significant bytes)

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#73](https://www.evm.codes/#73)
    """

    PUSH21 = Opcode(0x74, pushed_stack_items=1, data_portion_length=21)
    """
    PUSH21() = value
    ----

    Description
    ----
    Place 21 byte item on stack

    Inputs
    ----
    - None

    Outputs
    ----
    - value: pushed value, aligned to the right (put in the lowest significant bytes)

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#74](https://www.evm.codes/#74)
    """

    PUSH22 = Opcode(0x75, pushed_stack_items=1, data_portion_length=22)
    """
    PUSH22() = value
    ----

    Description
    ----
    Place 22 byte item on stack

    Inputs
    ----
    - None

    Outputs
    ----
    - value: pushed value, aligned to the right (put in the lowest significant bytes)

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#75](https://www.evm.codes/#75)
    """

    PUSH23 = Opcode(0x76, pushed_stack_items=1, data_portion_length=23)
    """
    PUSH23() = value
    ----

    Description
    ----
    Place 23 byte item on stack

    Inputs
    ----
    - None

    Outputs
    ----
    - value: pushed value, aligned to the right (put in the lowest significant bytes)

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#76](https://www.evm.codes/#76)
    """

    PUSH24 = Opcode(0x77, pushed_stack_items=1, data_portion_length=24)
    """
    PUSH24() = value
    ----

    Description
    ----
    Place 24 byte item on stack

    Inputs
    ----
    - None

    Outputs
    ----
    - value: pushed value, aligned to the right (put in the lowest significant bytes)

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#77](https://www.evm.codes/#77)
    """

    PUSH25 = Opcode(0x78, pushed_stack_items=1, data_portion_length=25)
    """
    PUSH25() = value
    ----

    Description
    ----
    Place 25 byte item on stack

    Inputs
    ----
    - None

    Outputs
    ----
    - value: pushed value, aligned to the right (put in the lowest significant bytes)

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#78](https://www.evm.codes/#78)
    """

    PUSH26 = Opcode(0x79, pushed_stack_items=1, data_portion_length=26)
    """
    PUSH26() = value
    ----

    Description
    ----
    Place 26 byte item on stack

    Inputs
    ----
    - None

    Outputs
    ----
    - value: pushed value, aligned to the right (put in the lowest significant bytes)

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#79](https://www.evm.codes/#79)
    """

    PUSH27 = Opcode(0x7A, pushed_stack_items=1, data_portion_length=27)
    """
    PUSH27() = value
    ----

    Description
    ----
    Place 27 byte item on stack

    Inputs
    ----
    - None

    Outputs
    ----
    - value: pushed value, aligned to the right (put in the lowest significant bytes)

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#7A](https://www.evm.codes/#7A)
    """

    PUSH28 = Opcode(0x7B, pushed_stack_items=1, data_portion_length=28)
    """
    PUSH28() = value
    ----

    Description
    ----
    Place 28 byte item on stack

    Inputs
    ----
    - None

    Outputs
    ----
    - value: pushed value, aligned to the right (put in the lowest significant bytes)

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#7B](https://www.evm.codes/#7B)
    """

    PUSH29 = Opcode(0x7C, pushed_stack_items=1, data_portion_length=29)
    """
    PUSH29() = value
    ----

    Description
    ----
    Place 29 byte item on stack

    Inputs
    ----
    - None

    Outputs
    ----
    - value: pushed value, aligned to the right (put in the lowest significant bytes)

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#7C](https://www.evm.codes/#7C)
    """

    PUSH30 = Opcode(0x7D, pushed_stack_items=1, data_portion_length=30)
    """
    PUSH30() = value
    ----

    Description
    ----
    Place 30 byte item on stack

    Inputs
    ----
    - None

    Outputs
    ----
    - value: pushed value, aligned to the right (put in the lowest significant bytes)

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#7D](https://www.evm.codes/#7D)
    """

    PUSH31 = Opcode(0x7E, pushed_stack_items=1, data_portion_length=31)
    """
    PUSH31() = value
    ----

    Description
    ----
    Place 31 byte item on stack

    Inputs
    ----
    - None

    Outputs
    ----
    - value: pushed value, aligned to the right (put in the lowest significant bytes)

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#7E](https://www.evm.codes/#7E)
    """

    PUSH32 = Opcode(0x7F, pushed_stack_items=1, data_portion_length=32)
    """
    PUSH32() = value
    ----

    Description
    ----
    Place 32 byte item on stack

    Inputs
    ----
    - None

    Outputs
    ----
    - value: pushed value, aligned to the right (put in the lowest significant bytes)

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#7F](https://www.evm.codes/#7F)
    """

    DUP1 = Opcode(0x80, pushed_stack_items=1, min_stack_height=1)
    """
    DUP1(value) = value, value
    ----

    Description
    ----
    Duplicate 1st stack item

    Inputs
    ----
    - value: value to duplicate

    Outputs
    ----
    - value: duplicated value
    - value: original value

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#80](https://www.evm.codes/#80)
    """

    DUP2 = Opcode(0x81, pushed_stack_items=1, min_stack_height=2)
    """
    DUP2(v1, v2) = v2, v1, v2
    ----

    Description
    ----
    Duplicate 2nd stack item

    Inputs
    ----
    - v1: ignored value
    - v2: value to duplicate

    Outputs
    ----
    - v2: duplicated value
    - v1: ignored value
    - v2: original value

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#81](https://www.evm.codes/#81)
    """

    DUP3 = Opcode(0x82, pushed_stack_items=1, min_stack_height=3)
    """
    DUP3(v1, v2, v3) = v3, v1, v2, v3
    ----

    Description
    ----
    Duplicate 3rd stack item

    Inputs
    ----
    - v1: ignored value
    - v2: ignored value
    - v3: value to duplicate

    Outputs
    ----
    - v3: duplicated value
    - v1: ignored value
    - v2: ignored value
    - v3: original value

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#82](https://www.evm.codes/#82)
    """

    DUP4 = Opcode(0x83, pushed_stack_items=1, min_stack_height=4)
    """
    DUP4(v1, v2, v3, v4) = v4, v1, v2, v3, v4
    ----

    Description
    ----
    Duplicate 4th stack item

    Inputs
    ----
    - v1: ignored value
    - v2: ignored value
    - v3: ignored value
    - v4: value to duplicate

    Outputs
    ----
    - v4: duplicated value
    - v1: ignored value
    - v2: ignored value
    - v3: ignored value
    - v4: original value

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#83](https://www.evm.codes/#83)
    """

    DUP5 = Opcode(0x84, pushed_stack_items=1, min_stack_height=5)
    """
    DUP5(v1, v2, v3, v4, v5) = v5, v1, v2, v3, v4, v5
    ----

    Description
    ----
    Duplicate 5th stack item

    Inputs
    ----
    - v1: ignored value
    - v2: ignored value
    - v3: ignored value
    - v4: ignored value
    - v5: value to duplicate

    Outputs
    ----
    - v5: duplicated value
    - v1: ignored value
    - v2: ignored value
    - v3: ignored value
    - v4: ignored value
    - v5: original value

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#84](https://www.evm.codes/#84)
    """

    DUP6 = Opcode(0x85, pushed_stack_items=1, min_stack_height=6)
    """
    DUP6(v1, v2, ..., v5, v6) = v6, v1, v2, ..., v5, v6
    ----

    Description
    ----
    Duplicate 6th stack item

    Inputs
    ----
    - v1: ignored value
    - v2: ignored value
    - ...
    - v5: ignored value
    - v6: value to duplicate

    Outputs
    ----
    - v6: duplicated value
    - v1: ignored value
    - v2: ignored value
    - ...
    - v5: ignored value
    - v6: original value

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#85](https://www.evm.codes/#85)
    """

    DUP7 = Opcode(0x86, pushed_stack_items=1, min_stack_height=7)
    """
    DUP7(v1, v2, ..., v6, v7) = v7, v1, v2, ..., v6, v7
    ----

    Description
    ----
    Duplicate 7th stack item

    Inputs
    ----
    - v1: ignored value
    - v2: ignored value
    - ...
    - v6: ignored value
    - v7: value to duplicate

    Outputs
    ----
    - v7: duplicated value
    - v1: ignored value
    - v2: ignored value
    - ...
    - v6: ignored value
    - v7: original value

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#86](https://www.evm.codes/#86)
    """

    DUP8 = Opcode(0x87, pushed_stack_items=1, min_stack_height=8)
    """
    DUP8(v1, v2, ..., v7, v8) = v8, v1, v2, ..., v7, v8
    ----

    Description
    ----
    Duplicate 8th stack item

    Inputs
    ----
    - v1: ignored value
    - v2: ignored value
    - ...
    - v7: ignored value
    - v8: value to duplicate

    Outputs
    ----
    - v8: duplicated value
    - v1: ignored value
    - v2: ignored value
    - ...
    - v7: ignored value
    - v8: original value

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#87](https://www.evm.codes/#87)
    """

    DUP9 = Opcode(0x88, pushed_stack_items=1, min_stack_height=9)
    """
    DUP9(v1, v2, ..., v8, v9) = v9, v1, v2, ..., v8, v9
    ----

    Description
    ----
    Duplicate 9th stack item

    Inputs
    ----
    - v1: ignored value
    - v2: ignored value
    - ...
    - v8: ignored value
    - v9: value to duplicate

    Outputs
    ----
    - v9: duplicated value
    - v1: ignored value
    - v2: ignored value
    - ...
    - v8: ignored value
    - v9: original value

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#88](https://www.evm.codes/#88)
    """
    DUP10 = Opcode(0x89, pushed_stack_items=1, min_stack_height=10)
    """
    DUP10(v1, v2, ..., v9, v10) = v10, v1, v2, ..., v9, v10
    ----

    Description
    ----
    Duplicate 10th stack item

    Inputs
    ----
    - v1: ignored value
    - v2: ignored value
    - ...
    - v9: ignored value
    - v10: value to duplicate

    Outputs
    ----
    - v10: duplicated value
    - v1: ignored value
    - v2: ignored value
    - ...
    - v9: ignored value
    - v10: original value

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#89](https://www.evm.codes/#89)
    """

    DUP11 = Opcode(0x8A, pushed_stack_items=1, min_stack_height=11)
    """
    DUP11(v1, v2, ..., v10, v11) = v11, v1, v2, ..., v10, v11
    ----

    Description
    ----
    Duplicate 11th stack item

    Inputs
    ----
    - v1: ignored value
    - v2: ignored value
    - ...
    - v10: ignored value
    - v11: value to duplicate

    Outputs
    ----
    - v11: duplicated value
    - v1: ignored value
    - v2: ignored value
    - ...
    - v10: ignored value
    - v11: original value

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#8A](https://www.evm.codes/#8A)
    """

    DUP12 = Opcode(0x8B, pushed_stack_items=1, min_stack_height=12)
    """
    DUP12(v1, v2, ..., v11, v12) = v12, v1, v2, ..., v11, v12
    ----

    Description
    ----
    Duplicate 12th stack item

    Inputs
    ----
    - v1: ignored value
    - v2: ignored value
    - ...
    - v11: ignored value
    - v12: value to duplicate

    Outputs
    ----
    - v12: duplicated value
    - v1: ignored value
    - v2: ignored value
    - ...
    - v11: ignored value
    - v12: original value

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#8B](https://www.evm.codes/#8B)
    """

    DUP13 = Opcode(0x8C, pushed_stack_items=1, min_stack_height=13)
    """
    DUP13(v1, v2, ..., v12, v13) = v13, v1, v2, ..., v12, v13
    ----

    Description
    ----
    Duplicate 13th stack item

    Inputs
    ----
    - v1: ignored value
    - v2: ignored value
    - ...
    - v12: ignored value
    - v13: value to duplicate

    Outputs
    ----
    - v13: duplicated value
    - v1: ignored value
    - v2: ignored value
    - ...
    - v12: ignored value
    - v13: original value

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#8C](https://www.evm.codes/#8C)
    """

    DUP14 = Opcode(0x8D, pushed_stack_items=1, min_stack_height=14)
    """
    DUP14(v1, v2, ..., v13, v14) = v14, v1, v2, ..., v13, v14
    ----

    Description
    ----
    Duplicate 14th stack item

    Inputs
    ----
    - v1: ignored value
    - v2: ignored value
    - ...
    - v13: ignored value
    - v14: value to duplicate

    Outputs
    ----
    - v14: duplicated value
    - v1: ignored value
    - v2: ignored value
    - ...
    - v13: ignored value
    - v14: original value

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#8D](https://www.evm.codes/#8D)
    """

    DUP15 = Opcode(0x8E, pushed_stack_items=1, min_stack_height=15)
    """
    DUP15(v1, v2, ..., v14, v15) = v15, v1, v2, ..., v14, v15
    ----

    Description
    ----
    Duplicate 15th stack item

    Inputs
    ----
    - v1: ignored value
    - v2: ignored value
    - ...
    - v14: ignored value
    - v15: value to duplicate

    Outputs
    ----
    - v15: duplicated value
    - v1: ignored value
    - v2: ignored value
    - ...
    - v14: ignored value
    - v15: original value

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#8E](https://www.evm.codes/#8E)
    """

    DUP16 = Opcode(0x8F, pushed_stack_items=1, min_stack_height=16)
    """
    DUP16(v1, v2, ..., v15, v16) = v16, v1, v2, ..., v15, v16
    ----

    Description
    ----
    Duplicate 16th stack item

    Inputs
    ----
    - v1: ignored value
    - v2: ignored value
    - ...
    - v15: ignored value
    - v16: value to duplicate

    Outputs
    ----
    - v16: duplicated value
    - v1: ignored value
    - v2: ignored value
    - ...
    - v15: ignored value
    - v16: original value

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#8F](https://www.evm.codes/#8F)
    """

    SWAP1 = Opcode(0x90, min_stack_height=2)
    """
    SWAP1(v1, v2) = v2, v1
    ----

    Description
    ----
    Exchange the top stack item with the second stack item.

    Inputs
    ----
    - v1: value to swap
    - v2: value to swap

    Outputs
    ----
    - v1: swapped value
    - v2: swapped value

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#90](https://www.evm.codes/#90)
    """

    SWAP2 = Opcode(0x91, min_stack_height=3)
    """
    SWAP2(v1, v2, v3) = v3, v2, v1
    ----

    Description
    ----
    Exchange 1st and 3rd stack items

    Inputs
    ----
    - v1: value to swap
    - v2: ignored value
    - v3: value to swap

    Outputs
    ----
    - v3: swapped value
    - v2: ignored value
    - v1: swapped value

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#91](https://www.evm.codes/#91)
    """

    SWAP3 = Opcode(0x92, min_stack_height=4)
    """
    SWAP3(v1, v2, v3, v4) = v4, v2, v3, v1
    ----

    Description
    ----
    Exchange 1st and 4th stack items

    Inputs
    ----
    - v1: value to swap
    - v2: ignored value
    - v3: ignored value
    - v4: value to swap

    Outputs
    ----
    - v4: swapped value
    - v2: ignored value
    - v3: ignored value
    - v1: swapped value

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#92](https://www.evm.codes/#92)
    """

    SWAP4 = Opcode(0x93, min_stack_height=5)
    """
    SWAP4(v1, v2, ..., v4, v5) = v5, v2, ..., v4, v1
    ----

    Description
    ----
    Exchange 1st and 5th stack items

    Inputs
    ----
    - v1: value to swap
    - v2: ignored value
    - ...
    - v4: ignored value
    - v5: value to swap

    Outputs
    ----
    - v5: swapped value
    - v2: ignored value
    - ...
    - v4: ignored value
    - v1: swapped value

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#93](https://www.evm.codes/#93)
    """

    SWAP5 = Opcode(0x94, min_stack_height=6)
    """
    SWAP5(v1, v2, ..., v5, v6) = v6, v2, ..., v5, v1
    ----

    Description
    ----
    Exchange 1st and 6th stack items

    Inputs
    ----
    - v1: value to swap
    - v2: ignored value
    - ...
    - v5: ignored value
    - v6: value to swap

    Outputs
    ----
    - v6: swapped value
    - v2: ignored value
    - ...
    - v5: ignored value
    - v1: swapped value

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#94](https://www.evm.codes/#94)
    """

    SWAP6 = Opcode(0x95, min_stack_height=7)
    """
    SWAP6(v1, v2, ..., v6, v7) = v7, v2, ..., v6, v1
    ----

    Description
    ----
    Exchange 1st and 7th stack items

    Inputs
    ----
    - v1: value to swap
    - v2: ignored value
    - ...
    - v6: ignored value
    - v7: value to swap

    Outputs
    ----
    - v7: swapped value
    - v2: ignored value
    - ...
    - v6: ignored value
    - v1: swapped value

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#95](https://www.evm.codes/#95)
    """

    SWAP7 = Opcode(0x96, min_stack_height=8)
    """
    SWAP7(v1, v2, ..., v7, v8) = v8, v2, ..., v7, v1
    ----

    Description
    ----
    Exchange 1st and 8th stack items

    Inputs
    ----
    - v1: value to swap
    - v2: ignored value
    - ...
    - v7: ignored value
    - v8: value to swap

    Outputs
    ----
    - v8: swapped value
    - v2: ignored value
    - ...
    - v7: ignored value
    - v1: swapped value

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#96](https://www.evm.codes/#96)
    """

    SWAP8 = Opcode(0x97, min_stack_height=9)
    """
    SWAP8(v1, v2, ..., v8, v9) = v9, v2, ..., v8, v1
    ----

    Description
    ----
    Exchange 1st and 9th stack items

    Inputs
    ----
    - v1: value to swap
    - v2: ignored value
    - ...
    - v8: ignored value
    - v9: value to swap

    Outputs
    ----
    - v9: swapped value
    - v2: ignored value
    - ...
    - v8: ignored value
    - v1: swapped value

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#97](https://www.evm.codes/#97)
    """

    SWAP9 = Opcode(0x98, min_stack_height=10)
    """
    SWAP9(v1, v2, ..., v9, v10) = v10, v2, ..., v9, v1
    ----

    Description
    ----
    Exchange 1st and 10th stack items

    Inputs
    ----
    - v1: value to swap
    - v2: ignored value
    - ...
    - v9: ignored value
    - v10: value to swap

    Outputs
    ----
    - v10: swapped value
    - v2: ignored value
    - ...
    - v9: ignored value
    - v1: swapped value

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#98](https://www.evm.codes/#98)
    """

    SWAP10 = Opcode(0x99, min_stack_height=11)
    """
    SWAP10(v1, v2, ..., v10, v11) = v11, v2, ..., v10, v1
    ----

    Description
    ----
    Exchange 1st and 11th stack items

    Inputs
    ----
    - v1: value to swap
    - v2: ignored value
    - ...
    - v10: ignored value
    - v11: value to swap

    Outputs
    ----
    - v11: swapped value
    - v2: ignored value
    - ...
    - v10: ignored value
    - v1: swapped value

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#99](https://www.evm.codes/#99)
    """

    SWAP11 = Opcode(0x9A, min_stack_height=12)
    """
    SWAP11(v1, v2, ..., v11, v12) = v12, v2, ..., v11, v1
    ----

    Description
    ----
    Exchange 1st and 12th stack items

    Inputs
    ----
    - v1: value to swap
    - v2: ignored value
    - ...
    - v11: ignored value
    - v12: value to swap

    Outputs
    ----
    - v12: swapped value
    - v2: ignored value
    - ...
    - v11: ignored value
    - v1: swapped value

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#9A](https://www.evm.codes/#9A)
    """

    SWAP12 = Opcode(0x9B, min_stack_height=13)
    """
    SWAP12(v1, v2, ..., v12, v13) = v13, v2, ..., v12, v1
    ----

    Description
    ----
    Exchange 1st and 13th stack items

    Inputs
    ----
    - v1: value to swap
    - v2: ignored value
    - ...
    - v12: ignored value
    - v13: value to swap

    Outputs
    ----
    - v13: swapped value
    - v2: ignored value
    - ...
    - v12: ignored value
    - v1: swapped value

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#9B](https://www.evm.codes/#9B)
    """

    SWAP13 = Opcode(0x9C, min_stack_height=14)
    """
    SWAP13(v1, v2, ..., v13, v14) = v14, v2, ..., v13, v1
    ----

    Description
    ----
    Exchange 1st and 14th stack items

    Inputs
    ----
    - v1: value to swap
    - v2: ignored value
    - ...
    - v13: ignored value
    - v14: value to swap

    Outputs
    ----
    - v14: swapped value
    - v2: ignored value
    - ...
    - v13: ignored value
    - v1: swapped value

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#9C](https://www.evm.codes/#9C)
    """

    SWAP14 = Opcode(0x9D, min_stack_height=15)
    """
    SWAP14(v1, v2, ..., v14, v15) = v15, v2, ..., v14, v1
    ----

    Description
    ----
    Exchange 1st and 15th stack items

    Inputs
    ----
    - v1: value to swap
    - v2: ignored value
    - ...
    - v14: ignored value
    - v15: value to swap

    Outputs
    ----
    - v15: swapped value
    - v2: ignored value
    - ...
    - v14: ignored value
    - v1: swapped value

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#9D](https://www.evm.codes/#9D)
    """

    SWAP15 = Opcode(0x9E, min_stack_height=16)
    """
    SWAP15(v1, v2, ..., v15, v16) = v16, v2, ..., v15, v1
    ----

    Description
    ----
    Exchange 1st and 16th stack items

    Inputs
    ----
    - v1: value to swap
    - v2: ignored value
    - ...
    - v15: ignored value
    - v16: value to swap

    Outputs
    ----
    - v16: swapped value
    - v2: ignored value
    - ...
    - v15: ignored value
    - v1: swapped value

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#9E](https://www.evm.codes/#9E)
    """

    SWAP16 = Opcode(0x9F, min_stack_height=17)
    """
    SWAP16(v1, v2, ..., v16, v17) = v17, v2, ..., v16, v1
    ----

    Description
    ----
    Exchange 1st and 17th stack items

    Inputs
    ----
    - v1: value to swap
    - v2: ignored value
    - ...
    - v16: ignored value
    - v17: value to swap

    Outputs
    ----
    - v17: swapped value
    - v2: ignored value
    - ...
    - v16: ignored value
    - v1: swapped value

    Fork
    ----
    Frontier

    Gas
    ----
    3

    Source: [evm.codes/#9F](https://www.evm.codes/#9F)
    """

    LOG0 = Opcode(0xA0, popped_stack_items=2)
    """
    LOG0(offset, size)
    ----

    Description
    ----
    Append log record with no topics

    Inputs
    ----
    - offset: byte offset in the memory in bytes
    - size: byte size to copy

    Outputs
    ----
    - None

    Fork
    ----
    Frontier

    Gas
    ----
    - static_gas = 375
    - dynamic_gas = 375 * topic_count + 8 * size + memory_expansion_cost

    Source: [evm.codes/#A0](https://www.evm.codes/#A0)
    """

    LOG1 = Opcode(0xA1, popped_stack_items=3)
    """
    LOG1(offset, size, topic1)
    ----

    Description
    ----
    Append log record with one topic

    Inputs
    ----
    - offset: byte offset in the memory in bytes
    - size: byte size to copy
    - topic1: 32-byte value

    Outputs
    ----
    - None

    Fork
    ----
    Frontier

    Gas
    ----
    - static_gas = 375
    - dynamic_gas = 375 * topic_count + 8 * size + memory_expansion_cost

    Source: [evm.codes/#A1](https://www.evm.codes/#A1)
    """

    LOG2 = Opcode(0xA2, popped_stack_items=4)
    """
    LOG2(offset, size, topic1, topic2)
    ----

    Description
    ----
    Append log record with two topics

    Inputs
    ----
    - offset: byte offset in the memory in bytes
    - size: byte size to copy
    - topic1: 32-byte value
    - topic2: 32-byte value

    Outputs
    ----
    - None

    Fork
    ----
    Frontier

    Gas
    ----
    - static_gas = 375
    - dynamic_gas = 375 * topic_count + 8 * size + memory_expansion_cost

    Source: [evm.codes/#A2](https://www.evm.codes/#A2)
    """

    LOG3 = Opcode(0xA3, popped_stack_items=5)
    """
    LOG3(offset, size, topic1, topic2, topic3)
    ----

    Description
    ----
    Append log record with three topics

    Inputs
    ----
    - offset: byte offset in the memory in bytes
    - size: byte size to copy
    - topic1: 32-byte value
    - topic2: 32-byte value
    - topic3: 32-byte value

    Outputs
    ----
    - None

    Fork
    ----
    Frontier

    Gas
    ----
    - static_gas = 375
    - dynamic_gas = 375 * topic_count + 8 * size + memory_expansion_cost

    Source: [evm.codes/#A3](https://www.evm.codes/#A3)
    """

    LOG4 = Opcode(0xA4, popped_stack_items=6)
    """
    LOG4(offset, size, topic1, topic2, topic3, topic4)
    ----

    Description
    ----
    Append log record with four topics

    Inputs
    ----
    - offset: byte offset in the memory in bytes
    - size: byte size to copy
    - topic1: 32-byte value
    - topic2: 32-byte value
    - topic3: 32-byte value
    - topic4: 32-byte value

    Outputs
    ----
    - None

    Fork
    ----
    Frontier

    Gas
    ----
    - static_gas = 375
    - dynamic_gas = 375 * topic_count + 8 * size + memory_expansion_cost

    Source: [evm.codes/#A4](https://www.evm.codes/#A4)
    """

    RJUMP = Opcode(0xE0, data_portion_length=2)
    """
    !!! Note: This opcode is under development

    RJUMP()
    ----

    Description
    ----

    Inputs
    ----

    Outputs
    ----

    Fork
    ----
    EOF Fork

    Gas
    ----

    Source: [eips.ethereum.org/EIPS/eip-4200](https://eips.ethereum.org/EIPS/eip-4200)
    """

    RJUMPI = Opcode(0xE1, popped_stack_items=1, data_portion_length=2)
    """
    !!! Note: This opcode is under development

    RJUMPI()
    ----

    Description
    ----

    Inputs
    ----

    Outputs
    ----

    Fork
    ----
    EOF Fork

    Gas
    ----

    Source: [eips.ethereum.org/EIPS/eip-4200](https://eips.ethereum.org/EIPS/eip-4200)
    """

    RJUMPV = Opcode(0xE2)
    """
    !!! Note: This opcode is under development

    RJUMPV()
    ----

    Description
    ----

    Inputs
    ----

    Outputs
    ----

    Fork
    ----
    EOF Fork

    Gas
    ----

    Source: [eips.ethereum.org/EIPS/eip-4200](https://eips.ethereum.org/EIPS/eip-4200)
    """

    RETF = Opcode(0xE4)
    """
    !!! Note: This opcode is under development

    RETF()
    ----

    Description
    ----

    Inputs
    ----

    Outputs
    ----

    Fork
    ----
    EOF Fork

    Gas
    ----
    3

    Source: [eips.ethereum.org/EIPS/eip-4750](https://eips.ethereum.org/EIPS/eip-4750)
    """

    CREATE = Opcode(0xF0, popped_stack_items=3, pushed_stack_items=1)
    """
    CREATE(value, offset, length) = address
    ----

    Description
    ----
    Create a new contract with the given code

    Inputs
    ----
    - value: value in wei to send to the new account
    - offset: byte offset in the memory in bytes, the initialisation code for the new account
    - size: byte size to copy (size of the initialisation code)

    Outputs
    ----
    - address: the address of the deployed contract, 0 if the deployment failed

    Fork
    ----
    Frontier

    Gas
    ----
    ```
    minimum_word_size = (size + 31) / 32
    init_code_cost = 2 * minimum_word_size
    code_deposit_cost = 200 * deployed_code_size

    static_gas = 32000
    dynamic_gas = init_code_cost + memory_expansion_cost + deployment_code_execution_cost
        + code_deposit_cost
    ```

    Source: [evm.codes/#F0](https://www.evm.codes/#F0)
    """

    CALL = Opcode(0xF1, popped_stack_items=7, pushed_stack_items=1)
    """
    CALL(gas, address, value, argsOffset, argsSize, retOffset, retSize) = success
    ----

    Description
    ----
    Message-call into an account

    Inputs
    ----
    - gas: amount of gas to send to the sub context to execute. The gas that is not used by the sub
        context is returned to this one
    - address: the account which context to execute
    - value: value in wei to send to the account
    - argsOffset: byte offset in the memory in bytes, the calldata of the sub context
    - argsSize: byte size to copy (size of the calldata)
    - retOffset: byte offset in the memory in bytes, where to store the return data of the sub
        context
    - retSize: byte size to copy (size of the return data)

    Outputs
    ----
    - success: return 0 if the sub context reverted, 1 otherwise

    Fork
    ----
    Frontier

    Gas
    ----
    ```
    static_gas = 0
    dynamic_gas = memory_expansion_cost + code_execution_cost + address_access_cost
        + positive_value_cost + value_to_empty_account_cost
    ```

    Source: [evm.codes/#F1](https://www.evm.codes/#F1)
    """

    CALLCODE = Opcode(0xF2, popped_stack_items=7, pushed_stack_items=1)
    """
    CALLCODE(gas, address, value, argsOffset, argsSize, retOffset, retSize) = success
    ----

    Description
    ----
    Message-call into this account with an alternative account's code. Executes code starting at
    the address to which the call is made.

    Inputs
    ----
    - gas: amount of gas to send to the sub context to execute. The gas that is not used by the sub
        context is returned to this one
    - address: the account which code to execute
    - value: value in wei to send to the account
    - argsOffset: byte offset in the memory in bytes, the calldata of the sub context
    - argsSize: byte size to copy (size of the calldata)
    - retOffset: byte offset in the memory in bytes, where to store the return data of the sub
        context
    - retSize: byte size to copy (size of the return data)

    Outputs
    ----
    - success: return 0 if the sub context reverted, 1 otherwise

    Fork
    ----
    Frontier

    Gas
    ----
    ```
    static_gas = 0
    dynamic_gas = memory_expansion_cost + code_execution_cost + address_access_cost
        + positive_value_cost
    ```

    Source: [evm.codes/#F2](https://www.evm.codes/#F2)
    """

    RETURN = Opcode(0xF3, popped_stack_items=2)
    """
    RETURN(offset, size)
    ----

    Description
    ----
    Halt execution returning output data

    Inputs
    ----
    - offset: byte offset in the memory in bytes, to copy what will be the return data of this
        context
    - size: byte size to copy (size of the return data)

    Outputs
    ----
    - None

    Fork
    ----
    Frontier

    Gas
    ----
    - static_gas = 0
    - dynamic_gas = memory_expansion_cost

    Source: [evm.codes/#F3](https://www.evm.codes/#F3)
    """

    DELEGATECALL = Opcode(0xF4, popped_stack_items=6, pushed_stack_items=1)
    """
    DELEGATECALL(gas, address, argsOffset, argsSize, retOffset, retSize) = success
    ----

    Description
    ----
    Message-call into this account with an alternative account's code, but persisting the current
    values for sender and value

    Inputs
    ----
    - gas: amount of gas to send to the sub context to execute. The gas that is not used by the sub
        context is returned to this one
    - address: the account which code to execute
    - argsOffset: byte offset in the memory in bytes, the calldata of the sub context
    - argsSize: byte size to copy (size of the calldata)
    - retOffset: byte offset in the memory in bytes, where to store the return data of the sub
        context
    - retSize: byte size to copy (size of the return data)

    Outputs
    ----
    - success: return 0 if the sub context reverted, 1 otherwise

    Fork
    ----
    Byzantium

    Gas
    ----
    - static_gas = 0
    - dynamic_gas = memory_expansion_cost + code_execution_cost + address_access_cost

    Source: [evm.codes/#F4](https://www.evm.codes/#F4)
    """

    CREATE2 = Opcode(0xF5, popped_stack_items=4, pushed_stack_items=1)
    """
    CREATE2(value, offset, size, salt) = address
    ----

    Description
    ----
    Creates a new contract

    Inputs
    ----
    - value: value in wei to send to the new account
    - offset: byte offset in the memory in bytes, the initialisation code of the new account
    - size: byte size to copy (size of the initialisation code)
    - salt: 32-byte value used to create the new account at a deterministic address

    Outputs
    ----
    - address: the address of the deployed contract, 0 if the deployment failed

    Fork
    ----
    Constantinople

    Gas
    ----
    ```
    minimum_word_size = (size + 31) / 32
    init_code_cost = 2 * minimum_word_size
    hash_cost = 6 * minimum_word_size
    code_deposit_cost = 200 * deployed_code_size

    static_gas = 32000
    dynamic_gas = init_code_cost + hash_cost + memory_expansion_cost
        + deployment_code_execution_cost + code_deposit_cost
    ```

    Source: [evm.codes/#F5](https://www.evm.codes/#F5)
    """

    STATICCALL = Opcode(0xFA, popped_stack_items=6, pushed_stack_items=1)
    """
    STATICCALL(gas, address, argsOffset, argsSize, retOffset, retSize) = success
    ----

    Description
    ----
    Static message-call into an account

    Inputs
    ----
    - gas: amount of gas to send to the sub context to execute. The gas that is not used by the sub
        context is returned to this one
    - address: the account which context to execute
    - argsOffset: byte offset in the memory in bytes, the calldata of the sub context
    - argsSize: byte size to copy (size of the calldata)
    - retOffset: byte offset in the memory in bytes, where to store the return data of the sub
        context
    - retSize: byte size to copy (size of the return data)

    Outputs
    ----
    - success: return 0 if the sub context reverted, 1 otherwise

    Fork
    ----
    Byzantium

    Gas
    ----
    - static_gas = 0
    - dynamic_gas = memory_expansion_cost + code_execution_cost + address_access_cost

    Source: [evm.codes/#FA](https://www.evm.codes/#FA)
    """

    REVERT = Opcode(0xFD, popped_stack_items=2)
    """
    REVERT(offset, size)
    ----

    Description
    ----
    Halt execution reverting state changes but returning data and remaining gas

    Inputs
    ----
    - offset: byte offset in the memory in bytes. The return data of the calling context
    - size: byte size to copy (size of the return data)

    Fork
    ----
    Byzantium

    Gas
    ----
    static_gas = 0
    dynamic_gas = memory_expansion_cost

    Source: [evm.codes/#FD](https://www.evm.codes/#FD)
    """

    INVALID = Opcode(0xFE)
    """
    INVALID()
    ----

    Description
    ----
    Designated invalid instruction

    Inputs
    ----
    None

    Outputs
    ----
    None

    Fork
    ----
    Frontier

    Gas
    ----
    All the remaining gas in this context is consumed

    Source: [evm.codes/#FE](https://www.evm.codes/#FE)
    """

    SELFDESTRUCT = Opcode(0xFF, popped_stack_items=1)
    """
    SELFDESTRUCT(address)
    ----

    Description
    ----
    Halt execution and register the account for later deletion

    Inputs
    ----
    - address: account to send the current balance to

    Fork
    ----
    Frontier

    Gas
    ----
    5000

    Source: [evm.codes/#FF](https://www.evm.codes/#FF)
    """

STOP = Opcode(0) class-attribute instance-attribute

STOP()
Description

Stop execution

Inputs
  • None
Outputs
  • None
Fork

Frontier

Gas

0

Source: evm.codes/#00

ADD = Opcode(1, popped_stack_items=2, pushed_stack_items=1) class-attribute instance-attribute

ADD(a, b) = c
Description

Addition operation

Inputs
  • a: first integer value to add
  • b: second integer value to add
Outputs
  • c: integer result of the addition modulo 2**256
Fork

Frontier

Gas

3

Source: evm.codes/#01

MUL = Opcode(2, popped_stack_items=2, pushed_stack_items=1) class-attribute instance-attribute

MUL(a, b) = c
Description

Multiplication operation

Inputs
  • a: first integer value to multiply
  • b: second integer value to multiply
Outputs
  • c: integer result of the multiplication modulo 2**256
Fork

Frontier

Gas

5

Source: evm.codes/#02

SUB = Opcode(3, popped_stack_items=2, pushed_stack_items=1) class-attribute instance-attribute

SUB(a, b) = c
Description

Subtraction operation

Inputs
  • a: first integer value
  • b: second integer value
Outputs
  • c: integer result of the subtraction modulo 2**256
Fork

Frontier

Gas

3

Source: evm.codes/#03

DIV = Opcode(4, popped_stack_items=2, pushed_stack_items=1) class-attribute instance-attribute

DIV(a, b) = c
Description

Division operation

Inputs
  • a: numerator
  • b: denominator (must be non-zero)
Outputs
  • c: integer result of the division
Fork

Frontier

Gas

5

Source: evm.codes/#04

SDIV = Opcode(5, popped_stack_items=2, pushed_stack_items=1) class-attribute instance-attribute

SDIV(a, b) = c
Description

Signed division operation

Inputs
  • a: signed numerator
  • b: signed denominator
Outputs
- c: signed integer result of the division. If the denominator is 0, the result will be 0
Fork

Frontier

Gas

5

Source: evm.codes/#05

MOD = Opcode(6, popped_stack_items=2, pushed_stack_items=1) class-attribute instance-attribute

MOD(a, b) = c
Description

Modulo operation

Inputs
  • a: integer numerator
  • b: integer denominator
Outputs
  • a % b: integer result of the integer modulo. If the denominator is 0, the result will be 0
Fork

Frontier

Gas

5

Source: evm.codes/#06

SMOD = Opcode(7, popped_stack_items=2, pushed_stack_items=1) class-attribute instance-attribute

SMOD(a, b) = c
Description

Signed modulo remainder operation

Inputs
  • a: integer numerator
  • b: integer denominator
Outputs
  • a % b: integer result of the signed integer modulo. If the denominator is 0, the result will be 0
Fork

Frontier

Gas

5

Source: evm.codes/#07

ADDMOD = Opcode(8, popped_stack_items=3, pushed_stack_items=1) class-attribute instance-attribute

ADDMOD(a, b, c) = d
Description

Modular addition operation with overflow check

Inputs
  • a: first integer value
  • b: second integer value
  • c: integer denominator
Outputs
  • (a + b) % N: integer result of the addition followed by a modulo. If the denominator is 0, the result will be 0
Fork

Frontier

Gas

8

Source: evm.codes/#08

MULMOD = Opcode(9, popped_stack_items=3, pushed_stack_items=1) class-attribute instance-attribute

MULMOD(a, b, N) = d
Description

Modulo multiplication operation

Inputs
  • a: first integer value to multiply
  • b: second integer value to multiply
  • N: integer denominator
Outputs
  • (a * b) % N: integer result of the multiplication followed by a modulo. If the denominator is 0, the result will be 0
Fork

Frontier

Gas

8

Source: evm.codes/#09

EXP = Opcode(10, popped_stack_items=2, pushed_stack_items=1) class-attribute instance-attribute

EXP(a, exponent) = a ** exponent
Description

Exponential operation

Inputs
  • a: integer base
  • exponent: integer exponent
Outputs
  • a ** exponent: integer result of the exponential operation modulo 2**256
Fork

Frontier

Gas
  • static_gas = 10
  • dynamic_gas = 50 * exponent_byte_size

Source: evm.codes/#0A

SIGNEXTEND = Opcode(11, popped_stack_items=2, pushed_stack_items=1) class-attribute instance-attribute

SIGNEXTEND(b, x) = y
Description

Sign extension operation

Inputs
  • b: size in byte - 1 of the integer to sign extend
  • x: integer value to sign extend
Outputs
  • y: integer result of the sign extend
Fork

Frontier

Gas

5

Source: evm.codes/#0B

LT = Opcode(16, popped_stack_items=2, pushed_stack_items=1) class-attribute instance-attribute

LT(a, b) = a < b
Description

Less-than comparison

Inputs
  • a: left side integer value
  • b: right side integer value
Outputs
  • a < b: 1 if the left side is smaller, 0 otherwise
Fork

Frontier

Gas

3

Source: evm.codes/#10

GT = Opcode(17, popped_stack_items=2, pushed_stack_items=1) class-attribute instance-attribute

GT(a, b) = a > b
Description

Greater-than comparison

Inputs
  • a: left side integer
  • b: right side integer
Outputs
  • a > b: 1 if the left side is bigger, 0 otherwise
Fork

Frontier

Gas

3

Source: evm.codes/#11

SLT = Opcode(18, popped_stack_items=2, pushed_stack_items=1) class-attribute instance-attribute

SLT(a, b) = a < b
Description

Signed less-than comparison

Inputs
  • a: left side signed integer
  • b: right side signed integer
Outputs
  • a < b: 1 if the left side is smaller, 0 otherwise
Fork

Frontier

Gas

3

Source: evm.codes/#12

SGT = Opcode(19, popped_stack_items=2, pushed_stack_items=1) class-attribute instance-attribute

SGT(a, b) = a > b
Description

Signed greater-than comparison

Inputs
  • a: left side signed integer
  • b: right side signed integer
Outputs
  • a > b: 1 if the left side is bigger, 0 otherwise
Fork

Frontier

Gas

3

Source: evm.codes/#13

EQ = Opcode(20, popped_stack_items=2, pushed_stack_items=1) class-attribute instance-attribute

EQ(a, b) = a == b
Description

Equality comparison

Inputs
  • a: left side integer
  • b: right side integer
Outputs
  • a == b: 1 if the left side is equal to the right side, 0 otherwise
Fork

Frontier

Gas

3

Source: evm.codes/#14

ISZERO = Opcode(21, popped_stack_items=1, pushed_stack_items=1) class-attribute instance-attribute

ISZERO(a) = a == 0
Description

Is-zero comparison

Inputs
  • a: integer
Outputs
  • a == 0: 1 if a is 0, 0 otherwise
Fork

Frontier

Gas

3

Source: evm.codes/#15

AND = Opcode(22, popped_stack_items=2, pushed_stack_items=1) class-attribute instance-attribute

AND(a, b) = a & b
Description

Bitwise AND operation

Inputs
  • a: first binary value
  • b: second binary value
Outputs
  • a & b: the bitwise AND result
Fork

Frontier

Gas

3

Source: evm.codes/#16

OR = Opcode(23, popped_stack_items=2, pushed_stack_items=1) class-attribute instance-attribute

OR(a, b) = a | b
Description

Bitwise OR operation

Inputs
  • a: first binary value
  • b: second binary value
Outputs
  • a | b: the bitwise OR result
Fork

Frontier

Gas

3

Source: evm.codes/#17

XOR = Opcode(24, popped_stack_items=2, pushed_stack_items=1) class-attribute instance-attribute

XOR(a, b) = a ^ b
Description

Bitwise XOR operation

Inputs
  • a: first binary value
  • b: second binary value
Outputs
  • a ^ b: the bitwise XOR result
Fork

Frontier

Gas

3

Source: evm.codes/#18

NOT = Opcode(25, popped_stack_items=1, pushed_stack_items=1) class-attribute instance-attribute

NOT(a) = ~a
Description

Bitwise NOT operation

Inputs
  • a: binary value
Outputs
  • ~a: the bitwise NOT result
Fork

Frontier

Gas

3

Source: evm.codes/#19

BYTE = Opcode(26, popped_stack_items=2, pushed_stack_items=1) class-attribute instance-attribute

BYTE(i, x) = y
Description

Extract a byte from the given position in the value

Inputs
  • i: byte offset starting from the most significant byte
  • x: 32-byte value
Outputs
  • y: the indicated byte at the least significant position. If the byte offset is out of range, the result is 0
Fork

Frontier

Gas

3

Source: evm.codes/#1A

SHL = Opcode(27, popped_stack_items=2, pushed_stack_items=1) class-attribute instance-attribute

SHL(shift, value) = value << shift
Description

Shift left operation

Inputs
  • shift: number of bits to shift to the left
  • value: 32 bytes to shift
Outputs
  • value << shift: the shifted value. If shift is bigger than 255, returns 0
Fork

Constantinople

Gas

3

Source: evm.codes/#1B

SHR = Opcode(28, popped_stack_items=2, pushed_stack_items=1) class-attribute instance-attribute

SHR(shift, value) = value >> shift
Description

Logical shift right operation

Inputs
  • shift: number of bits to shift to the right.
  • value: 32 bytes to shift
Outputs
  • value >> shift: the shifted value. If shift is bigger than 255, returns 0
Fork

Constantinople

Gas

3

Source: evm.codes/#1C

SAR = Opcode(29, popped_stack_items=2, pushed_stack_items=1) class-attribute instance-attribute

SAR(shift, value) = value >> shift
Description

Arithmetic shift right operation

Inputs
  • shift: number of bits to shift to the right
  • value: integer to shift
Outputs
  • value >> shift: the shifted value
Fork

Constantinople

Gas

3

Source: evm.codes/#1D

SHA3 = Opcode(32, popped_stack_items=2, pushed_stack_items=1) class-attribute instance-attribute

SHA3(start, length) = hash
Description

Compute Keccak-256 hash

Inputs
  • offset: byte offset in the memory
  • size: byte size to read in the memory
Outputs
  • hash: Keccak-256 hash of the given data in memory
Fork

Frontier

Gas
  • minimum_word_size = (size + 31) / 32
  • static_gas = 30
  • dynamic_gas = 6 * minimum_word_size + memory_expansion_cost

Source: evm.codes/#20

ADDRESS = Opcode(48, pushed_stack_items=1) class-attribute instance-attribute

ADDRESS() = address
Description

Get address of currently executing account

Inputs
  • None
Outputs
  • address: the 20-byte address of the current account
Fork

Frontier

Gas

2

Source: evm.codes/#30

BALANCE = Opcode(49, popped_stack_items=1, pushed_stack_items=1) class-attribute instance-attribute

BALANCE(address) = balance
Description

Get the balance of the specified account

Inputs
  • address: 20-byte address of the account to check
Outputs
  • balance: balance of the given account in wei. Returns 0 if the account doesn't exist
Fork

Frontier

Gas
  • static_gas = 0
  • dynamic_gas = 100 if warm_address, 2600 if cold_address

Source: evm.codes/#31

ORIGIN = Opcode(50, pushed_stack_items=1) class-attribute instance-attribute

ORIGIN() = address
Description

Get execution origination address

Inputs
  • None
Outputs
  • address: the 20-byte address of the sender of the transaction. It can only be an account without code
Fork

Frontier

Gas

2

Source: evm.codes/#32

CALLER = Opcode(51, pushed_stack_items=1) class-attribute instance-attribute

CALLER() = address
Description

Get caller address

Inputs
  • None
Outputs
  • address: the 20-byte address of the caller account. This is the account that did the last call (except delegate call)
Fork

Frontier

Gas

2

Source: evm.codes/#33

CALLVALUE = Opcode(52, pushed_stack_items=1) class-attribute instance-attribute

CALLVALUE() = value
Description

Get deposited value by the instruction/transaction responsible for this execution

Inputs
  • None
Outputs
  • value: the value of the current call in wei
Fork

Frontier

Gas

2

Source: evm.codes/#34

CALLDATALOAD = Opcode(53, popped_stack_items=1, pushed_stack_items=1) class-attribute instance-attribute

CALLDATALOAD(i) = data[i]
Description

Get input data of current environment

Inputs
  • i: byte offset in the calldata
Outputs
  • data[i]: 32-byte value starting from the given offset of the calldata. All bytes after the end of the calldata are set to 0
Fork

Frontier

Gas

3

Source: evm.codes/#35

CALLDATASIZE = Opcode(54, pushed_stack_items=1) class-attribute instance-attribute

CALLDATASIZE() = size
Description

Get size of input data in current environment

Inputs
  • None
Outputs
  • size: byte size of the calldata
Fork

Frontier

Gas

2

Source: evm.codes/#36

CALLDATACOPY = Opcode(55, popped_stack_items=3) class-attribute instance-attribute

CALLDATACOPY(destOffset, offset, size)
Description

Copy input data in current environment to memory

Inputs
  • destOffset: byte offset in the memory where the result will be copied
  • offset: byte offset in the calldata to copy
  • size: byte size to copy
Outputs
  • None
Fork

Frontier

Gas
  • minimum_word_size = (size + 31) / 32
  • static_gas = 3
  • dynamic_gas = 3 * minimum_word_size + memory_expansion_cost

Source: evm.codes/#37

CODESIZE = Opcode(56, pushed_stack_items=1) class-attribute instance-attribute

CODESIZE() = size
Description

Get size of code running in current environment

Inputs
  • None
Outputs
  • size: byte size of the code
Fork

Frontier

Gas

2

Source: evm.codes/#38

CODECOPY = Opcode(57, popped_stack_items=3) class-attribute instance-attribute

CODECOPY(destOffset, offset, size)
Description

Copy code running in current environment to memory

Inputs
  • destOffset: byte offset in the memory where the result will be copied.
  • offset: byte offset in the code to copy.
  • size: byte size to copy
Fork

Frontier

Gas
  • minimum_word_size = (size + 31) / 32
  • static_gas = 3
  • dynamic_gas = 3 * minimum_word_size + memory_expansion_cost

Source: evm.codes/#39

GASPRICE = Opcode(58, pushed_stack_items=1) class-attribute instance-attribute

GASPRICE() = price
Description

Get price of gas in current environment

Outputs
  • price: gas price in wei per gas
Fork

Frontier

Gas

2

Source: evm.codes/#3A

EXTCODESIZE = Opcode(59, popped_stack_items=1, pushed_stack_items=1) class-attribute instance-attribute

EXTCODESIZE(account) = size
Description

Get size of an account's code

Inputs
  • address: 20-byte address of the contract to query
Outputs
  • size: byte size of the code
Fork

Frontier

Gas
  • static_gas = 0
  • dynamic_gas = 100 if warm_address, 2600 if cold_address

Source: evm.codes/#3B

EXTCODECOPY = Opcode(60, popped_stack_items=4) class-attribute instance-attribute

EXTCODECOPY(addr, destOffset, offset, size)
Description

Copy an account's code to memory

Inputs
  • address: 20-byte address of the contract to query
  • destOffset: byte offset in the memory where the result will be copied
  • offset: byte offset in the code to copy
  • size: byte size to copy
Outputs
  • None
Fork

Frontier

Gas
  • minimum_word_size = (size + 31) / 32
  • static_gas = 0
  • dynamic_gas = 3 * minimum_word_size + memory_expansion_cost + address_access_cost

Source: evm.codes/#3C

RETURNDATASIZE = Opcode(61, pushed_stack_items=1) class-attribute instance-attribute

RETURNDATASIZE() = size
Description

Get size of output data from the previous call from the current environment

Outputs
  • size: byte size of the return data from the last executed sub context
Fork

Byzantium

Gas

2

Source: evm.codes/#3D

RETURNDATACOPY = Opcode(62, popped_stack_items=3) class-attribute instance-attribute

RETURNDATACOPY(destOffset, offset, size)
Description

Copy output data from the previous call to memory

Inputs
  • destOffset: byte offset in the memory where the result will be copied
  • offset: byte offset in the return data from the last executed sub context to copy
  • size: byte size to copy
Fork

Byzantium

Gas
  • minimum_word_size = (size + 31) / 32
  • static_gas = 3
  • dynamic_gas = 3 * minimum_word_size + memory_expansion_cost

Source: evm.codes/#3E

EXTCODEHASH = Opcode(63, popped_stack_items=1, pushed_stack_items=1) class-attribute instance-attribute

EXTCODEHASH(address) = hash
Description

Get hash of an account's code

Inputs
  • address: 20-byte address of the account
Outputs
  • hash: hash of the chosen account's code, the empty hash (0xc5d24601...) if the account has no code, or 0 if the account does not exist or has been destroyed
Fork

Constantinople

Gas
  • static_gas = 0
  • dynamic_gas = 100 if warm_address, 2600 if cold_address

Source: evm.codes/#3F

BLOCKHASH = Opcode(64, popped_stack_items=1, pushed_stack_items=1) class-attribute instance-attribute

BLOCKHASH(block_number) = hash
Description

Get the hash of one of the 256 most recent complete blocks

Inputs
  • blockNumber: block number to get the hash from. Valid range is the last 256 blocks (not including the current one). Current block number can be queried with NUMBER
Outputs
  • hash: hash of the chosen block, or 0 if the block number is not in the valid range
Fork

Frontier

Gas

20

Source: evm.codes/#40

COINBASE = Opcode(65, pushed_stack_items=1) class-attribute instance-attribute

COINBASE() = address
Description

Get the block's beneficiary address

Inputs
  • None
Outputs
  • address: miner's 20-byte address
Fork

Frontier

Gas

2

Source: evm.codes/#41

TIMESTAMP = Opcode(66, pushed_stack_items=1) class-attribute instance-attribute

TIMESTAMP() = timestamp
Description

Get the block's timestamp

Inputs
  • None
Outputs
  • timestamp: unix timestamp of the current block
Fork

Frontier

Gas

2

Source: evm.codes/#42

NUMBER = Opcode(67, pushed_stack_items=1) class-attribute instance-attribute

NUMBER() = blockNumber
Description

Get the block's number

Inputs
  • None
Outputs
  • blockNumber: current block number
Fork

Frontier

Gas

2

Source: evm.codes/#43

PREVRANDAO = Opcode(68, pushed_stack_items=1) class-attribute instance-attribute

PREVRANDAO() = prevRandao
Description

Get the previous block's RANDAO mix

Inputs
  • None
Outputs
  • prevRandao: previous block's RANDAO mix
Fork

Merge

Gas

2

Source: evm.codes/#44

GASLIMIT = Opcode(69, pushed_stack_items=1) class-attribute instance-attribute

GASLIMIT() = gasLimit
Description

Get the block's gas limit

Inputs
  • None
Outputs
  • gasLimit: gas limit
Fork

Frontier

Gas

2

Source: evm.codes/#45

CHAINID = Opcode(70, pushed_stack_items=1) class-attribute instance-attribute

CHAINID() = chainId
Description

Get the chain ID

Inputs
  • None
Outputs
  • chainId: chain id of the network
Fork

Istanbul

Gas

2

Source: evm.codes/#46

SELFBALANCE = Opcode(71, pushed_stack_items=1) class-attribute instance-attribute

SELFBALANCE() = balance
Description

Get balance of currently executing account

Inputs
  • None
Outputs
  • balance: balance of the current account in wei
Fork

Istanbul

Gas

5

Source: evm.codes/#47

BASEFEE = Opcode(72, pushed_stack_items=1) class-attribute instance-attribute

BASEFEE() = baseFee
Description

Get the base fee

Outputs
  • baseFee: base fee in wei
Fork

London

Gas

2

Source: evm.codes/#48

BLOBHASH = Opcode(73, popped_stack_items=1, pushed_stack_items=1) class-attribute instance-attribute

BLOBHASH(index) = versionedHash
Description

Returns the versioned hash of a single blob contained in the type-3 transaction

Inputs
  • index: index of the blob
Outputs
  • versionedHash: versioned hash of the blob
Fork

Cancun

Gas

3

Source: eips.ethereum.org/EIPS/eip-4844

BLOBBASEFEE = Opcode(74, popped_stack_items=0, pushed_stack_items=1) class-attribute instance-attribute

BLOBBASEFEE() = fee
Description

Returns the value of the blob base fee of the block it is executing in

Inputs
  • None
Outputs
  • baseFeePerBlobGas: base fee for the blob gas in wei
Fork

Cancun

Gas

2

Source: eips.ethereum.org/EIPS/eip-7516

POP = Opcode(80, popped_stack_items=1) class-attribute instance-attribute

POP()
Description

Remove item from stack

Inputs
  • None
Outputs
  • None
Fork

Frontier

Gas

2

Source: evm.codes/#50

MLOAD = Opcode(81, popped_stack_items=1, pushed_stack_items=1) class-attribute instance-attribute

MLOAD(offset) = value
Description

Load word from memory

Inputs
  • offset: offset in the memory in bytes
Outputs
  • value: the 32 bytes in memory starting at that offset. If it goes beyond its current size (see MSIZE), writes 0s
Fork

Frontier

Gas
  • static_gas = 3
  • dynamic_gas = memory_expansion_cost

Source: evm.codes/#51

MSTORE = Opcode(82, popped_stack_items=2) class-attribute instance-attribute

MSTORE(offset, value)
Description

Save word to memory

Inputs
  • offset: offset in the memory in bytes
  • value: 32-byte value to write in the memory
Outputs
  • None
Fork

Frontier

Gas
  • static_gas = 3
  • dynamic_gas = memory_expansion_cost

Source: evm.codes/#52

MSTORE8 = Opcode(83, popped_stack_items=2) class-attribute instance-attribute

MSTORE8(offset, value)
Description

Save byte to memory

Inputs
  • offset: offset in the memory in bytes
  • value: 1-byte value to write in the memory (the least significant byte of the 32-byte stack value)
Fork

Frontier

Gas
  • static_gas = 3
  • dynamic_gas = memory_expansion_cost

Source: evm.codes/#53

SLOAD = Opcode(84, popped_stack_items=1, pushed_stack_items=1) class-attribute instance-attribute

SLOAD(key) = value
Description

Load word from storage

Inputs
  • key: 32-byte key in storage
Outputs
  • value: 32-byte value corresponding to that key. 0 if that key was never written before
Fork

Frontier

Gas
  • static_gas = 0
  • dynamic_gas = 100 if warm_address, 2600 if cold_address

Source: evm.codes/#54

SSTORE = Opcode(85, popped_stack_items=2) class-attribute instance-attribute

SSTORE(key, value)
Description

Save word to storage

Inputs
  • key: 32-byte key in storage
  • value: 32-byte value to store
Outputs
  • None
Fork

Frontier

Gas
static_gas = 0

if value == current_value
    if key is warm
        base_dynamic_gas = 100
    else
        base_dynamic_gas = 100
else if current_value == original_value
    if original_value == 0
        base_dynamic_gas = 20000
    else
        base_dynamic_gas = 2900
else
    base_dynamic_gas = 100

if key is cold:
    base_dynamic_gas += 2100

Source: evm.codes/#55

JUMP = Opcode(86, popped_stack_items=1) class-attribute instance-attribute

JUMP(counter)
Description

Alter the program counter

Inputs
  • counter: byte offset in the deployed code where execution will continue from. Must be a JUMPDEST instruction
Outputs
  • None
Fork

Frontier

Gas

8

Source: evm.codes/#56

JUMPI = Opcode(87, popped_stack_items=2) class-attribute instance-attribute

JUMPI(counter, b)
Description

Conditionally alter the program counter

Inputs
  • counter: byte offset in the deployed code where execution will continue from. Must be a JUMPDEST instruction
  • b: the program counter will be altered with the new value only if this value is different from 0. Otherwise, the program counter is simply incremented and the next instruction will be executed
Fork

Frontier

Gas

10

Source: evm.codes/#57

PC = Opcode(88, pushed_stack_items=1) class-attribute instance-attribute

PC() = counter
Description

Get the value of the program counter prior to the increment corresponding to this instruction

Inputs
  • None
Outputs
  • counter: PC of this instruction in the current program.
Fork

Frontier

Gas

2

Source: evm.codes/#58

MSIZE = Opcode(89, pushed_stack_items=1) class-attribute instance-attribute

MSIZE() = size
Description

Get the size of active memory in bytes

Outputs
  • size: current memory size in bytes (higher offset accessed until now + 1)
Fork

Frontier

Gas

2

Source: evm.codes/#59

GAS = Opcode(90, pushed_stack_items=1) class-attribute instance-attribute

GAS() = gas_remaining
Description

Get the amount of available gas, including the corresponding reduction for the cost of this instruction

Inputs
  • None
Outputs
  • gas: remaining gas (after this instruction)
Fork

Frontier

Gas

2

Source: evm.codes/#5A

JUMPDEST = Opcode(91) class-attribute instance-attribute

JUMPDEST()
Description

Mark a valid destination for jumps

Inputs
  • None
Outputs
  • None
Fork

Frontier

Gas

1

Source: evm.codes/#5B

TLOAD = Opcode(92, popped_stack_items=1, pushed_stack_items=1) class-attribute instance-attribute

TLOAD(key) = value
Description

Load word from transient storage

Inputs
  • key: 32-byte key in transient storage
Outputs
  • value: 32-byte value corresponding to that key. 0 if that key was never written
Fork

Cancun

Gas

100

Source: eips.ethereum.org/EIPS/eip-1153

TSTORE = Opcode(93, popped_stack_items=2) class-attribute instance-attribute

TSTORE(key, value)
Description

Save word to transient storage

Inputs
  • key: 32-byte key in transient storage
  • value: 32-byte value to store
Fork

Cancun

Gas

100

Source: eips.ethereum.org/EIPS/eip-1153

MCOPY = Opcode(94, popped_stack_items=3) class-attribute instance-attribute

MCOPY(dst, src, length)
Description

Copies areas in memory

Inputs
  • dst: byte offset in the memory where the result will be copied
  • src: byte offset in the calldata to copy
  • length: byte size to copy
Outputs
  • None
Fork

Cancun

Gas
  • minimum_word_size = (length + 31) / 32
  • static_gas = 3
  • dynamic_gas = 3 * minimum_word_size + memory_expansion_cost

Source: eips.ethereum.org/EIPS/eip-5656

PUSH0 = Opcode(95, pushed_stack_items=1) class-attribute instance-attribute

PUSH0() = value
Description

Place value 0 on stack

Inputs
  • None
Outputs
  • value: pushed value, equal to 0
Fork

Shanghai

Gas

2

Source: evm.codes/#5F

PUSH1 = Opcode(96, pushed_stack_items=1, data_portion_length=1) class-attribute instance-attribute

PUSH1() = value
Description

Place 1 byte item on stack

Inputs
  • None
Outputs
  • value: pushed value, aligned to the right (put in the lowest significant bytes)
Fork

Frontier

Gas

3

Source: evm.codes/#60

PUSH2 = Opcode(97, pushed_stack_items=1, data_portion_length=2) class-attribute instance-attribute

PUSH2() = value
Description

Place 2 byte item on stack

Inputs
  • None
Outputs
  • value: pushed value, aligned to the right (put in the lowest significant bytes)
Fork

Frontier

Gas

3

Source: evm.codes/#61

PUSH3 = Opcode(98, pushed_stack_items=1, data_portion_length=3) class-attribute instance-attribute

PUSH3() = value
Description

Place 3 byte item on stack

Inputs
  • None
Outputs
  • value: pushed value, aligned to the right (put in the lowest significant bytes)
Fork

Frontier

Gas

3

Source: evm.codes/#62

PUSH4 = Opcode(99, pushed_stack_items=1, data_portion_length=4) class-attribute instance-attribute

PUSH4() = value
Description

Place 4 byte item on stack

Inputs
  • None
Outputs
  • value: pushed value, aligned to the right (put in the lowest significant bytes)
Fork

Frontier

Gas

3

Source: evm.codes/#63

PUSH5 = Opcode(100, pushed_stack_items=1, data_portion_length=5) class-attribute instance-attribute

PUSH5() = value
Description

Place 5 byte item on stack

Inputs
  • None
Outputs
  • value: pushed value, aligned to the right (put in the lowest significant bytes)
Fork

Frontier

Gas

3

Source: evm.codes/#64

PUSH6 = Opcode(101, pushed_stack_items=1, data_portion_length=6) class-attribute instance-attribute

PUSH6() = value
Description

Place 6 byte item on stack

Inputs
  • None
Outputs
  • value: pushed value, aligned to the right (put in the lowest significant bytes)
Fork

Frontier

Gas

3

Source: evm.codes/#65

PUSH7 = Opcode(102, pushed_stack_items=1, data_portion_length=7) class-attribute instance-attribute

PUSH7() = value
Description

Place 7 byte item on stack

Inputs
  • None
Outputs
  • value: pushed value, aligned to the right (put in the lowest significant bytes)
Fork

Frontier

Gas

3

Source: evm.codes/#66

PUSH8 = Opcode(103, pushed_stack_items=1, data_portion_length=8) class-attribute instance-attribute

PUSH8() = value
Description

Place 8 byte item on stack

Inputs
  • None
Outputs
  • value: pushed value, aligned to the right (put in the lowest significant bytes)
Fork

Frontier

Gas

3

Source: evm.codes/#67

PUSH9 = Opcode(104, pushed_stack_items=1, data_portion_length=9) class-attribute instance-attribute

PUSH9() = value
Description

Place 9 byte item on stack

Inputs
  • None
Outputs
  • value: pushed value, aligned to the right (put in the lowest significant bytes)
Fork

Frontier

Gas

3

Source: evm.codes/#68

PUSH10 = Opcode(105, pushed_stack_items=1, data_portion_length=10) class-attribute instance-attribute

PUSH10() = value
Description

Place 10 byte item on stack

Inputs
  • None
Outputs
  • value: pushed value, aligned to the right (put in the lowest significant bytes)
Fork

Frontier

Gas

3

Source: evm.codes/#69

PUSH11 = Opcode(106, pushed_stack_items=1, data_portion_length=11) class-attribute instance-attribute

PUSH11() = value
Description

Place 11 byte item on stack

Inputs
  • None
Outputs
  • value: pushed value, aligned to the right (put in the lowest significant bytes)
Fork

Frontier

Gas

3

Source: evm.codes/#6A

PUSH12 = Opcode(107, pushed_stack_items=1, data_portion_length=12) class-attribute instance-attribute

PUSH12() = value
Description

Place 12 byte item on stack

Inputs
  • None
Outputs
  • value: pushed value, aligned to the right (put in the lowest significant bytes)
Fork

Frontier

Gas

3

Source: evm.codes/#6B

PUSH13 = Opcode(108, pushed_stack_items=1, data_portion_length=13) class-attribute instance-attribute

PUSH13() = value
Description

Place 13 byte item on stack

Inputs
  • None
Outputs
  • value: pushed value, aligned to the right (put in the lowest significant bytes)
Fork

Frontier

Gas

3

Source: evm.codes/#6C

PUSH14 = Opcode(109, pushed_stack_items=1, data_portion_length=14) class-attribute instance-attribute

PUSH14() = value
Description

Place 14 byte item on stack

Inputs
  • None
Outputs
  • value: pushed value, aligned to the right (put in the lowest significant bytes)
Fork

Frontier

Gas

3

Source: evm.codes/#6D

PUSH15 = Opcode(110, pushed_stack_items=1, data_portion_length=15) class-attribute instance-attribute

PUSH15() = value
Description

Place 15 byte item on stack

Inputs
  • None
Outputs
  • value: pushed value, aligned to the right (put in the lowest significant bytes)
Fork

Frontier

Gas

3

Source: evm.codes/#6E

PUSH16 = Opcode(111, pushed_stack_items=1, data_portion_length=16) class-attribute instance-attribute

PUSH16() = value
Description

Place 16 byte item on stack

Inputs
  • None
Outputs
  • value: pushed value, aligned to the right (put in the lowest significant bytes)
Fork

Frontier

Gas

3

Source: evm.codes/#6F

PUSH17 = Opcode(112, pushed_stack_items=1, data_portion_length=17) class-attribute instance-attribute

PUSH17() = value
Description

Place 17 byte item on stack

Inputs
  • None
Outputs
  • value: pushed value, aligned to the right (put in the lowest significant bytes)
Fork

Frontier

Gas

3

Source: evm.codes/#70

PUSH18 = Opcode(113, pushed_stack_items=1, data_portion_length=18) class-attribute instance-attribute

PUSH18() = value
Description

Place 18 byte item on stack

Inputs
  • None
Outputs
  • value: pushed value, aligned to the right (put in the lowest significant bytes)
Fork

Frontier

Gas

3

Source: evm.codes/#71

PUSH19 = Opcode(114, pushed_stack_items=1, data_portion_length=19) class-attribute instance-attribute

PUSH19() = value
Description

Place 19 byte item on stack

Inputs
  • None
Outputs
  • value: pushed value, aligned to the right (put in the lowest significant bytes)
Fork

Frontier

Gas

3

Source: evm.codes/#72

PUSH20 = Opcode(115, pushed_stack_items=1, data_portion_length=20) class-attribute instance-attribute

PUSH20() = value
Description

Place 20 byte item on stack

Inputs
  • None
Outputs
  • value: pushed value, aligned to the right (put in the lowest significant bytes)
Fork

Frontier

Gas

3

Source: evm.codes/#73

PUSH21 = Opcode(116, pushed_stack_items=1, data_portion_length=21) class-attribute instance-attribute

PUSH21() = value
Description

Place 21 byte item on stack

Inputs
  • None
Outputs
  • value: pushed value, aligned to the right (put in the lowest significant bytes)
Fork

Frontier

Gas

3

Source: evm.codes/#74

PUSH22 = Opcode(117, pushed_stack_items=1, data_portion_length=22) class-attribute instance-attribute

PUSH22() = value
Description

Place 22 byte item on stack

Inputs
  • None
Outputs
  • value: pushed value, aligned to the right (put in the lowest significant bytes)
Fork

Frontier

Gas

3

Source: evm.codes/#75

PUSH23 = Opcode(118, pushed_stack_items=1, data_portion_length=23) class-attribute instance-attribute

PUSH23() = value
Description

Place 23 byte item on stack

Inputs
  • None
Outputs
  • value: pushed value, aligned to the right (put in the lowest significant bytes)
Fork

Frontier

Gas

3

Source: evm.codes/#76

PUSH24 = Opcode(119, pushed_stack_items=1, data_portion_length=24) class-attribute instance-attribute

PUSH24() = value
Description

Place 24 byte item on stack

Inputs
  • None
Outputs
  • value: pushed value, aligned to the right (put in the lowest significant bytes)
Fork

Frontier

Gas

3

Source: evm.codes/#77

PUSH25 = Opcode(120, pushed_stack_items=1, data_portion_length=25) class-attribute instance-attribute

PUSH25() = value
Description

Place 25 byte item on stack

Inputs
  • None
Outputs
  • value: pushed value, aligned to the right (put in the lowest significant bytes)
Fork

Frontier

Gas

3

Source: evm.codes/#78

PUSH26 = Opcode(121, pushed_stack_items=1, data_portion_length=26) class-attribute instance-attribute

PUSH26() = value
Description

Place 26 byte item on stack

Inputs
  • None
Outputs
  • value: pushed value, aligned to the right (put in the lowest significant bytes)
Fork

Frontier

Gas

3

Source: evm.codes/#79

PUSH27 = Opcode(122, pushed_stack_items=1, data_portion_length=27) class-attribute instance-attribute

PUSH27() = value
Description

Place 27 byte item on stack

Inputs
  • None
Outputs
  • value: pushed value, aligned to the right (put in the lowest significant bytes)
Fork

Frontier

Gas

3

Source: evm.codes/#7A

PUSH28 = Opcode(123, pushed_stack_items=1, data_portion_length=28) class-attribute instance-attribute

PUSH28() = value
Description

Place 28 byte item on stack

Inputs
  • None
Outputs
  • value: pushed value, aligned to the right (put in the lowest significant bytes)
Fork

Frontier

Gas

3

Source: evm.codes/#7B

PUSH29 = Opcode(124, pushed_stack_items=1, data_portion_length=29) class-attribute instance-attribute

PUSH29() = value
Description

Place 29 byte item on stack

Inputs
  • None
Outputs
  • value: pushed value, aligned to the right (put in the lowest significant bytes)
Fork

Frontier

Gas

3

Source: evm.codes/#7C

PUSH30 = Opcode(125, pushed_stack_items=1, data_portion_length=30) class-attribute instance-attribute

PUSH30() = value
Description

Place 30 byte item on stack

Inputs
  • None
Outputs
  • value: pushed value, aligned to the right (put in the lowest significant bytes)
Fork

Frontier

Gas

3

Source: evm.codes/#7D

PUSH31 = Opcode(126, pushed_stack_items=1, data_portion_length=31) class-attribute instance-attribute

PUSH31() = value
Description

Place 31 byte item on stack

Inputs
  • None
Outputs
  • value: pushed value, aligned to the right (put in the lowest significant bytes)
Fork

Frontier

Gas

3

Source: evm.codes/#7E

PUSH32 = Opcode(127, pushed_stack_items=1, data_portion_length=32) class-attribute instance-attribute

PUSH32() = value
Description

Place 32 byte item on stack

Inputs
  • None
Outputs
  • value: pushed value, aligned to the right (put in the lowest significant bytes)
Fork

Frontier

Gas

3

Source: evm.codes/#7F

DUP1 = Opcode(128, pushed_stack_items=1, min_stack_height=1) class-attribute instance-attribute

DUP1(value) = value, value
Description

Duplicate 1st stack item

Inputs
  • value: value to duplicate
Outputs
  • value: duplicated value
  • value: original value
Fork

Frontier

Gas

3

Source: evm.codes/#80

DUP2 = Opcode(129, pushed_stack_items=1, min_stack_height=2) class-attribute instance-attribute

DUP2(v1, v2) = v2, v1, v2
Description

Duplicate 2nd stack item

Inputs
  • v1: ignored value
  • v2: value to duplicate
Outputs
  • v2: duplicated value
  • v1: ignored value
  • v2: original value
Fork

Frontier

Gas

3

Source: evm.codes/#81

DUP3 = Opcode(130, pushed_stack_items=1, min_stack_height=3) class-attribute instance-attribute

DUP3(v1, v2, v3) = v3, v1, v2, v3
Description

Duplicate 3rd stack item

Inputs
  • v1: ignored value
  • v2: ignored value
  • v3: value to duplicate
Outputs
  • v3: duplicated value
  • v1: ignored value
  • v2: ignored value
  • v3: original value
Fork

Frontier

Gas

3

Source: evm.codes/#82

DUP4 = Opcode(131, pushed_stack_items=1, min_stack_height=4) class-attribute instance-attribute

DUP4(v1, v2, v3, v4) = v4, v1, v2, v3, v4
Description

Duplicate 4th stack item

Inputs
  • v1: ignored value
  • v2: ignored value
  • v3: ignored value
  • v4: value to duplicate
Outputs
  • v4: duplicated value
  • v1: ignored value
  • v2: ignored value
  • v3: ignored value
  • v4: original value
Fork

Frontier

Gas

3

Source: evm.codes/#83

DUP5 = Opcode(132, pushed_stack_items=1, min_stack_height=5) class-attribute instance-attribute

DUP5(v1, v2, v3, v4, v5) = v5, v1, v2, v3, v4, v5
Description

Duplicate 5th stack item

Inputs
  • v1: ignored value
  • v2: ignored value
  • v3: ignored value
  • v4: ignored value
  • v5: value to duplicate
Outputs
  • v5: duplicated value
  • v1: ignored value
  • v2: ignored value
  • v3: ignored value
  • v4: ignored value
  • v5: original value
Fork

Frontier

Gas

3

Source: evm.codes/#84

DUP6 = Opcode(133, pushed_stack_items=1, min_stack_height=6) class-attribute instance-attribute

DUP6(v1, v2, ..., v5, v6) = v6, v1, v2, ..., v5, v6
Description

Duplicate 6th stack item

Inputs
  • v1: ignored value
  • v2: ignored value
  • ...
  • v5: ignored value
  • v6: value to duplicate
Outputs
  • v6: duplicated value
  • v1: ignored value
  • v2: ignored value
  • ...
  • v5: ignored value
  • v6: original value
Fork

Frontier

Gas

3

Source: evm.codes/#85

DUP7 = Opcode(134, pushed_stack_items=1, min_stack_height=7) class-attribute instance-attribute

DUP7(v1, v2, ..., v6, v7) = v7, v1, v2, ..., v6, v7
Description

Duplicate 7th stack item

Inputs
  • v1: ignored value
  • v2: ignored value
  • ...
  • v6: ignored value
  • v7: value to duplicate
Outputs
  • v7: duplicated value
  • v1: ignored value
  • v2: ignored value
  • ...
  • v6: ignored value
  • v7: original value
Fork

Frontier

Gas

3

Source: evm.codes/#86

DUP8 = Opcode(135, pushed_stack_items=1, min_stack_height=8) class-attribute instance-attribute

DUP8(v1, v2, ..., v7, v8) = v8, v1, v2, ..., v7, v8
Description

Duplicate 8th stack item

Inputs
  • v1: ignored value
  • v2: ignored value
  • ...
  • v7: ignored value
  • v8: value to duplicate
Outputs
  • v8: duplicated value
  • v1: ignored value
  • v2: ignored value
  • ...
  • v7: ignored value
  • v8: original value
Fork

Frontier

Gas

3

Source: evm.codes/#87

DUP9 = Opcode(136, pushed_stack_items=1, min_stack_height=9) class-attribute instance-attribute

DUP9(v1, v2, ..., v8, v9) = v9, v1, v2, ..., v8, v9
Description

Duplicate 9th stack item

Inputs
  • v1: ignored value
  • v2: ignored value
  • ...
  • v8: ignored value
  • v9: value to duplicate
Outputs
  • v9: duplicated value
  • v1: ignored value
  • v2: ignored value
  • ...
  • v8: ignored value
  • v9: original value
Fork

Frontier

Gas

3

Source: evm.codes/#88

DUP10 = Opcode(137, pushed_stack_items=1, min_stack_height=10) class-attribute instance-attribute

DUP10(v1, v2, ..., v9, v10) = v10, v1, v2, ..., v9, v10
Description

Duplicate 10th stack item

Inputs
  • v1: ignored value
  • v2: ignored value
  • ...
  • v9: ignored value
  • v10: value to duplicate
Outputs
  • v10: duplicated value
  • v1: ignored value
  • v2: ignored value
  • ...
  • v9: ignored value
  • v10: original value
Fork

Frontier

Gas

3

Source: evm.codes/#89

DUP11 = Opcode(138, pushed_stack_items=1, min_stack_height=11) class-attribute instance-attribute

DUP11(v1, v2, ..., v10, v11) = v11, v1, v2, ..., v10, v11
Description

Duplicate 11th stack item

Inputs
  • v1: ignored value
  • v2: ignored value
  • ...
  • v10: ignored value
  • v11: value to duplicate
Outputs
  • v11: duplicated value
  • v1: ignored value
  • v2: ignored value
  • ...
  • v10: ignored value
  • v11: original value
Fork

Frontier

Gas

3

Source: evm.codes/#8A

DUP12 = Opcode(139, pushed_stack_items=1, min_stack_height=12) class-attribute instance-attribute

DUP12(v1, v2, ..., v11, v12) = v12, v1, v2, ..., v11, v12
Description

Duplicate 12th stack item

Inputs
  • v1: ignored value
  • v2: ignored value
  • ...
  • v11: ignored value
  • v12: value to duplicate
Outputs
  • v12: duplicated value
  • v1: ignored value
  • v2: ignored value
  • ...
  • v11: ignored value
  • v12: original value
Fork

Frontier

Gas

3

Source: evm.codes/#8B

DUP13 = Opcode(140, pushed_stack_items=1, min_stack_height=13) class-attribute instance-attribute

DUP13(v1, v2, ..., v12, v13) = v13, v1, v2, ..., v12, v13
Description

Duplicate 13th stack item

Inputs
  • v1: ignored value
  • v2: ignored value
  • ...
  • v12: ignored value
  • v13: value to duplicate
Outputs
  • v13: duplicated value
  • v1: ignored value
  • v2: ignored value
  • ...
  • v12: ignored value
  • v13: original value
Fork

Frontier

Gas

3

Source: evm.codes/#8C

DUP14 = Opcode(141, pushed_stack_items=1, min_stack_height=14) class-attribute instance-attribute

DUP14(v1, v2, ..., v13, v14) = v14, v1, v2, ..., v13, v14
Description

Duplicate 14th stack item

Inputs
  • v1: ignored value
  • v2: ignored value
  • ...
  • v13: ignored value
  • v14: value to duplicate
Outputs
  • v14: duplicated value
  • v1: ignored value
  • v2: ignored value
  • ...
  • v13: ignored value
  • v14: original value
Fork

Frontier

Gas

3

Source: evm.codes/#8D

DUP15 = Opcode(142, pushed_stack_items=1, min_stack_height=15) class-attribute instance-attribute

DUP15(v1, v2, ..., v14, v15) = v15, v1, v2, ..., v14, v15
Description

Duplicate 15th stack item

Inputs
  • v1: ignored value
  • v2: ignored value
  • ...
  • v14: ignored value
  • v15: value to duplicate
Outputs
  • v15: duplicated value
  • v1: ignored value
  • v2: ignored value
  • ...
  • v14: ignored value
  • v15: original value
Fork

Frontier

Gas

3

Source: evm.codes/#8E

DUP16 = Opcode(143, pushed_stack_items=1, min_stack_height=16) class-attribute instance-attribute

DUP16(v1, v2, ..., v15, v16) = v16, v1, v2, ..., v15, v16
Description

Duplicate 16th stack item

Inputs
  • v1: ignored value
  • v2: ignored value
  • ...
  • v15: ignored value
  • v16: value to duplicate
Outputs
  • v16: duplicated value
  • v1: ignored value
  • v2: ignored value
  • ...
  • v15: ignored value
  • v16: original value
Fork

Frontier

Gas

3

Source: evm.codes/#8F

SWAP1 = Opcode(144, min_stack_height=2) class-attribute instance-attribute

SWAP1(v1, v2) = v2, v1
Description

Exchange the top stack item with the second stack item.

Inputs
  • v1: value to swap
  • v2: value to swap
Outputs
  • v1: swapped value
  • v2: swapped value
Fork

Frontier

Gas

3

Source: evm.codes/#90

SWAP2 = Opcode(145, min_stack_height=3) class-attribute instance-attribute

SWAP2(v1, v2, v3) = v3, v2, v1
Description

Exchange 1st and 3rd stack items

Inputs
  • v1: value to swap
  • v2: ignored value
  • v3: value to swap
Outputs
  • v3: swapped value
  • v2: ignored value
  • v1: swapped value
Fork

Frontier

Gas

3

Source: evm.codes/#91

SWAP3 = Opcode(146, min_stack_height=4) class-attribute instance-attribute

SWAP3(v1, v2, v3, v4) = v4, v2, v3, v1
Description

Exchange 1st and 4th stack items

Inputs
  • v1: value to swap
  • v2: ignored value
  • v3: ignored value
  • v4: value to swap
Outputs
  • v4: swapped value
  • v2: ignored value
  • v3: ignored value
  • v1: swapped value
Fork

Frontier

Gas

3

Source: evm.codes/#92

SWAP4 = Opcode(147, min_stack_height=5) class-attribute instance-attribute

SWAP4(v1, v2, ..., v4, v5) = v5, v2, ..., v4, v1
Description

Exchange 1st and 5th stack items

Inputs
  • v1: value to swap
  • v2: ignored value
  • ...
  • v4: ignored value
  • v5: value to swap
Outputs
  • v5: swapped value
  • v2: ignored value
  • ...
  • v4: ignored value
  • v1: swapped value
Fork

Frontier

Gas

3

Source: evm.codes/#93

SWAP5 = Opcode(148, min_stack_height=6) class-attribute instance-attribute

SWAP5(v1, v2, ..., v5, v6) = v6, v2, ..., v5, v1
Description

Exchange 1st and 6th stack items

Inputs
  • v1: value to swap
  • v2: ignored value
  • ...
  • v5: ignored value
  • v6: value to swap
Outputs
  • v6: swapped value
  • v2: ignored value
  • ...
  • v5: ignored value
  • v1: swapped value
Fork

Frontier

Gas

3

Source: evm.codes/#94

SWAP6 = Opcode(149, min_stack_height=7) class-attribute instance-attribute

SWAP6(v1, v2, ..., v6, v7) = v7, v2, ..., v6, v1
Description

Exchange 1st and 7th stack items

Inputs
  • v1: value to swap
  • v2: ignored value
  • ...
  • v6: ignored value
  • v7: value to swap
Outputs
  • v7: swapped value
  • v2: ignored value
  • ...
  • v6: ignored value
  • v1: swapped value
Fork

Frontier

Gas

3

Source: evm.codes/#95

SWAP7 = Opcode(150, min_stack_height=8) class-attribute instance-attribute

SWAP7(v1, v2, ..., v7, v8) = v8, v2, ..., v7, v1
Description

Exchange 1st and 8th stack items

Inputs
  • v1: value to swap
  • v2: ignored value
  • ...
  • v7: ignored value
  • v8: value to swap
Outputs
  • v8: swapped value
  • v2: ignored value
  • ...
  • v7: ignored value
  • v1: swapped value
Fork

Frontier

Gas

3

Source: evm.codes/#96

SWAP8 = Opcode(151, min_stack_height=9) class-attribute instance-attribute

SWAP8(v1, v2, ..., v8, v9) = v9, v2, ..., v8, v1
Description

Exchange 1st and 9th stack items

Inputs
  • v1: value to swap
  • v2: ignored value
  • ...
  • v8: ignored value
  • v9: value to swap
Outputs
  • v9: swapped value
  • v2: ignored value
  • ...
  • v8: ignored value
  • v1: swapped value
Fork

Frontier

Gas

3

Source: evm.codes/#97

SWAP9 = Opcode(152, min_stack_height=10) class-attribute instance-attribute

SWAP9(v1, v2, ..., v9, v10) = v10, v2, ..., v9, v1
Description

Exchange 1st and 10th stack items

Inputs
  • v1: value to swap
  • v2: ignored value
  • ...
  • v9: ignored value
  • v10: value to swap
Outputs
  • v10: swapped value
  • v2: ignored value
  • ...
  • v9: ignored value
  • v1: swapped value
Fork

Frontier

Gas

3

Source: evm.codes/#98

SWAP10 = Opcode(153, min_stack_height=11) class-attribute instance-attribute

SWAP10(v1, v2, ..., v10, v11) = v11, v2, ..., v10, v1
Description

Exchange 1st and 11th stack items

Inputs
  • v1: value to swap
  • v2: ignored value
  • ...
  • v10: ignored value
  • v11: value to swap
Outputs
  • v11: swapped value
  • v2: ignored value
  • ...
  • v10: ignored value
  • v1: swapped value
Fork

Frontier

Gas

3

Source: evm.codes/#99

SWAP11 = Opcode(154, min_stack_height=12) class-attribute instance-attribute

SWAP11(v1, v2, ..., v11, v12) = v12, v2, ..., v11, v1
Description

Exchange 1st and 12th stack items

Inputs
  • v1: value to swap
  • v2: ignored value
  • ...
  • v11: ignored value
  • v12: value to swap
Outputs
  • v12: swapped value
  • v2: ignored value
  • ...
  • v11: ignored value
  • v1: swapped value
Fork

Frontier

Gas

3

Source: evm.codes/#9A

SWAP12 = Opcode(155, min_stack_height=13) class-attribute instance-attribute

SWAP12(v1, v2, ..., v12, v13) = v13, v2, ..., v12, v1
Description

Exchange 1st and 13th stack items

Inputs
  • v1: value to swap
  • v2: ignored value
  • ...
  • v12: ignored value
  • v13: value to swap
Outputs
  • v13: swapped value
  • v2: ignored value
  • ...
  • v12: ignored value
  • v1: swapped value
Fork

Frontier

Gas

3

Source: evm.codes/#9B

SWAP13 = Opcode(156, min_stack_height=14) class-attribute instance-attribute

SWAP13(v1, v2, ..., v13, v14) = v14, v2, ..., v13, v1
Description

Exchange 1st and 14th stack items

Inputs
  • v1: value to swap
  • v2: ignored value
  • ...
  • v13: ignored value
  • v14: value to swap
Outputs
  • v14: swapped value
  • v2: ignored value
  • ...
  • v13: ignored value
  • v1: swapped value
Fork

Frontier

Gas

3

Source: evm.codes/#9C

SWAP14 = Opcode(157, min_stack_height=15) class-attribute instance-attribute

SWAP14(v1, v2, ..., v14, v15) = v15, v2, ..., v14, v1
Description

Exchange 1st and 15th stack items

Inputs
  • v1: value to swap
  • v2: ignored value
  • ...
  • v14: ignored value
  • v15: value to swap
Outputs
  • v15: swapped value
  • v2: ignored value
  • ...
  • v14: ignored value
  • v1: swapped value
Fork

Frontier

Gas

3

Source: evm.codes/#9D

SWAP15 = Opcode(158, min_stack_height=16) class-attribute instance-attribute

SWAP15(v1, v2, ..., v15, v16) = v16, v2, ..., v15, v1
Description

Exchange 1st and 16th stack items

Inputs
  • v1: value to swap
  • v2: ignored value
  • ...
  • v15: ignored value
  • v16: value to swap
Outputs
  • v16: swapped value
  • v2: ignored value
  • ...
  • v15: ignored value
  • v1: swapped value
Fork

Frontier

Gas

3

Source: evm.codes/#9E

SWAP16 = Opcode(159, min_stack_height=17) class-attribute instance-attribute

SWAP16(v1, v2, ..., v16, v17) = v17, v2, ..., v16, v1
Description

Exchange 1st and 17th stack items

Inputs
  • v1: value to swap
  • v2: ignored value
  • ...
  • v16: ignored value
  • v17: value to swap
Outputs
  • v17: swapped value
  • v2: ignored value
  • ...
  • v16: ignored value
  • v1: swapped value
Fork

Frontier

Gas

3

Source: evm.codes/#9F

LOG0 = Opcode(160, popped_stack_items=2) class-attribute instance-attribute

LOG0(offset, size)
Description

Append log record with no topics

Inputs
  • offset: byte offset in the memory in bytes
  • size: byte size to copy
Outputs
  • None
Fork

Frontier

Gas
  • static_gas = 375
  • dynamic_gas = 375 * topic_count + 8 * size + memory_expansion_cost

Source: evm.codes/#A0

LOG1 = Opcode(161, popped_stack_items=3) class-attribute instance-attribute

LOG1(offset, size, topic1)
Description

Append log record with one topic

Inputs
  • offset: byte offset in the memory in bytes
  • size: byte size to copy
  • topic1: 32-byte value
Outputs
  • None
Fork

Frontier

Gas
  • static_gas = 375
  • dynamic_gas = 375 * topic_count + 8 * size + memory_expansion_cost

Source: evm.codes/#A1

LOG2 = Opcode(162, popped_stack_items=4) class-attribute instance-attribute

LOG2(offset, size, topic1, topic2)
Description

Append log record with two topics

Inputs
  • offset: byte offset in the memory in bytes
  • size: byte size to copy
  • topic1: 32-byte value
  • topic2: 32-byte value
Outputs
  • None
Fork

Frontier

Gas
  • static_gas = 375
  • dynamic_gas = 375 * topic_count + 8 * size + memory_expansion_cost

Source: evm.codes/#A2

LOG3 = Opcode(163, popped_stack_items=5) class-attribute instance-attribute

LOG3(offset, size, topic1, topic2, topic3)
Description

Append log record with three topics

Inputs
  • offset: byte offset in the memory in bytes
  • size: byte size to copy
  • topic1: 32-byte value
  • topic2: 32-byte value
  • topic3: 32-byte value
Outputs
  • None
Fork

Frontier

Gas
  • static_gas = 375
  • dynamic_gas = 375 * topic_count + 8 * size + memory_expansion_cost

Source: evm.codes/#A3

LOG4 = Opcode(164, popped_stack_items=6) class-attribute instance-attribute

LOG4(offset, size, topic1, topic2, topic3, topic4)
Description

Append log record with four topics

Inputs
  • offset: byte offset in the memory in bytes
  • size: byte size to copy
  • topic1: 32-byte value
  • topic2: 32-byte value
  • topic3: 32-byte value
  • topic4: 32-byte value
Outputs
  • None
Fork

Frontier

Gas
  • static_gas = 375
  • dynamic_gas = 375 * topic_count + 8 * size + memory_expansion_cost

Source: evm.codes/#A4

RJUMP = Opcode(224, data_portion_length=2) class-attribute instance-attribute

!!! Note: This opcode is under development

RJUMP()
Description
Inputs
Outputs
Fork

EOF Fork

Gas

Source: eips.ethereum.org/EIPS/eip-4200

RJUMPI = Opcode(225, popped_stack_items=1, data_portion_length=2) class-attribute instance-attribute

!!! Note: This opcode is under development

RJUMPI()
Description
Inputs
Outputs
Fork

EOF Fork

Gas

Source: eips.ethereum.org/EIPS/eip-4200

RJUMPV = Opcode(226) class-attribute instance-attribute

!!! Note: This opcode is under development

RJUMPV()
Description
Inputs
Outputs
Fork

EOF Fork

Gas

Source: eips.ethereum.org/EIPS/eip-4200

RETF = Opcode(228) class-attribute instance-attribute

!!! Note: This opcode is under development

RETF()
Description
Inputs
Outputs
Fork

EOF Fork

Gas

3

Source: eips.ethereum.org/EIPS/eip-4750

CREATE = Opcode(240, popped_stack_items=3, pushed_stack_items=1) class-attribute instance-attribute

CREATE(value, offset, length) = address
Description

Create a new contract with the given code

Inputs
  • value: value in wei to send to the new account
  • offset: byte offset in the memory in bytes, the initialisation code for the new account
  • size: byte size to copy (size of the initialisation code)
Outputs
  • address: the address of the deployed contract, 0 if the deployment failed
Fork

Frontier

Gas
minimum_word_size = (size + 31) / 32
init_code_cost = 2 * minimum_word_size
code_deposit_cost = 200 * deployed_code_size

static_gas = 32000
dynamic_gas = init_code_cost + memory_expansion_cost + deployment_code_execution_cost
    + code_deposit_cost

Source: evm.codes/#F0

CALL = Opcode(241, popped_stack_items=7, pushed_stack_items=1) class-attribute instance-attribute

CALL(gas, address, value, argsOffset, argsSize, retOffset, retSize) = success
Description

Message-call into an account

Inputs
  • gas: amount of gas to send to the sub context to execute. The gas that is not used by the sub context is returned to this one
  • address: the account which context to execute
  • value: value in wei to send to the account
  • argsOffset: byte offset in the memory in bytes, the calldata of the sub context
  • argsSize: byte size to copy (size of the calldata)
  • retOffset: byte offset in the memory in bytes, where to store the return data of the sub context
  • retSize: byte size to copy (size of the return data)
Outputs
  • success: return 0 if the sub context reverted, 1 otherwise
Fork

Frontier

Gas
static_gas = 0
dynamic_gas = memory_expansion_cost + code_execution_cost + address_access_cost
    + positive_value_cost + value_to_empty_account_cost

Source: evm.codes/#F1

CALLCODE = Opcode(242, popped_stack_items=7, pushed_stack_items=1) class-attribute instance-attribute

CALLCODE(gas, address, value, argsOffset, argsSize, retOffset, retSize) = success
Description

Message-call into this account with an alternative account's code. Executes code starting at the address to which the call is made.

Inputs
  • gas: amount of gas to send to the sub context to execute. The gas that is not used by the sub context is returned to this one
  • address: the account which code to execute
  • value: value in wei to send to the account
  • argsOffset: byte offset in the memory in bytes, the calldata of the sub context
  • argsSize: byte size to copy (size of the calldata)
  • retOffset: byte offset in the memory in bytes, where to store the return data of the sub context
  • retSize: byte size to copy (size of the return data)
Outputs
  • success: return 0 if the sub context reverted, 1 otherwise
Fork

Frontier

Gas
static_gas = 0
dynamic_gas = memory_expansion_cost + code_execution_cost + address_access_cost
    + positive_value_cost

Source: evm.codes/#F2

RETURN = Opcode(243, popped_stack_items=2) class-attribute instance-attribute

RETURN(offset, size)
Description

Halt execution returning output data

Inputs
  • offset: byte offset in the memory in bytes, to copy what will be the return data of this context
  • size: byte size to copy (size of the return data)
Outputs
  • None
Fork

Frontier

Gas
  • static_gas = 0
  • dynamic_gas = memory_expansion_cost

Source: evm.codes/#F3

DELEGATECALL = Opcode(244, popped_stack_items=6, pushed_stack_items=1) class-attribute instance-attribute

DELEGATECALL(gas, address, argsOffset, argsSize, retOffset, retSize) = success
Description

Message-call into this account with an alternative account's code, but persisting the current values for sender and value

Inputs
  • gas: amount of gas to send to the sub context to execute. The gas that is not used by the sub context is returned to this one
  • address: the account which code to execute
  • argsOffset: byte offset in the memory in bytes, the calldata of the sub context
  • argsSize: byte size to copy (size of the calldata)
  • retOffset: byte offset in the memory in bytes, where to store the return data of the sub context
  • retSize: byte size to copy (size of the return data)
Outputs
  • success: return 0 if the sub context reverted, 1 otherwise
Fork

Byzantium

Gas
  • static_gas = 0
  • dynamic_gas = memory_expansion_cost + code_execution_cost + address_access_cost

Source: evm.codes/#F4

CREATE2 = Opcode(245, popped_stack_items=4, pushed_stack_items=1) class-attribute instance-attribute

CREATE2(value, offset, size, salt) = address
Description

Creates a new contract

Inputs
  • value: value in wei to send to the new account
  • offset: byte offset in the memory in bytes, the initialisation code of the new account
  • size: byte size to copy (size of the initialisation code)
  • salt: 32-byte value used to create the new account at a deterministic address
Outputs
  • address: the address of the deployed contract, 0 if the deployment failed
Fork

Constantinople

Gas
minimum_word_size = (size + 31) / 32
init_code_cost = 2 * minimum_word_size
hash_cost = 6 * minimum_word_size
code_deposit_cost = 200 * deployed_code_size

static_gas = 32000
dynamic_gas = init_code_cost + hash_cost + memory_expansion_cost
    + deployment_code_execution_cost + code_deposit_cost

Source: evm.codes/#F5

STATICCALL = Opcode(250, popped_stack_items=6, pushed_stack_items=1) class-attribute instance-attribute

STATICCALL(gas, address, argsOffset, argsSize, retOffset, retSize) = success
Description

Static message-call into an account

Inputs
  • gas: amount of gas to send to the sub context to execute. The gas that is not used by the sub context is returned to this one
  • address: the account which context to execute
  • argsOffset: byte offset in the memory in bytes, the calldata of the sub context
  • argsSize: byte size to copy (size of the calldata)
  • retOffset: byte offset in the memory in bytes, where to store the return data of the sub context
  • retSize: byte size to copy (size of the return data)
Outputs
  • success: return 0 if the sub context reverted, 1 otherwise
Fork

Byzantium

Gas
  • static_gas = 0
  • dynamic_gas = memory_expansion_cost + code_execution_cost + address_access_cost

Source: evm.codes/#FA

REVERT = Opcode(253, popped_stack_items=2) class-attribute instance-attribute

REVERT(offset, size)
Description

Halt execution reverting state changes but returning data and remaining gas

Inputs
  • offset: byte offset in the memory in bytes. The return data of the calling context
  • size: byte size to copy (size of the return data)
Fork

Byzantium

Gas

static_gas = 0 dynamic_gas = memory_expansion_cost

Source: evm.codes/#FD

INVALID = Opcode(254) class-attribute instance-attribute

INVALID()
Description

Designated invalid instruction

Inputs

None

Outputs

None

Fork

Frontier

Gas

All the remaining gas in this context is consumed

Source: evm.codes/#FE

SELFDESTRUCT = Opcode(255, popped_stack_items=1) class-attribute instance-attribute

SELFDESTRUCT(address)
Description

Halt execution and register the account for later deletion

Inputs
  • address: account to send the current balance to
Fork

Frontier

Gas

5000

Source: evm.codes/#FF