Skip to content

Ethereum Test Types package

Common definitions and types.

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_types/helpers.py
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
@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_types/helpers.py
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
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)}"

add_kzg_version(b_hashes, kzg_version)

Adds the Kzg Version to each blob hash.

Source code in src/ethereum_test_types/helpers.py
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
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_types/helpers.py
21
22
23
24
25
26
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_types/helpers.py
56
57
58
59
60
61
62
63
64
def compute_create2_address(
    address: FixedSizeBytesConvertible, salt: FixedSizeBytesConvertible, initcode: BytesConvertible
) -> Address:
    """
    Compute address of the resulting contract created using the `CREATE2`
    opcode.
    """
    hash = Bytes(b"\xff" + Address(address) + Hash(salt) + Bytes(initcode).keccak256()).keccak256()
    return Address(hash[-20:])

compute_create_address(*, address, nonce=None, salt=0, initcode=b'', opcode=Op.CREATE)

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

Source code in src/ethereum_test_types/helpers.py
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
def compute_create_address(
    *,
    address: FixedSizeBytesConvertible | EOA,
    nonce: int | None = None,
    salt: int = 0,
    initcode: BytesConvertible = b"",
    opcode: Op = Op.CREATE,
) -> Address:
    """
    Compute address of the resulting contract created using a transaction
    or the `CREATE` opcode.
    """
    if opcode == Op.CREATE:
        if isinstance(address, EOA):
            if nonce is None:
                nonce = address.nonce
        else:
            address = Address(address)
        if nonce is None:
            nonce = 0
        hash = Bytes(encode([address, int_to_bytes(nonce)])).keccak256()
        return Address(hash[-20:])
    if opcode == Op.CREATE2:
        return compute_create2_address(address, salt, initcode)
    raise ValueError("Unsupported opcode")

compute_eofcreate_address(address, salt, init_container)

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

Source code in src/ethereum_test_types/helpers.py
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
def compute_eofcreate_address(
    address: FixedSizeBytesConvertible,
    salt: FixedSizeBytesConvertible,
    init_container: BytesConvertible,
) -> Address:
    """
    Compute address of the resulting contract created using the `EOFCREATE` opcode.
    """
    hash = Bytes(
        b"\xff" + Address(address) + Hash(salt) + Bytes(init_container).keccak256()
    ).keccak256()
    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_types/helpers.py
84
85
86
87
88
89
90
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_types/helpers.py
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
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_types/helpers.py
107
108
109
110
111
112
113
114
115
116
117
118
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

EOA

Bases: Address

An Externally Owned Account (EOA) is an account controlled by a private key.

The EOA is defined by its address and (optionally) by its corresponding private key.

Source code in src/ethereum_test_types/types.py
 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
class EOA(Address):
    """
    An Externally Owned Account (EOA) is an account controlled by a private key.

    The EOA is defined by its address and (optionally) by its corresponding private key.
    """

    key: Hash | None
    nonce: Number

    def __new__(
        cls,
        address: "FixedSizeBytesConvertible | Address | EOA | None" = None,
        *,
        key: FixedSizeBytesConvertible | None = None,
        nonce: NumberConvertible = 0,
    ):
        """
        Init the EOA.
        """
        if address is None:
            if key is None:
                raise ValueError("impossible to initialize EOA without address")
            private_key = PrivateKey(Hash(key))
            public_key = private_key.public_key
            address = Address(
                keccak256(public_key.format(compressed=False)[1:])[32 - 20 :]
            )
        elif isinstance(address, EOA):
            return address
        instance = super(EOA, cls).__new__(cls, address)
        instance.key = Hash(key) if key is not None else None
        instance.nonce = Number(nonce)
        return instance

    def get_nonce(self) -> Number:
        """
        Returns the current nonce of the EOA and increments it by one.
        """
        nonce = self.nonce
        self.nonce = Number(nonce + 1)
        return nonce

    def copy(self) -> "EOA":
        """
        Returns a copy of the EOA.
        """
        return EOA(Address(self), key=self.key, nonce=self.nonce)

__new__(address=None, *, key=None, nonce=0)

Init the EOA.

Source code in src/ethereum_test_types/types.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
def __new__(
    cls,
    address: "FixedSizeBytesConvertible | Address | EOA | None" = None,
    *,
    key: FixedSizeBytesConvertible | None = None,
    nonce: NumberConvertible = 0,
):
    """
    Init the EOA.
    """
    if address is None:
        if key is None:
            raise ValueError("impossible to initialize EOA without address")
        private_key = PrivateKey(Hash(key))
        public_key = private_key.public_key
        address = Address(
            keccak256(public_key.format(compressed=False)[1:])[32 - 20 :]
        )
    elif isinstance(address, EOA):
        return address
    instance = super(EOA, cls).__new__(cls, address)
    instance.key = Hash(key) if key is not None else None
    instance.nonce = Number(nonce)
    return instance

get_nonce()

Returns the current nonce of the EOA and increments it by one.

Source code in src/ethereum_test_types/types.py
116
117
118
119
120
121
122
def get_nonce(self) -> Number:
    """
    Returns the current nonce of the EOA and increments it by one.
    """
    nonce = self.nonce
    self.nonce = Number(nonce + 1)
    return nonce

copy()

Returns a copy of the EOA.

Source code in src/ethereum_test_types/types.py
124
125
126
127
128
def copy(self) -> "EOA":
    """
    Returns a copy of the EOA.
    """
    return EOA(Address(self), key=self.key, nonce=self.nonce)

AccessList

Bases: CamelModel

Access List for transactions.

Source code in src/ethereum_test_types/types.py
525
526
527
528
529
530
531
532
533
534
535
536
537
class AccessList(CamelModel):
    """
    Access List for transactions.
    """

    address: Address
    storage_keys: List[Hash]

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

to_list()

Returns the access list as a list of serializable elements.

Source code in src/ethereum_test_types/types.py
533
534
535
536
537
def to_list(self) -> List[Address | List[Hash]]:
    """
    Returns the access list as a list of serializable elements.
    """
    return [self.address, self.storage_keys]

Account

Bases: CamelModel

State associated with an address.

Source code in src/ethereum_test_base_types/composite_types.py
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
class Account(CamelModel):
    """
    State associated with an address.
    """

    nonce: ZeroPaddedHexNumber = ZeroPaddedHexNumber(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: ZeroPaddedHexNumber = ZeroPaddedHexNumber(0)
    """
    The amount of Wei (10<sup>-18</sup> Eth) the account has.
    """
    code: Bytes = Bytes(b"")
    """
    Bytecode contained by the account.
    """
    storage: Storage = Field(default_factory=Storage)
    """
    Storage within a contract.
    """

    NONEXISTENT: ClassVar[None] = None
    """
    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"""
            label_str = ""
            if self.address.label is not None:
                label_str = f" ({self.address.label})"
            return (
                f"unexpected nonce for account {self.address}{label_str}: "
                + 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"""
            label_str = ""
            if self.address.label is not None:
                label_str = f" ({self.address.label})"
            return (
                f"unexpected balance for account {self.address}{label_str}: "
                + 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: bytes | None
        got: bytes | None

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

        def __str__(self):
            """Print exception string"""
            label_str = ""
            if self.address.label is not None:
                label_str = f" ({self.address.label})"
            return (
                f"unexpected code for account {self.address}{label_str}: "
                + f"want {self.want}, got {self.got}"
            )

    def check_alloc(self: "Account", address: Address, account: "Account"):
        """
        Checks the returned alloc against an expected account in post state.
        Raises exception on failure.
        """
        if "nonce" in self.model_fields_set:
            if self.nonce != account.nonce:
                raise Account.NonceMismatch(
                    address=address,
                    want=self.nonce,
                    got=account.nonce,
                )

        if "balance" in self.model_fields_set:
            if self.balance != account.balance:
                raise Account.BalanceMismatch(
                    address=address,
                    want=self.balance,
                    got=account.balance,
                )

        if "code" in self.model_fields_set:
            if self.code != account.code:
                raise Account.CodeMismatch(
                    address=address,
                    want=self.code,
                    got=account.code,
                )

        if "storage" in self.model_fields_set:
            self.storage.must_be_equal(address=address, other=account.storage)

    def __bool__(self: "Account") -> bool:
        """
        Returns True on a non-empty account.
        """
        return any((self.nonce, self.balance, self.code, self.storage))

    @classmethod
    def with_code(cls: Type, code: BytesConvertible) -> "Account":
        """
        Create account with provided `code` and nonce of `1`.
        """
        return Account(nonce=HexNumber(1), code=Bytes(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 account.model_dump(exclude_unset=True)
            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: ZeroPaddedHexNumber = ZeroPaddedHexNumber(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: ZeroPaddedHexNumber = ZeroPaddedHexNumber(0) class-attribute instance-attribute

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

code: Bytes = Bytes(b'') class-attribute instance-attribute

Bytecode contained by the account.

storage: Storage = Field(default_factory=Storage) class-attribute instance-attribute

Storage within a contract.

NONEXISTENT: None = None 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_base_types/composite_types.py
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
@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"""
        label_str = ""
        if self.address.label is not None:
            label_str = f" ({self.address.label})"
        return (
            f"unexpected nonce for account {self.address}{label_str}: "
            + f"want {self.want}, got {self.got}"
        )

__str__()

Print exception string

Source code in src/ethereum_test_base_types/composite_types.py
313
314
315
316
317
318
319
320
321
def __str__(self):
    """Print exception string"""
    label_str = ""
    if self.address.label is not None:
        label_str = f" ({self.address.label})"
    return (
        f"unexpected nonce for account {self.address}{label_str}: "
        + 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_base_types/composite_types.py
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
@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"""
        label_str = ""
        if self.address.label is not None:
            label_str = f" ({self.address.label})"
        return (
            f"unexpected balance for account {self.address}{label_str}: "
            + f"want {self.want}, got {self.got}"
        )

__str__()

Print exception string

Source code in src/ethereum_test_base_types/composite_types.py
340
341
342
343
344
345
346
347
348
def __str__(self):
    """Print exception string"""
    label_str = ""
    if self.address.label is not None:
        label_str = f" ({self.address.label})"
    return (
        f"unexpected balance for account {self.address}{label_str}: "
        + 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_base_types/composite_types.py
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
@dataclass(kw_only=True)
class CodeMismatch(Exception):
    """
    Test expected a certain bytecode for an account but a different
    one was found.
    """

    address: Address
    want: bytes | None
    got: bytes | None

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

    def __str__(self):
        """Print exception string"""
        label_str = ""
        if self.address.label is not None:
            label_str = f" ({self.address.label})"
        return (
            f"unexpected code for account {self.address}{label_str}: "
            + f"want {self.want}, got {self.got}"
        )

__str__()

Print exception string

Source code in src/ethereum_test_base_types/composite_types.py
367
368
369
370
371
372
373
374
375
def __str__(self):
    """Print exception string"""
    label_str = ""
    if self.address.label is not None:
        label_str = f" ({self.address.label})"
    return (
        f"unexpected code for account {self.address}{label_str}: "
        + f"want {self.want}, got {self.got}"
    )

check_alloc(address, account)

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

Source code in src/ethereum_test_base_types/composite_types.py
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
def check_alloc(self: "Account", address: Address, account: "Account"):
    """
    Checks the returned alloc against an expected account in post state.
    Raises exception on failure.
    """
    if "nonce" in self.model_fields_set:
        if self.nonce != account.nonce:
            raise Account.NonceMismatch(
                address=address,
                want=self.nonce,
                got=account.nonce,
            )

    if "balance" in self.model_fields_set:
        if self.balance != account.balance:
            raise Account.BalanceMismatch(
                address=address,
                want=self.balance,
                got=account.balance,
            )

    if "code" in self.model_fields_set:
        if self.code != account.code:
            raise Account.CodeMismatch(
                address=address,
                want=self.code,
                got=account.code,
            )

    if "storage" in self.model_fields_set:
        self.storage.must_be_equal(address=address, other=account.storage)

__bool__()

Returns True on a non-empty account.

Source code in src/ethereum_test_base_types/composite_types.py
409
410
411
412
413
def __bool__(self: "Account") -> bool:
    """
    Returns True on a non-empty account.
    """
    return any((self.nonce, self.balance, self.code, self.storage))

with_code(code) classmethod

Create account with provided code and nonce of 1.

Source code in src/ethereum_test_base_types/composite_types.py
415
416
417
418
419
420
@classmethod
def with_code(cls: Type, code: BytesConvertible) -> "Account":
    """
    Create account with provided `code` and nonce of `1`.
    """
    return Account(nonce=HexNumber(1), code=Bytes(code))

merge(account_1, account_2) classmethod

Create a merged account from two sources.

Source code in src/ethereum_test_base_types/composite_types.py
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
@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 account.model_dump(exclude_unset=True)
        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)

Alloc

Bases: Alloc

Allocation of accounts in the state, pre and post test execution.

Source code in src/ethereum_test_types/types.py
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
class Alloc(BaseAlloc):
    """
    Allocation of accounts in the state, pre and post test execution.
    """

    _eoa_fund_amount_default: int = PrivateAttr(10**21)

    @dataclass(kw_only=True)
    class UnexpectedAccount(Exception):
        """
        Unexpected account found in the allocation.
        """

        address: Address
        account: Account | None

        def __init__(self, address: Address, account: Account | None, *args):
            super().__init__(args)
            self.address = address
            self.account = account

        def __str__(self):
            """Print exception string"""
            return f"unexpected account in allocation {self.address}: {self.account}"

    @dataclass(kw_only=True)
    class MissingAccount(Exception):
        """
        Expected account not found in the allocation.
        """

        address: Address

        def __init__(self, address: Address, *args):
            super().__init__(args)
            self.address = address

        def __str__(self):
            """Print exception string"""
            return f"Account missing from allocation {self.address}"

    @classmethod
    def merge(cls, alloc_1: "Alloc", alloc_2: "Alloc") -> "Alloc":
        """
        Returns the merged allocation of two sources.
        """
        merged = alloc_1.model_dump()

        for address, other_account in alloc_2.root.items():
            merged_account = Account.merge(merged.get(address, None), other_account)
            if merged_account:
                merged[address] = merged_account
            elif address in merged:
                merged.pop(address, None)

        return Alloc(merged)

    def __iter__(self):
        """
        Returns an iterator over the allocation.
        """
        return iter(self.root)

    def items(self):
        """
        Returns an iterator over the allocation items.
        """
        return self.root.items()

    def __getitem__(
        self, address: Address | FixedSizeBytesConvertible
    ) -> Account | None:
        """
        Returns the account associated with an address.
        """
        if not isinstance(address, Address):
            address = Address(address)
        return self.root[address]

    def __setitem__(
        self, address: Address | FixedSizeBytesConvertible, account: Account | None
    ):
        """
        Sets the account associated with an address.
        """
        if not isinstance(address, Address):
            address = Address(address)
        self.root[address] = account

    def __delitem__(self, address: Address | FixedSizeBytesConvertible):
        """
        Deletes the account associated with an address.
        """
        if not isinstance(address, Address):
            address = Address(address)
        self.root.pop(address, None)

    def __eq__(self, other) -> bool:
        """
        Returns True if both allocations are equal.
        """
        if not isinstance(other, Alloc):
            return False
        return self.root == other.root

    def __contains__(self, address: Address | FixedSizeBytesConvertible) -> bool:
        """
        Checks if an account is in the allocation.
        """
        if not isinstance(address, Address):
            address = Address(address)
        return address in self.root

    def empty_accounts(self) -> List[Address]:
        """
        Returns a list of addresses of empty accounts.
        """
        return [address for address, account in self.root.items() if not account]

    def state_root(self) -> bytes:
        """
        Returns the state root of the allocation.
        """
        state = State()
        for address, account in self.root.items():
            if account is None:
                continue
            set_account(
                state=state,
                address=FrontierAddress(address),
                account=FrontierAccount(
                    nonce=Uint(account.nonce) if account.nonce is not None else Uint(0),
                    balance=(
                        U256(account.balance)
                        if account.balance is not None
                        else U256(0)
                    ),
                    code=account.code if account.code is not None else b"",
                ),
            )
            if account.storage is not None:
                for key, value in account.storage.root.items():
                    set_storage(
                        state=state,
                        address=FrontierAddress(address),
                        key=Hash(key),
                        value=U256(value),
                    )
        return state_root(state)

    def verify_post_alloc(self, got_alloc: "Alloc"):
        """
        Verify that the allocation matches the expected post in the test.
        Raises exception on unexpected values.
        """
        assert isinstance(got_alloc, Alloc), f"got_alloc is not an Alloc: {got_alloc}"
        for address, account in self.root.items():
            if account is None:
                # Account must not exist
                if address in got_alloc.root and got_alloc.root[address] is not None:
                    raise Alloc.UnexpectedAccount(address, got_alloc.root[address])
            else:
                if address in got_alloc.root:
                    got_account = got_alloc.root[address]
                    assert isinstance(got_account, Account)
                    assert isinstance(account, Account)
                    account.check_alloc(address, got_account)
                else:
                    raise Alloc.MissingAccount(address)

    def deploy_contract(
        self,
        code: BytesConvertible,
        *,
        storage: Storage | StorageRootType = {},
        balance: NumberConvertible = 0,
        nonce: NumberConvertible = 1,
        address: Address | None = None,
        evm_code_type: EVMCodeType | None = None,
        label: str | None = None,
    ) -> Address:
        """
        Deploy a contract to the allocation.
        """
        raise NotImplementedError(
            "deploy_contract is not implemented in the base class"
        )

    def fund_eoa(
        self,
        amount: NumberConvertible | None = None,
        label: str | None = None,
        storage: Storage | None = None,
        delegation: Address | Literal["Self"] | None = None,
    ) -> EOA:
        """
        Add a previously unused EOA to the pre-alloc with the balance specified by `amount`.
        """
        raise NotImplementedError("fund_eoa is not implemented in the base class")

    def fund_address(self, address: Address, amount: NumberConvertible):
        """
        Fund an address with a given amount.

        If the address is already present in the pre-alloc the amount will be
        added to its existing balance.
        """
        raise NotImplementedError("fund_address is not implemented in the base class")

UnexpectedAccount dataclass

Bases: Exception

Unexpected account found in the allocation.

Source code in src/ethereum_test_types/types.py
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
@dataclass(kw_only=True)
class UnexpectedAccount(Exception):
    """
    Unexpected account found in the allocation.
    """

    address: Address
    account: Account | None

    def __init__(self, address: Address, account: Account | None, *args):
        super().__init__(args)
        self.address = address
        self.account = account

    def __str__(self):
        """Print exception string"""
        return f"unexpected account in allocation {self.address}: {self.account}"

__str__()

Print exception string

Source code in src/ethereum_test_types/types.py
152
153
154
def __str__(self):
    """Print exception string"""
    return f"unexpected account in allocation {self.address}: {self.account}"

MissingAccount dataclass

Bases: Exception

Expected account not found in the allocation.

Source code in src/ethereum_test_types/types.py
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
@dataclass(kw_only=True)
class MissingAccount(Exception):
    """
    Expected account not found in the allocation.
    """

    address: Address

    def __init__(self, address: Address, *args):
        super().__init__(args)
        self.address = address

    def __str__(self):
        """Print exception string"""
        return f"Account missing from allocation {self.address}"

__str__()

Print exception string

Source code in src/ethereum_test_types/types.py
168
169
170
def __str__(self):
    """Print exception string"""
    return f"Account missing from allocation {self.address}"

merge(alloc_1, alloc_2) classmethod

Returns the merged allocation of two sources.

Source code in src/ethereum_test_types/types.py
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
@classmethod
def merge(cls, alloc_1: "Alloc", alloc_2: "Alloc") -> "Alloc":
    """
    Returns the merged allocation of two sources.
    """
    merged = alloc_1.model_dump()

    for address, other_account in alloc_2.root.items():
        merged_account = Account.merge(merged.get(address, None), other_account)
        if merged_account:
            merged[address] = merged_account
        elif address in merged:
            merged.pop(address, None)

    return Alloc(merged)

__iter__()

Returns an iterator over the allocation.

Source code in src/ethereum_test_types/types.py
188
189
190
191
192
def __iter__(self):
    """
    Returns an iterator over the allocation.
    """
    return iter(self.root)

items()

Returns an iterator over the allocation items.

Source code in src/ethereum_test_types/types.py
194
195
196
197
198
def items(self):
    """
    Returns an iterator over the allocation items.
    """
    return self.root.items()

__getitem__(address)

Returns the account associated with an address.

Source code in src/ethereum_test_types/types.py
200
201
202
203
204
205
206
207
208
def __getitem__(
    self, address: Address | FixedSizeBytesConvertible
) -> Account | None:
    """
    Returns the account associated with an address.
    """
    if not isinstance(address, Address):
        address = Address(address)
    return self.root[address]

__setitem__(address, account)

Sets the account associated with an address.

Source code in src/ethereum_test_types/types.py
210
211
212
213
214
215
216
217
218
def __setitem__(
    self, address: Address | FixedSizeBytesConvertible, account: Account | None
):
    """
    Sets the account associated with an address.
    """
    if not isinstance(address, Address):
        address = Address(address)
    self.root[address] = account

__delitem__(address)

Deletes the account associated with an address.

Source code in src/ethereum_test_types/types.py
220
221
222
223
224
225
226
def __delitem__(self, address: Address | FixedSizeBytesConvertible):
    """
    Deletes the account associated with an address.
    """
    if not isinstance(address, Address):
        address = Address(address)
    self.root.pop(address, None)

__eq__(other)

Returns True if both allocations are equal.

Source code in src/ethereum_test_types/types.py
228
229
230
231
232
233
234
def __eq__(self, other) -> bool:
    """
    Returns True if both allocations are equal.
    """
    if not isinstance(other, Alloc):
        return False
    return self.root == other.root

__contains__(address)

Checks if an account is in the allocation.

Source code in src/ethereum_test_types/types.py
236
237
238
239
240
241
242
def __contains__(self, address: Address | FixedSizeBytesConvertible) -> bool:
    """
    Checks if an account is in the allocation.
    """
    if not isinstance(address, Address):
        address = Address(address)
    return address in self.root

empty_accounts()

Returns a list of addresses of empty accounts.

Source code in src/ethereum_test_types/types.py
244
245
246
247
248
def empty_accounts(self) -> List[Address]:
    """
    Returns a list of addresses of empty accounts.
    """
    return [address for address, account in self.root.items() if not account]

state_root()

Returns the state root of the allocation.

Source code in src/ethereum_test_types/types.py
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
def state_root(self) -> bytes:
    """
    Returns the state root of the allocation.
    """
    state = State()
    for address, account in self.root.items():
        if account is None:
            continue
        set_account(
            state=state,
            address=FrontierAddress(address),
            account=FrontierAccount(
                nonce=Uint(account.nonce) if account.nonce is not None else Uint(0),
                balance=(
                    U256(account.balance)
                    if account.balance is not None
                    else U256(0)
                ),
                code=account.code if account.code is not None else b"",
            ),
        )
        if account.storage is not None:
            for key, value in account.storage.root.items():
                set_storage(
                    state=state,
                    address=FrontierAddress(address),
                    key=Hash(key),
                    value=U256(value),
                )
    return state_root(state)

verify_post_alloc(got_alloc)

Verify that the allocation matches the expected post in the test. Raises exception on unexpected values.

Source code in src/ethereum_test_types/types.py
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
def verify_post_alloc(self, got_alloc: "Alloc"):
    """
    Verify that the allocation matches the expected post in the test.
    Raises exception on unexpected values.
    """
    assert isinstance(got_alloc, Alloc), f"got_alloc is not an Alloc: {got_alloc}"
    for address, account in self.root.items():
        if account is None:
            # Account must not exist
            if address in got_alloc.root and got_alloc.root[address] is not None:
                raise Alloc.UnexpectedAccount(address, got_alloc.root[address])
        else:
            if address in got_alloc.root:
                got_account = got_alloc.root[address]
                assert isinstance(got_account, Account)
                assert isinstance(account, Account)
                account.check_alloc(address, got_account)
            else:
                raise Alloc.MissingAccount(address)

deploy_contract(code, *, storage={}, balance=0, nonce=1, address=None, evm_code_type=None, label=None)

Deploy a contract to the allocation.

Source code in src/ethereum_test_types/types.py
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
def deploy_contract(
    self,
    code: BytesConvertible,
    *,
    storage: Storage | StorageRootType = {},
    balance: NumberConvertible = 0,
    nonce: NumberConvertible = 1,
    address: Address | None = None,
    evm_code_type: EVMCodeType | None = None,
    label: str | None = None,
) -> Address:
    """
    Deploy a contract to the allocation.
    """
    raise NotImplementedError(
        "deploy_contract is not implemented in the base class"
    )

fund_eoa(amount=None, label=None, storage=None, delegation=None)

Add a previously unused EOA to the pre-alloc with the balance specified by amount.

Source code in src/ethereum_test_types/types.py
319
320
321
322
323
324
325
326
327
328
329
def fund_eoa(
    self,
    amount: NumberConvertible | None = None,
    label: str | None = None,
    storage: Storage | None = None,
    delegation: Address | Literal["Self"] | None = None,
) -> EOA:
    """
    Add a previously unused EOA to the pre-alloc with the balance specified by `amount`.
    """
    raise NotImplementedError("fund_eoa is not implemented in the base class")

fund_address(address, amount)

Fund an address with a given amount.

If the address is already present in the pre-alloc the amount will be added to its existing balance.

Source code in src/ethereum_test_types/types.py
331
332
333
334
335
336
337
338
def fund_address(self, address: Address, amount: NumberConvertible):
    """
    Fund an address with a given amount.

    If the address is already present in the pre-alloc the amount will be
    added to its existing balance.
    """
    raise NotImplementedError("fund_address is not implemented in the base class")

AuthorizationTuple

Bases: AuthorizationTupleGeneric[HexNumber]

Authorization tuple for transactions.

Source code in src/ethereum_test_types/types.py
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
class AuthorizationTuple(AuthorizationTupleGeneric[HexNumber]):
    """
    Authorization tuple for transactions.
    """

    signer: EOA | None = None
    secret_key: Hash | None = None

    def model_post_init(self, __context: Any) -> None:
        """
        Automatically signs the authorization tuple if a secret key or sender are provided.
        """
        super().model_post_init(__context)

        if self.secret_key is not None:
            self.sign(self.secret_key)
        elif self.signer is not None:
            assert self.signer.key is not None, "signer must have a key"
            self.sign(self.signer.key)
        else:
            assert self.v is not None, "v must be set"
            assert self.r is not None, "r must be set"
            assert self.s is not None, "s must be set"

            # Calculate the address from the signature
            try:
                signature_bytes = (
                    int(self.r).to_bytes(32, byteorder="big")
                    + int(self.s).to_bytes(32, byteorder="big")
                    + bytes([self.v])
                )
                public_key = PublicKey.from_signature_and_message(
                    signature_bytes, self.signing_bytes.keccak256(), hasher=None
                )
                self.signer = EOA(
                    address=Address(
                        keccak256(public_key.format(compressed=False)[1:])[32 - 20 :]
                    )
                )
            except Exception:
                # Signer remains `None` in this case
                pass

    def sign(self, private_key: Hash) -> None:
        """
        Signs the authorization tuple with a private key.
        """
        signature = self.signature(private_key)

        self.v = HexNumber(signature[0])
        self.r = HexNumber(signature[1])
        self.s = HexNumber(signature[2])

model_post_init(__context)

Automatically signs the authorization tuple if a secret key or sender are provided.

Source code in src/ethereum_test_types/types.py
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
def model_post_init(self, __context: Any) -> None:
    """
    Automatically signs the authorization tuple if a secret key or sender are provided.
    """
    super().model_post_init(__context)

    if self.secret_key is not None:
        self.sign(self.secret_key)
    elif self.signer is not None:
        assert self.signer.key is not None, "signer must have a key"
        self.sign(self.signer.key)
    else:
        assert self.v is not None, "v must be set"
        assert self.r is not None, "r must be set"
        assert self.s is not None, "s must be set"

        # Calculate the address from the signature
        try:
            signature_bytes = (
                int(self.r).to_bytes(32, byteorder="big")
                + int(self.s).to_bytes(32, byteorder="big")
                + bytes([self.v])
            )
            public_key = PublicKey.from_signature_and_message(
                signature_bytes, self.signing_bytes.keccak256(), hasher=None
            )
            self.signer = EOA(
                address=Address(
                    keccak256(public_key.format(compressed=False)[1:])[32 - 20 :]
                )
            )
        except Exception:
            # Signer remains `None` in this case
            pass

sign(private_key)

Signs the authorization tuple with a private key.

Source code in src/ethereum_test_types/types.py
641
642
643
644
645
646
647
648
649
def sign(self, private_key: Hash) -> None:
    """
    Signs the authorization tuple with a private key.
    """
    signature = self.signature(private_key)

    self.v = HexNumber(signature[0])
    self.r = HexNumber(signature[1])
    self.s = HexNumber(signature[2])

CamelModel

Bases: CopyValidateModel

A base model that converts field names to camel case when serializing.

For example, the field name current_timestamp in a Python model will be represented as currentTimestamp when it is serialized to json.

Source code in src/ethereum_test_base_types/pydantic.py
25
26
27
28
29
30
31
32
33
34
35
36
37
class CamelModel(CopyValidateModel):
    """
    A base model that converts field names to camel case when serializing.

    For example, the field name `current_timestamp` in a Python model will be represented
    as `currentTimestamp` when it is serialized to json.
    """

    model_config = ConfigDict(
        alias_generator=to_camel,
        populate_by_name=True,
        validate_default=True,
    )

ConsolidationRequest

Bases: ConsolidationRequestGeneric[HexNumber]

Consolidation Request type

Source code in src/ethereum_test_types/types.py
1327
1328
1329
1330
1331
1332
class ConsolidationRequest(ConsolidationRequestGeneric[HexNumber]):
    """
    Consolidation Request type
    """

    pass

DepositRequest

Bases: DepositRequestGeneric[HexNumber]

Deposit Request type

Source code in src/ethereum_test_types/types.py
1255
1256
1257
1258
1259
1260
class DepositRequest(DepositRequestGeneric[HexNumber]):
    """
    Deposit Request type
    """

    pass

Environment

Bases: EnvironmentGeneric[Number]

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

Source code in src/ethereum_test_types/types.py
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
class Environment(EnvironmentGeneric[Number]):
    """
    Structure used to keep track of the context in which a block
    must be executed.
    """

    blob_gas_used: Number | None = Field(None, alias="currentBlobGasUsed")
    parent_ommers_hash: Hash = Field(Hash(0), alias="parentUncleHash")
    parent_blob_gas_used: Number | None = Field(None)
    parent_excess_blob_gas: Number | None = Field(None)
    parent_beacon_block_root: Hash | None = Field(None)
    verkle_conversion_address: Address | None = Field(
        None, alias="currentConversionAddress"
    )
    verkle_conversion_slot_hash: Hash | None = Field(
        None, alias="currentConversionSlotHash"
    )
    verkle_conversion_started: bool | None = Field(
        None, alias="currentConversionStarted"
    )
    verkle_conversion_ended: bool | None = Field(None, alias="currentConversionEnded")
    verkle_conversion_storage_processed: bool | None = Field(
        None,
        alias="currentConversionStorageProcessed",
    )

    block_hashes: Dict[Number, Hash] = Field(default_factory=dict)
    ommers: List[Hash] = Field(default_factory=list)
    withdrawals: List[Withdrawal] | None = Field(None)
    extra_data: Bytes = Field(Bytes(b"\x00"), exclude=True)

    @computed_field  # type: ignore[misc]
    @cached_property
    def parent_hash(self) -> Hash | None:
        """
        Obtains the latest hash according to the highest block number in
        `block_hashes`.
        """
        if len(self.block_hashes) == 0:
            return None

        last_index = max(self.block_hashes.keys())
        return Hash(self.block_hashes[last_index])

    def set_fork_requirements(self, fork: Fork) -> "Environment":
        """
        Fills the required fields in an environment depending on the fork.
        """
        number = self.number
        timestamp = self.timestamp

        updated_values: Dict[str, Any] = {}

        if (
            fork.header_prev_randao_required(number, timestamp)
            and self.prev_randao is None
        ):
            updated_values["prev_randao"] = 0

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

        if (
            fork.header_base_fee_required(number, timestamp)
            and self.base_fee_per_gas is None
            and self.parent_base_fee_per_gas is None
        ):
            updated_values["base_fee_per_gas"] = DEFAULT_BASE_FEE

        if fork.header_zero_difficulty_required(number, timestamp):
            updated_values["difficulty"] = 0
        elif self.difficulty is None and self.parent_difficulty is None:
            updated_values["difficulty"] = 0x20000

        if (
            fork.header_excess_blob_gas_required(number, timestamp)
            and self.excess_blob_gas is None
            and self.parent_excess_blob_gas is None
        ):
            updated_values["excess_blob_gas"] = 0

        if (
            fork.header_blob_gas_used_required(number, timestamp)
            and self.blob_gas_used is None
            and self.parent_blob_gas_used is None
        ):
            updated_values["blob_gas_used"] = 0

        if (
            fork.header_beacon_root_required(number, timestamp)
            and self.parent_beacon_block_root is None
        ):
            updated_values["parent_beacon_block_root"] = 0

        if fork.environment_verkle_conversion_starts():
            if self.verkle_conversion_ended:
                # Conversion is marked as completed if this is the genesis block, or we are
                # past the conversion end fork.
                updated_values["verkle_conversion_ended"] = (
                    number == 0 or fork.environment_verkle_conversion_completed()
                )

        return self.copy(**updated_values)

parent_hash: Hash | None cached property

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

set_fork_requirements(fork)

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

Source code in src/ethereum_test_types/types.py
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
def set_fork_requirements(self, fork: Fork) -> "Environment":
    """
    Fills the required fields in an environment depending on the fork.
    """
    number = self.number
    timestamp = self.timestamp

    updated_values: Dict[str, Any] = {}

    if (
        fork.header_prev_randao_required(number, timestamp)
        and self.prev_randao is None
    ):
        updated_values["prev_randao"] = 0

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

    if (
        fork.header_base_fee_required(number, timestamp)
        and self.base_fee_per_gas is None
        and self.parent_base_fee_per_gas is None
    ):
        updated_values["base_fee_per_gas"] = DEFAULT_BASE_FEE

    if fork.header_zero_difficulty_required(number, timestamp):
        updated_values["difficulty"] = 0
    elif self.difficulty is None and self.parent_difficulty is None:
        updated_values["difficulty"] = 0x20000

    if (
        fork.header_excess_blob_gas_required(number, timestamp)
        and self.excess_blob_gas is None
        and self.parent_excess_blob_gas is None
    ):
        updated_values["excess_blob_gas"] = 0

    if (
        fork.header_blob_gas_used_required(number, timestamp)
        and self.blob_gas_used is None
        and self.parent_blob_gas_used is None
    ):
        updated_values["blob_gas_used"] = 0

    if (
        fork.header_beacon_root_required(number, timestamp)
        and self.parent_beacon_block_root is None
    ):
        updated_values["parent_beacon_block_root"] = 0

    if fork.environment_verkle_conversion_starts():
        if self.verkle_conversion_ended:
            # Conversion is marked as completed if this is the genesis block, or we are
            # past the conversion end fork.
            updated_values["verkle_conversion_ended"] = (
                number == 0 or fork.environment_verkle_conversion_completed()
            )

    return self.copy(**updated_values)

Removable

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

Source code in src/ethereum_test_types/types.py
72
73
74
75
76
77
78
class Removable:
    """
    Sentinel class to detect if a parameter should be removed.
    (`None` normally means "do not modify")
    """

    pass

Requests

Bases: RootModel[List[DepositRequest | WithdrawalRequest | ConsolidationRequest]]

Requests for the transition tool.

Source code in src/ethereum_test_types/types.py
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
class Requests(
    RootModel[List[DepositRequest | WithdrawalRequest | ConsolidationRequest]]
):
    """
    Requests for the transition tool.
    """

    root: List[DepositRequest | WithdrawalRequest | ConsolidationRequest] = Field(
        default_factory=list
    )

    def to_serializable_list(self) -> List[Any]:
        """
        Returns the requests as a list of serializable elements.
        """
        return [
            r.type_byte() + eth_rlp.encode(r.to_serializable_list()) for r in self.root
        ]

    @cached_property
    def trie_root(self) -> Hash:
        """
        Returns the root hash of the requests.
        """
        t = HexaryTrie(db={})
        for i, r in enumerate(self.root):
            t.set(
                eth_rlp.encode(Uint(i)),
                r.type_byte() + eth_rlp.encode(r.to_serializable_list()),
            )
        return Hash(t.root_hash)

    def deposit_requests(self) -> List[DepositRequest]:
        """
        Returns the list of deposit requests.
        """
        return [d for d in self.root if isinstance(d, DepositRequest)]

    def withdrawal_requests(self) -> List[WithdrawalRequest]:
        """
        Returns the list of withdrawal requests.
        """
        return [w for w in self.root if isinstance(w, WithdrawalRequest)]

    def consolidation_requests(self) -> List[ConsolidationRequest]:
        """
        Returns the list of consolidation requests.
        """
        return [c for c in self.root if isinstance(c, ConsolidationRequest)]

to_serializable_list()

Returns the requests as a list of serializable elements.

Source code in src/ethereum_test_types/types.py
1346
1347
1348
1349
1350
1351
1352
def to_serializable_list(self) -> List[Any]:
    """
    Returns the requests as a list of serializable elements.
    """
    return [
        r.type_byte() + eth_rlp.encode(r.to_serializable_list()) for r in self.root
    ]

trie_root: Hash cached property

Returns the root hash of the requests.

deposit_requests()

Returns the list of deposit requests.

Source code in src/ethereum_test_types/types.py
1367
1368
1369
1370
1371
def deposit_requests(self) -> List[DepositRequest]:
    """
    Returns the list of deposit requests.
    """
    return [d for d in self.root if isinstance(d, DepositRequest)]

withdrawal_requests()

Returns the list of withdrawal requests.

Source code in src/ethereum_test_types/types.py
1373
1374
1375
1376
1377
def withdrawal_requests(self) -> List[WithdrawalRequest]:
    """
    Returns the list of withdrawal requests.
    """
    return [w for w in self.root if isinstance(w, WithdrawalRequest)]

consolidation_requests()

Returns the list of consolidation requests.

Source code in src/ethereum_test_types/types.py
1379
1380
1381
1382
1383
def consolidation_requests(self) -> List[ConsolidationRequest]:
    """
    Returns the list of consolidation requests.
    """
    return [c for c in self.root if isinstance(c, ConsolidationRequest)]

Storage

Bases: RootModel[Dict[StorageKeyValueType, StorageKeyValueType]]

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

Source code in src/ethereum_test_base_types/composite_types.py
 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
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
class Storage(RootModel[Dict[StorageKeyValueType, StorageKeyValueType]]):
    """
    Definition of a storage in pre or post state of a test
    """

    root: Dict[StorageKeyValueType, StorageKeyValueType] = Field(default_factory=dict)

    _current_slot: int = PrivateAttr(0)

    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 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(Hash(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"""
            label_str = ""
            if self.address.label is not None:
                label_str = f" ({self.address.label})"
            return (
                f"incorrect value in address {self.address}{label_str} for "
                + f"key {Hash(self.key)}:"
                + f" want {HexNumber(self.want)} (dec:{int(self.want)}),"
                + f" got {HexNumber(self.got)} (dec:{int(self.got)})"
            )

    def __contains__(self, key: StorageKeyValueTypeConvertible | StorageKeyValueType) -> bool:
        """Checks for an item in the storage"""
        return StorageKeyValueTypeAdapter.validate_python(key) in self.root

    def __getitem__(
        self, key: StorageKeyValueTypeConvertible | StorageKeyValueType
    ) -> StorageKeyValueType:
        """Returns an item from the storage"""
        return self.root[StorageKeyValueTypeAdapter.validate_python(key)]

    def __setitem__(
        self,
        key: StorageKeyValueTypeConvertible | StorageKeyValueType,
        value: StorageKeyValueTypeConvertible | StorageKeyValueType,
    ):  # noqa: SC200
        """Sets an item in the storage"""
        self.root[
            StorageKeyValueTypeAdapter.validate_python(key)
        ] = StorageKeyValueTypeAdapter.validate_python(value)

    def __delitem__(self, key: StorageKeyValueTypeConvertible | StorageKeyValueType):
        """Deletes an item from the storage"""
        del self.root[StorageKeyValueTypeAdapter.validate_python(key)]

    def __iter__(self):
        """Returns an iterator over the storage"""
        return iter(self.root)

    def __eq__(self, other) -> bool:
        """
        Returns True if both storages are equal.
        """
        if not isinstance(other, Storage):
            return False
        return self.root == other.root

    def __ne__(self, other) -> bool:
        """
        Returns True if both storages are not equal.
        """
        if not isinstance(other, Storage):
            return False
        return self.root != other.root

    def __bool__(self) -> bool:
        """Returns True if the storage is not empty"""
        return any(v for v in self.root.values())

    def __add__(self, other: "Storage") -> "Storage":
        """
        Returns a new storage that is the sum of two storages.
        """
        return Storage({**self.root, **other.root})

    def keys(self) -> set[StorageKeyValueType]:
        """Returns the keys of the storage"""
        return set(self.root.keys())

    def set_next_slot(self, slot: int) -> "Storage":
        """
        Sets the next slot to be used by `store_next`.
        """
        self._current_slot = slot
        return self

    def items(self):
        """Returns the items of the storage"""
        return self.root.items()

    def store_next(
        self, value: StorageKeyValueTypeConvertible | StorageKeyValueType | bool
    ) -> StorageKeyValueType:
        """
        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.
        """
        slot = StorageKeyValueTypeAdapter.validate_python(self._current_slot)
        self._current_slot += 1
        self[slot] = StorageKeyValueTypeAdapter.validate_python(value)
        return slot

    def peek_slot(self) -> int:
        """
        Peeks the next slot that will be used by `store_next`.
        """
        return self._current_slot

    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.keys():
            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.keys():
            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 | None"):
        """
        Succeeds only if "self" is equal to "other" storage.
        """
        # Test keys contained in both storage objects
        if other is None:
            other = Storage({})
        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])

    def canary(self) -> "Storage":
        """
        Returns a canary storage filled with non-zero values where the current storage expects
        zero values, to guarantee that the test overwrites the storage.
        """
        return Storage({key: HashInt(0xBA5E) for key in self.keys() if self[key] == 0})

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_base_types/composite_types.py
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
@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_base_types/composite_types.py
47
48
49
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_base_types/composite_types.py
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
@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_base_types/composite_types.py
64
65
66
def __str__(self):
    """Print exception string"""
    return f"invalid value for key/value: {self.key_or_value}"

MissingKey dataclass

Bases: Exception

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

Source code in src/ethereum_test_base_types/composite_types.py
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
@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(Hash(self.key))

__str__()

Print exception string

Source code in src/ethereum_test_base_types/composite_types.py
80
81
82
def __str__(self):
    """Print exception string"""
    return "key {0} not found in storage".format(Hash(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_base_types/composite_types.py
 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
@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"""
        label_str = ""
        if self.address.label is not None:
            label_str = f" ({self.address.label})"
        return (
            f"incorrect value in address {self.address}{label_str} for "
            + f"key {Hash(self.key)}:"
            + f" want {HexNumber(self.want)} (dec:{int(self.want)}),"
            + f" got {HexNumber(self.got)} (dec:{int(self.got)})"
        )

__str__()

Print exception string

Source code in src/ethereum_test_base_types/composite_types.py
103
104
105
106
107
108
109
110
111
112
113
def __str__(self):
    """Print exception string"""
    label_str = ""
    if self.address.label is not None:
        label_str = f" ({self.address.label})"
    return (
        f"incorrect value in address {self.address}{label_str} for "
        + f"key {Hash(self.key)}:"
        + f" want {HexNumber(self.want)} (dec:{int(self.want)}),"
        + f" got {HexNumber(self.got)} (dec:{int(self.got)})"
    )

__contains__(key)

Checks for an item in the storage

Source code in src/ethereum_test_base_types/composite_types.py
115
116
117
def __contains__(self, key: StorageKeyValueTypeConvertible | StorageKeyValueType) -> bool:
    """Checks for an item in the storage"""
    return StorageKeyValueTypeAdapter.validate_python(key) in self.root

__getitem__(key)

Returns an item from the storage

Source code in src/ethereum_test_base_types/composite_types.py
119
120
121
122
123
def __getitem__(
    self, key: StorageKeyValueTypeConvertible | StorageKeyValueType
) -> StorageKeyValueType:
    """Returns an item from the storage"""
    return self.root[StorageKeyValueTypeAdapter.validate_python(key)]

__setitem__(key, value)

Sets an item in the storage

Source code in src/ethereum_test_base_types/composite_types.py
125
126
127
128
129
130
131
132
133
def __setitem__(
    self,
    key: StorageKeyValueTypeConvertible | StorageKeyValueType,
    value: StorageKeyValueTypeConvertible | StorageKeyValueType,
):  # noqa: SC200
    """Sets an item in the storage"""
    self.root[
        StorageKeyValueTypeAdapter.validate_python(key)
    ] = StorageKeyValueTypeAdapter.validate_python(value)

__delitem__(key)

Deletes an item from the storage

Source code in src/ethereum_test_base_types/composite_types.py
135
136
137
def __delitem__(self, key: StorageKeyValueTypeConvertible | StorageKeyValueType):
    """Deletes an item from the storage"""
    del self.root[StorageKeyValueTypeAdapter.validate_python(key)]

__iter__()

Returns an iterator over the storage

Source code in src/ethereum_test_base_types/composite_types.py
139
140
141
def __iter__(self):
    """Returns an iterator over the storage"""
    return iter(self.root)

__eq__(other)

Returns True if both storages are equal.

Source code in src/ethereum_test_base_types/composite_types.py
143
144
145
146
147
148
149
def __eq__(self, other) -> bool:
    """
    Returns True if both storages are equal.
    """
    if not isinstance(other, Storage):
        return False
    return self.root == other.root

__ne__(other)

Returns True if both storages are not equal.

Source code in src/ethereum_test_base_types/composite_types.py
151
152
153
154
155
156
157
def __ne__(self, other) -> bool:
    """
    Returns True if both storages are not equal.
    """
    if not isinstance(other, Storage):
        return False
    return self.root != other.root

__bool__()

Returns True if the storage is not empty

Source code in src/ethereum_test_base_types/composite_types.py
159
160
161
def __bool__(self) -> bool:
    """Returns True if the storage is not empty"""
    return any(v for v in self.root.values())

__add__(other)

Returns a new storage that is the sum of two storages.

Source code in src/ethereum_test_base_types/composite_types.py
163
164
165
166
167
def __add__(self, other: "Storage") -> "Storage":
    """
    Returns a new storage that is the sum of two storages.
    """
    return Storage({**self.root, **other.root})

keys()

Returns the keys of the storage

Source code in src/ethereum_test_base_types/composite_types.py
169
170
171
def keys(self) -> set[StorageKeyValueType]:
    """Returns the keys of the storage"""
    return set(self.root.keys())

set_next_slot(slot)

Sets the next slot to be used by store_next.

Source code in src/ethereum_test_base_types/composite_types.py
173
174
175
176
177
178
def set_next_slot(self, slot: int) -> "Storage":
    """
    Sets the next slot to be used by `store_next`.
    """
    self._current_slot = slot
    return self

items()

Returns the items of the storage

Source code in src/ethereum_test_base_types/composite_types.py
180
181
182
def items(self):
    """Returns the items of the storage"""
    return self.root.items()

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_base_types/composite_types.py
184
185
186
187
188
189
190
191
192
193
194
195
196
def store_next(
    self, value: StorageKeyValueTypeConvertible | StorageKeyValueType | bool
) -> StorageKeyValueType:
    """
    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.
    """
    slot = StorageKeyValueTypeAdapter.validate_python(self._current_slot)
    self._current_slot += 1
    self[slot] = StorageKeyValueTypeAdapter.validate_python(value)
    return slot

peek_slot()

Peeks the next slot that will be used by store_next.

Source code in src/ethereum_test_base_types/composite_types.py
198
199
200
201
202
def peek_slot(self) -> int:
    """
    Peeks the next slot that will be used by `store_next`.
    """
    return self._current_slot

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_base_types/composite_types.py
204
205
206
207
208
209
210
211
212
213
214
215
216
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.keys():
        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_base_types/composite_types.py
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
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.keys():
        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_base_types/composite_types.py
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
def must_be_equal(self, address: Address, other: "Storage | None"):
    """
    Succeeds only if "self" is equal to "other" storage.
    """
    # Test keys contained in both storage objects
    if other is None:
        other = Storage({})
    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])

canary()

Returns a canary storage filled with non-zero values where the current storage expects zero values, to guarantee that the test overwrites the storage.

Source code in src/ethereum_test_base_types/composite_types.py
258
259
260
261
262
263
def canary(self) -> "Storage":
    """
    Returns a canary storage filled with non-zero values where the current storage expects
    zero values, to guarantee that the test overwrites the storage.
    """
    return Storage({key: HashInt(0xBA5E) for key in self.keys() if self[key] == 0})

Transaction

Bases: TransactionGeneric[HexNumber], TransactionTransitionToolConverter

Generic object that can represent all Ethereum transaction types.

Source code in src/ethereum_test_types/types.py
 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
class Transaction(TransactionGeneric[HexNumber], TransactionTransitionToolConverter):
    """
    Generic object that can represent all Ethereum transaction types.
    """

    gas_limit: HexNumber = Field(HexNumber(21_000), serialization_alias="gas")
    to: Address | None = Field(Address(0xAA))
    data: Bytes = Field(Bytes(b""), alias="input")

    authorization_list: List[AuthorizationTuple] | None = None

    secret_key: Hash | None = None
    error: List[TransactionException] | TransactionException | None = Field(
        None, exclude=True
    )

    protected: bool = Field(True, exclude=True)
    rlp_override: Bytes | None = Field(None, exclude=True)

    wrapped_blob_transaction: bool = Field(False, exclude=True)
    blobs: Sequence[Bytes] | None = Field(None, exclude=True)
    blob_kzg_commitments: Sequence[Bytes] | None = Field(None, exclude=True)
    blob_kzg_proofs: Sequence[Bytes] | None = Field(None, exclude=True)

    model_config = ConfigDict(validate_assignment=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 model_post_init(self, __context):
        """
        Ensures the transaction has no conflicting properties.
        """
        super().model_post_init(__context)

        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 "ty" not in self.model_fields_set:
            # Try to deduce transaction type from included fields
            if self.authorization_list is not None:
                self.ty = 4
            elif (
                self.max_fee_per_blob_gas is not None
                or self.blob_kzg_commitments is not None
            ):
                self.ty = 3
            elif (
                self.max_fee_per_gas is not None
                or self.max_priority_fee_per_gas is not None
            ):
                self.ty = 2
            elif self.access_list is not None:
                self.ty = 1
            else:
                self.ty = 0

        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:
            if self.sender is not None:
                self.secret_key = self.sender.key
            else:
                self.secret_key = Hash(TestPrivateKey)
                self.sender = EOA(address=TestAddress, key=self.secret_key, nonce=0)

        # Set default values for fields that are required for certain tx types
        if self.ty <= 1 and self.gas_price is None:
            self.gas_price = TransactionDefaults.gas_price
        if self.ty >= 1 and self.access_list is None:
            self.access_list = []
        if self.ty < 1:
            assert self.access_list is None, "access_list must be None"

        if self.ty >= 2 and self.max_fee_per_gas is None:
            self.max_fee_per_gas = TransactionDefaults.max_fee_per_gas
        if self.ty >= 2 and self.max_priority_fee_per_gas is None:
            self.max_priority_fee_per_gas = TransactionDefaults.max_priority_fee_per_gas
        if self.ty < 2:
            assert self.max_fee_per_gas is None, "max_fee_per_gas must be None"
            assert (
                self.max_priority_fee_per_gas is None
            ), "max_priority_fee_per_gas must be None"

        if self.ty == 3 and self.max_fee_per_blob_gas is None:
            self.max_fee_per_blob_gas = 1
        if self.ty != 3:
            assert (
                self.blob_versioned_hashes is None
            ), "blob_versioned_hashes must be None"
            assert (
                self.max_fee_per_blob_gas is None
            ), "max_fee_per_blob_gas must be None"

        if self.ty == 4 and self.authorization_list is None:
            self.authorization_list = []
        if self.ty != 4:
            assert self.authorization_list is None, "authorization_list must be None"

        if "nonce" not in self.model_fields_set and self.sender is not None:
            self.nonce = HexNumber(self.sender.get_nonce())

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

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

    def with_signature_and_sender(
        self, *, keep_secret_key: bool = False
    ) -> "Transaction":
        """
        Returns a signed version of the transaction using the private key.
        """
        updated_values: Dict[str, Any] = {}

        if self.v is not None:
            # Transaction already signed
            if self.sender is not None:
                return self

            public_key = PublicKey.from_signature_and_message(
                self.signature_bytes, self.signing_bytes.keccak256(), hasher=None
            )
            updated_values["sender"] = Address(
                keccak256(public_key.format(compressed=False)[1:])[32 - 20 :]
            )
            return self.copy(**updated_values)

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

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

        # Sign the bytes
        signature_bytes = PrivateKey(secret=self.secret_key).sign_recoverable(
            signing_hash, hasher=None
        )
        public_key = PublicKey.from_signature_and_message(
            signature_bytes, signing_hash, hasher=None
        )

        sender = keccak256(public_key.format(compressed=False)[1:])[32 - 20 :]
        updated_values["sender"] = Address(sender)

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

        updated_values["v"] = HexNumber(v)
        updated_values["r"] = HexNumber(r)
        updated_values["s"] = HexNumber(s)

        updated_values["secret_key"] = None

        updated_tx: "Transaction" = self.model_copy(update=updated_values)

        # Remove the secret key if requested
        if keep_secret_key:
            updated_tx.secret_key = self.secret_key
        return updated_tx

    @cached_property
    def signing_envelope(self) -> List[Any]:
        """
        Returns the list of values included in the envelope used for signing.
        """
        to = self.to if self.to else bytes()
        if self.ty == 4:
            # EIP-7702: https://eips.ethereum.org/EIPS/eip-7702
            if self.max_priority_fee_per_gas is None:
                raise ValueError(
                    f"max_priority_fee_per_gas must be set for type {self.ty} tx"
                )
            if self.max_fee_per_gas is None:
                raise ValueError(f"max_fee_per_gas must be set for type {self.ty} tx")
            if self.access_list is None:
                raise ValueError(f"access_list must be set for type {self.ty} tx")
            if self.authorization_list is None:
                raise ValueError(
                    f"authorization_tuples must be set for type {self.ty} 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),
                self.data,
                [a.to_list() for a in self.access_list],
                [a.to_list() for a in self.authorization_list],
            ]
        elif self.ty == 3:
            # EIP-4844: https://eips.ethereum.org/EIPS/eip-4844
            if self.max_priority_fee_per_gas is None:
                raise ValueError(
                    f"max_priority_fee_per_gas must be set for type {self.ty} tx"
                )
            if self.max_fee_per_gas is None:
                raise ValueError(f"max_fee_per_gas must be set for type {self.ty} tx")
            if self.max_fee_per_blob_gas is None:
                raise ValueError(
                    f"max_fee_per_blob_gas must be set for type {self.ty} tx"
                )
            if self.blob_versioned_hashes is None:
                raise ValueError(
                    f"blob_versioned_hashes must be set for type {self.ty} tx"
                )
            if self.access_list is None:
                raise ValueError(f"access_list must be set for type {self.ty} 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),
                self.data,
                [a.to_list() for a in self.access_list],
                Uint(self.max_fee_per_blob_gas),
                list(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(
                    f"max_priority_fee_per_gas must be set for type {self.ty} tx"
                )
            if self.max_fee_per_gas is None:
                raise ValueError(f"max_fee_per_gas must be set for type {self.ty} tx")
            if self.access_list is None:
                raise ValueError(f"access_list must be set for type {self.ty} 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),
                self.data,
                [a.to_list() for a in self.access_list],
            ]
        elif self.ty == 1:
            # EIP-2930: https://eips.ethereum.org/EIPS/eip-2930
            if self.gas_price is None:
                raise ValueError(f"gas_price must be set for type {self.ty} tx")
            if self.access_list is None:
                raise ValueError(f"access_list must be set for type {self.ty} tx")

            return [
                Uint(self.chain_id),
                Uint(self.nonce),
                Uint(self.gas_price),
                Uint(self.gas_limit),
                to,
                Uint(self.value),
                self.data,
                [a.to_list() for a in self.access_list],
            ]
        elif self.ty == 0:
            if self.gas_price is None:
                raise ValueError(f"gas_price must be set for type {self.ty} 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),
                    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),
                    self.data,
                ]
        raise NotImplementedError(
            "signing for transaction type {self.ty} not implemented"
        )

    @cached_property
    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")

        signing_envelope = self.signing_envelope

        if self.ty == 0 and self.protected:
            # Remove the chain_id and the two zeros from the signing envelope
            signing_envelope = signing_envelope[:-3]
        elif self.ty == 3 and self.wrapped_blob_transaction:
            # EIP-4844: https://eips.ethereum.org/EIPS/eip-4844
            if self.blobs is None:
                raise ValueError(f"blobs must be set for type {self.ty} tx")
            if self.blob_kzg_commitments is None:
                raise ValueError(
                    f"blob_kzg_commitments must be set for type {self.ty} tx"
                )
            if self.blob_kzg_proofs is None:
                raise ValueError(f"blob_kzg_proofs must be set for type {self.ty} tx")
            return [
                signing_envelope + [Uint(self.v), Uint(self.r), Uint(self.s)],
                list(self.blobs),
                list(self.blob_kzg_commitments),
                list(self.blob_kzg_proofs),
            ]

        return signing_envelope + [Uint(self.v), Uint(self.r), Uint(self.s)]

    @cached_property
    def rlp(self) -> Bytes:
        """
        Returns bytes of the serialized representation of the transaction,
        which is almost always RLP encoding.
        """
        if self.rlp_override is not None:
            return self.rlp_override
        if self.ty > 0:
            return Bytes(bytes([self.ty]) + eth_rlp.encode(self.payload_body))
        else:
            return Bytes(eth_rlp.encode(self.payload_body))

    @cached_property
    def hash(self) -> Hash:
        """
        Returns hash of the transaction.
        """
        return self.rlp.keccak256()

    @cached_property
    def signing_bytes(self) -> Bytes:
        """
        Returns the serialized bytes of the transaction used for signing.
        """
        return Bytes(
            bytes([self.ty]) + eth_rlp.encode(self.signing_envelope)
            if self.ty > 0
            else eth_rlp.encode(self.signing_envelope)
        )

    @cached_property
    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 = int(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 Bytes(
            self.r.to_bytes(32, byteorder="big")
            + self.s.to_bytes(32, byteorder="big")
            + bytes([v])
        )

    @cached_property
    def serializable_list(self) -> Any:
        """
        Returns the list of values included in the transaction as a serializable object.
        """
        return self.rlp if self.ty > 0 else self.payload_body

    @staticmethod
    def list_root(input_txs: List["Transaction"]) -> Hash:
        """
        Returns the transactions root of a list of transactions.
        """
        t = HexaryTrie(db={})
        for i, tx in enumerate(input_txs):
            t.set(eth_rlp.encode(Uint(i)), tx.rlp)
        return Hash(t.root_hash)

    @staticmethod
    def list_blob_versioned_hashes(input_txs: List["Transaction"]) -> List[Hash]:
        """
        Gets a list of ordered blob versioned hashes from a list of transactions.
        """
        return [
            blob_versioned_hash
            for tx in input_txs
            if tx.blob_versioned_hashes is not None
            for blob_versioned_hash in tx.blob_versioned_hashes
        ]

    @cached_property
    def created_contract(self) -> Address:
        """
        Returns the address of the contract created by the transaction.
        """
        if self.to is not None:
            raise ValueError("transaction is not a contract creation")
        if self.sender is None:
            raise ValueError("sender address is None")
        hash = Bytes(
            eth_rlp.encode([self.sender, int_to_bytes(self.nonce)])
        ).keccak256()
        return Address(hash[-20:])

InvalidFeePayment

Bases: Exception

Transaction described more than one fee payment type.

Source code in src/ethereum_test_types/types.py
773
774
775
776
777
778
779
780
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_types/types.py
778
779
780
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_types/types.py
782
783
784
785
786
787
788
789
790
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_types/types.py
788
789
790
def __str__(self):
    """Print exception string"""
    return "can't define both 'signature' and 'private_key'"

model_post_init(__context)

Ensures the transaction has no conflicting properties.

Source code in src/ethereum_test_types/types.py
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
def model_post_init(self, __context):
    """
    Ensures the transaction has no conflicting properties.
    """
    super().model_post_init(__context)

    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 "ty" not in self.model_fields_set:
        # Try to deduce transaction type from included fields
        if self.authorization_list is not None:
            self.ty = 4
        elif (
            self.max_fee_per_blob_gas is not None
            or self.blob_kzg_commitments is not None
        ):
            self.ty = 3
        elif (
            self.max_fee_per_gas is not None
            or self.max_priority_fee_per_gas is not None
        ):
            self.ty = 2
        elif self.access_list is not None:
            self.ty = 1
        else:
            self.ty = 0

    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:
        if self.sender is not None:
            self.secret_key = self.sender.key
        else:
            self.secret_key = Hash(TestPrivateKey)
            self.sender = EOA(address=TestAddress, key=self.secret_key, nonce=0)

    # Set default values for fields that are required for certain tx types
    if self.ty <= 1 and self.gas_price is None:
        self.gas_price = TransactionDefaults.gas_price
    if self.ty >= 1 and self.access_list is None:
        self.access_list = []
    if self.ty < 1:
        assert self.access_list is None, "access_list must be None"

    if self.ty >= 2 and self.max_fee_per_gas is None:
        self.max_fee_per_gas = TransactionDefaults.max_fee_per_gas
    if self.ty >= 2 and self.max_priority_fee_per_gas is None:
        self.max_priority_fee_per_gas = TransactionDefaults.max_priority_fee_per_gas
    if self.ty < 2:
        assert self.max_fee_per_gas is None, "max_fee_per_gas must be None"
        assert (
            self.max_priority_fee_per_gas is None
        ), "max_priority_fee_per_gas must be None"

    if self.ty == 3 and self.max_fee_per_blob_gas is None:
        self.max_fee_per_blob_gas = 1
    if self.ty != 3:
        assert (
            self.blob_versioned_hashes is None
        ), "blob_versioned_hashes must be None"
        assert (
            self.max_fee_per_blob_gas is None
        ), "max_fee_per_blob_gas must be None"

    if self.ty == 4 and self.authorization_list is None:
        self.authorization_list = []
    if self.ty != 4:
        assert self.authorization_list is None, "authorization_list must be None"

    if "nonce" not in self.model_fields_set and self.sender is not None:
        self.nonce = HexNumber(self.sender.get_nonce())

with_error(error)

Create a copy of the transaction with an added error.

Source code in src/ethereum_test_types/types.py
870
871
872
873
874
875
876
def with_error(
    self, error: List[TransactionException] | TransactionException
) -> "Transaction":
    """
    Create a copy of the transaction with an added error.
    """
    return self.copy(error=error)

with_nonce(nonce)

Create a copy of the transaction with a modified nonce.

Source code in src/ethereum_test_types/types.py
878
879
880
881
882
def with_nonce(self, nonce: int) -> "Transaction":
    """
    Create a copy of the transaction with a modified nonce.
    """
    return self.copy(nonce=nonce)

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_types/types.py
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
def with_signature_and_sender(
    self, *, keep_secret_key: bool = False
) -> "Transaction":
    """
    Returns a signed version of the transaction using the private key.
    """
    updated_values: Dict[str, Any] = {}

    if self.v is not None:
        # Transaction already signed
        if self.sender is not None:
            return self

        public_key = PublicKey.from_signature_and_message(
            self.signature_bytes, self.signing_bytes.keccak256(), hasher=None
        )
        updated_values["sender"] = Address(
            keccak256(public_key.format(compressed=False)[1:])[32 - 20 :]
        )
        return self.copy(**updated_values)

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

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

    # Sign the bytes
    signature_bytes = PrivateKey(secret=self.secret_key).sign_recoverable(
        signing_hash, hasher=None
    )
    public_key = PublicKey.from_signature_and_message(
        signature_bytes, signing_hash, hasher=None
    )

    sender = keccak256(public_key.format(compressed=False)[1:])[32 - 20 :]
    updated_values["sender"] = Address(sender)

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

    updated_values["v"] = HexNumber(v)
    updated_values["r"] = HexNumber(r)
    updated_values["s"] = HexNumber(s)

    updated_values["secret_key"] = None

    updated_tx: "Transaction" = self.model_copy(update=updated_values)

    # Remove the secret key if requested
    if keep_secret_key:
        updated_tx.secret_key = self.secret_key
    return updated_tx

signing_envelope: List[Any] cached property

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

payload_body: List[Any] cached property

Returns the list of values included in the transaction body.

rlp: Bytes cached property

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

hash: Hash cached property

Returns hash of the transaction.

signing_bytes: Bytes cached property

Returns the serialized bytes of the transaction used for signing.

signature_bytes: Bytes cached property

Returns the serialized bytes of the transaction signature.

serializable_list: Any cached property

Returns the list of values included in the transaction as a serializable object.

list_root(input_txs) staticmethod

Returns the transactions root of a list of transactions.

Source code in src/ethereum_test_types/types.py
1166
1167
1168
1169
1170
1171
1172
1173
1174
@staticmethod
def list_root(input_txs: List["Transaction"]) -> Hash:
    """
    Returns the transactions root of a list of transactions.
    """
    t = HexaryTrie(db={})
    for i, tx in enumerate(input_txs):
        t.set(eth_rlp.encode(Uint(i)), tx.rlp)
    return Hash(t.root_hash)

list_blob_versioned_hashes(input_txs) staticmethod

Gets a list of ordered blob versioned hashes from a list of transactions.

Source code in src/ethereum_test_types/types.py
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
@staticmethod
def list_blob_versioned_hashes(input_txs: List["Transaction"]) -> List[Hash]:
    """
    Gets a list of ordered blob versioned hashes from a list of transactions.
    """
    return [
        blob_versioned_hash
        for tx in input_txs
        if tx.blob_versioned_hashes is not None
        for blob_versioned_hash in tx.blob_versioned_hashes
    ]

created_contract: Address cached property

Returns the address of the contract created by the transaction.

TransactionDefaults dataclass

Default values for transactions.

Source code in src/ethereum_test_types/types.py
652
653
654
655
656
657
658
659
660
661
@dataclass
class TransactionDefaults:
    """
    Default values for transactions.
    """

    chain_id: int = 1
    gas_price = 10
    max_fee_per_gas = 7
    max_priority_fee_per_gas: int = 0

Withdrawal

Bases: WithdrawalGeneric[HexNumber]

Withdrawal type

Source code in src/ethereum_test_types/types.py
374
375
376
377
378
379
class Withdrawal(WithdrawalGeneric[HexNumber]):
    """
    Withdrawal type
    """

    pass

WithdrawalRequest

Bases: WithdrawalRequestGeneric[HexNumber]

Withdrawal Request type

Source code in src/ethereum_test_types/types.py
1291
1292
1293
1294
1295
1296
class WithdrawalRequest(WithdrawalRequestGeneric[HexNumber]):
    """
    Withdrawal Request type
    """

    pass

keccak256(data)

Calculates the keccak256 hash of the given data.

Source code in src/ethereum_test_types/types.py
54
55
56
57
58
def keccak256(data: bytes) -> Hash:
    """
    Calculates the keccak256 hash of the given data.
    """
    return Bytes(data).keccak256()

VerkleTree

Bases: RootModel[Dict[Hash, Hash]]

Definition of a Verkle Tree.

A Verkle Tree is a data structure used to efficiently prove the membership or non-membership of elements in a state. This class represents the Verkle Tree as a dictionary, where each key and value is a Hash (32 bytes). The root attribute holds this dictionary, providing a mapping of the tree's key/values.

Source code in src/ethereum_test_types/verkle/types.py
144
145
146
147
148
149
150
151
152
153
154
class VerkleTree(RootModel[Dict[Hash, Hash]]):
    """
    Definition of a Verkle Tree.

    A Verkle Tree is a data structure used to efficiently prove the membership or non-membership
    of elements in a state. This class represents the Verkle Tree as a dictionary, where each key
    and value is a Hash (32 bytes). The root attribute holds this dictionary, providing a mapping
    of the tree's key/values.
    """

    root: Dict[Hash, Hash] = Field(default_factory=dict)

Witness

Bases: CamelModel

Definition of an Execution Witness.

Contains all the necessary data to verify the correctness of a blockchain state transition. This includes the state differences indicating changes in the Verkle tree, the Verkle proof for proving element membership or non-membership, and the parent state root which provides the root hash of the state tree before the current block execution.

Source code in src/ethereum_test_types/verkle/types.py
129
130
131
132
133
134
135
136
137
138
139
140
class Witness(CamelModel):
    """
    Definition of an Execution Witness.

    Contains all the necessary data to verify the correctness of a blockchain state transition.
    This includes the state differences indicating changes in the Verkle tree, the Verkle proof for
    proving element membership or non-membership, and the parent state root which provides the root
    hash of the state tree before the current block execution.
    """

    state_diff: StateDiff
    verkle_proof: VerkleProof

WitnessCheck

Definition of a Witness Check.

Used as an intermediary class to store all the necessary items required to check during the filling process of a blockchain test.

Source code in src/ethereum_test_types/verkle/types.py
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
class WitnessCheck:
    """
    Definition of a Witness Check.

    Used as an intermediary class to store all the necessary items required to check
    during the filling process of a blockchain test.
    """

    version: int = 0

    class AccountHeaderEntry(Enum):
        """
        Represents all the data entries in an account header.
        """

        BASIC_DATA = 0
        CODEHASH = 1

    def __init__(self, fork: Fork) -> None:
        """
        Initializes a WitnessCheck instance.
        """
        assert fork >= Verkle, "WitnessCheck is only supported for Verkle fork and later"
        self.account_entries: List[
            Tuple[Address, WitnessCheck.AccountHeaderEntry, Optional[Hash]]
        ] = []
        self.storage_slots: List[Tuple[Address, int, Optional[Hash]]] = []
        self.code_chunks: List[Tuple[Address, int, Optional[Hash]]] = []

        # Add the pre-allocation accounts by default
        pre_allocations = fork.pre_allocation_blockchain()
        for address, account_data in pre_allocations.items():
            self.add_account_full(Address(address), Account(**account_data))

    def __repr__(self) -> str:
        """
        Provides a detailed string representation of the WitnessCheck object for debugging.
        """
        return (
            f"WitnessCheck(\n"
            f"  account_entries={self.account_entries},\n"
            f"  storage_slots={self.storage_slots},\n"
            f"  code_chunks={self.code_chunks}\n"
            f")"
        )

    def add_account_full(self, address: Address, account: Account | None) -> None:
        """
        Adds the address, nonce, balance, and code. Delays actual key computation until later.
        """
        self.add_account_basic_data(address, account)
        if account:
            if account.code:
                code_hash = Hash(keccak256(account.code))
            else:  # keccak256 of empty byte array
                code_hash = Hash(
                    0xC5D2460186F7233C927E7DB2DCC703C0E500B653CA82273B7BFAD8045D85A470
                )
            self.add_account_codehash(address, code_hash)
        else:
            self.add_account_codehash(address, None)

    def add_account_basic_data(self, address: Address, account: Account | None) -> None:
        """
        Adds the basic data witness for the given address.
        """
        if account is None:
            self.account_entries.append(
                (address, WitnessCheck.AccountHeaderEntry.BASIC_DATA, None)
            )
        else:  # Use big-endian encoding for basic data items
            basic_data_value = bytearray(32)

            # Set version to 0 (1 byte at offset 0)
            basic_data_value[0] = self.version

            # Bytes 1..4 are reserved for future use, leave them as 0

            # Set code_size (3 bytes at offset 5)
            code_size_bytes = len(account.code).to_bytes(3, byteorder="big")
            basic_data_value[5:8] = code_size_bytes

            # Set nonce (8 bytes at offset 8)
            nonce_bytes = account.nonce.to_bytes(8, byteorder="big")
            basic_data_value[8:16] = nonce_bytes

            # Set balance (16 bytes at offset 16) - encode as big-endian
            balance_bytes = account.balance.to_bytes(16, byteorder="big")
            basic_data_value[16:32] = balance_bytes

            # Append the encoded basic data to account_entries
            self.account_entries.append(
                (
                    address,
                    WitnessCheck.AccountHeaderEntry.BASIC_DATA,
                    Hash(bytes(basic_data_value)),
                )
            )

    def add_account_codehash(self, address: Address, codehash: Optional[Hash]) -> None:
        """
        Adds the code hash witness for the given address.
        """
        self.account_entries.append((address, WitnessCheck.AccountHeaderEntry.CODEHASH, codehash))

    def add_storage_slot(self, address: Address, storage_slot: int, value: Optional[Hash]) -> None:
        """
        Adds the storage slot witness for the given address and storage slot.
        """
        self.storage_slots.append((address, storage_slot, value))

    def add_code_chunk(self, address: Address, chunk_number: int, value: Optional[Hash]) -> None:
        """
        Adds the code chunk witness for the given address and chunk number.
        """
        self.code_chunks.append((address, chunk_number, value))

AccountHeaderEntry

Bases: Enum

Represents all the data entries in an account header.

Source code in src/ethereum_test_types/verkle/types.py
167
168
169
170
171
172
173
class AccountHeaderEntry(Enum):
    """
    Represents all the data entries in an account header.
    """

    BASIC_DATA = 0
    CODEHASH = 1

__init__(fork)

Initializes a WitnessCheck instance.

Source code in src/ethereum_test_types/verkle/types.py
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
def __init__(self, fork: Fork) -> None:
    """
    Initializes a WitnessCheck instance.
    """
    assert fork >= Verkle, "WitnessCheck is only supported for Verkle fork and later"
    self.account_entries: List[
        Tuple[Address, WitnessCheck.AccountHeaderEntry, Optional[Hash]]
    ] = []
    self.storage_slots: List[Tuple[Address, int, Optional[Hash]]] = []
    self.code_chunks: List[Tuple[Address, int, Optional[Hash]]] = []

    # Add the pre-allocation accounts by default
    pre_allocations = fork.pre_allocation_blockchain()
    for address, account_data in pre_allocations.items():
        self.add_account_full(Address(address), Account(**account_data))

__repr__()

Provides a detailed string representation of the WitnessCheck object for debugging.

Source code in src/ethereum_test_types/verkle/types.py
191
192
193
194
195
196
197
198
199
200
201
def __repr__(self) -> str:
    """
    Provides a detailed string representation of the WitnessCheck object for debugging.
    """
    return (
        f"WitnessCheck(\n"
        f"  account_entries={self.account_entries},\n"
        f"  storage_slots={self.storage_slots},\n"
        f"  code_chunks={self.code_chunks}\n"
        f")"
    )

add_account_full(address, account)

Adds the address, nonce, balance, and code. Delays actual key computation until later.

Source code in src/ethereum_test_types/verkle/types.py
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
def add_account_full(self, address: Address, account: Account | None) -> None:
    """
    Adds the address, nonce, balance, and code. Delays actual key computation until later.
    """
    self.add_account_basic_data(address, account)
    if account:
        if account.code:
            code_hash = Hash(keccak256(account.code))
        else:  # keccak256 of empty byte array
            code_hash = Hash(
                0xC5D2460186F7233C927E7DB2DCC703C0E500B653CA82273B7BFAD8045D85A470
            )
        self.add_account_codehash(address, code_hash)
    else:
        self.add_account_codehash(address, None)

add_account_basic_data(address, account)

Adds the basic data witness for the given address.

Source code in src/ethereum_test_types/verkle/types.py
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
def add_account_basic_data(self, address: Address, account: Account | None) -> None:
    """
    Adds the basic data witness for the given address.
    """
    if account is None:
        self.account_entries.append(
            (address, WitnessCheck.AccountHeaderEntry.BASIC_DATA, None)
        )
    else:  # Use big-endian encoding for basic data items
        basic_data_value = bytearray(32)

        # Set version to 0 (1 byte at offset 0)
        basic_data_value[0] = self.version

        # Bytes 1..4 are reserved for future use, leave them as 0

        # Set code_size (3 bytes at offset 5)
        code_size_bytes = len(account.code).to_bytes(3, byteorder="big")
        basic_data_value[5:8] = code_size_bytes

        # Set nonce (8 bytes at offset 8)
        nonce_bytes = account.nonce.to_bytes(8, byteorder="big")
        basic_data_value[8:16] = nonce_bytes

        # Set balance (16 bytes at offset 16) - encode as big-endian
        balance_bytes = account.balance.to_bytes(16, byteorder="big")
        basic_data_value[16:32] = balance_bytes

        # Append the encoded basic data to account_entries
        self.account_entries.append(
            (
                address,
                WitnessCheck.AccountHeaderEntry.BASIC_DATA,
                Hash(bytes(basic_data_value)),
            )
        )

add_account_codehash(address, codehash)

Adds the code hash witness for the given address.

Source code in src/ethereum_test_types/verkle/types.py
256
257
258
259
260
def add_account_codehash(self, address: Address, codehash: Optional[Hash]) -> None:
    """
    Adds the code hash witness for the given address.
    """
    self.account_entries.append((address, WitnessCheck.AccountHeaderEntry.CODEHASH, codehash))

add_storage_slot(address, storage_slot, value)

Adds the storage slot witness for the given address and storage slot.

Source code in src/ethereum_test_types/verkle/types.py
262
263
264
265
266
def add_storage_slot(self, address: Address, storage_slot: int, value: Optional[Hash]) -> None:
    """
    Adds the storage slot witness for the given address and storage slot.
    """
    self.storage_slots.append((address, storage_slot, value))

add_code_chunk(address, chunk_number, value)

Adds the code chunk witness for the given address and chunk number.

Source code in src/ethereum_test_types/verkle/types.py
268
269
270
271
272
def add_code_chunk(self, address: Address, chunk_number: int, value: Optional[Hash]) -> None:
    """
    Adds the code chunk witness for the given address and chunk number.
    """
    self.code_chunks.append((address, chunk_number, value))