ethereum.forks.bpo5.transactionsethereum.forks.amsterdam.transactions

Transactions are atomic units of work created externally to Ethereum and submitted to be executed. If Ethereum is viewed as a state machine, transactions are the events that move between states.

IntrinsicGasCost

Intrinsic gas costs for a transaction, split by gas type.

41
@final
42
@dataclass
class IntrinsicGasCost:

regular

Regular execution gas (calldata, base cost, access list, etc.).

39
    regular: Uint

execution

Execution gas (calldata, base cost, access list, etc.).

46
    execution: ExecutionGas

calldata_floor

Minimum gas cost based on calldata size per EIP-7623, including the access list data surcharge per EIP-7981.

42
    calldata_floor: Uint
49
    calldata_floor: ExecutionGas

BLOB_COUNT_LIMIT

Maximum number of blobs a single transaction may carry.

59
BLOB_COUNT_LIMIT = 6

VERSIONED_HASH_VERSION_KZG

Version byte that every blob versioned hash must start with.

64
VERSIONED_HASH_VERSION_KZG = b"\x01"

ACCESS_LIST_ADDRESS_FLOOR_TOKENS

Floor data tokens contributed by a single access list address per EIP-7981.

69
ACCESS_LIST_ADDRESS_FLOOR_TOKENS = Uint(80)

ACCESS_LIST_STORAGE_KEY_FLOOR_TOKENS

Floor data tokens contributed by a single access list storage key per EIP-7981.

77
ACCESS_LIST_STORAGE_KEY_FLOOR_TOKENS = Uint(128)

LegacyTransaction

Atomic operation performed on the block chain. This represents the original transaction format used before EIP-1559, EIP-2930, EIP-4844, and EIP-7702.

86
@final
87
@slotted_freezable
88
@dataclass
class LegacyTransaction:

nonce

A scalar value equal to the number of transactions sent by the sender.

101
    nonce: U256

gas_price

The price of gas for this transaction, in wei.

106
    gas_price: Uint

gas

The maximum amount of gas that can be used by this transaction.

111
    gas: Uint

to

The address of the recipient. If empty, the transaction is a contract creation.

116
    to: Bytes0 | Address

value

The amount of ether (in wei) to send with this transaction.

122
    value: U256

data

The data payload of the transaction, which can be used to call functions on contracts or to create new contracts.

127
    data: Bytes

v

The recovery id of the signature.

133
    v: U256

r

The first part of the signature.

138
    r: U256

s

The second part of the signature.

143
    s: U256

Access

A mapping from account address to storage slots that are pre-warmed as part of a transaction.

149
@final
150
@slotted_freezable
151
@dataclass
class Access:

account

The address of the account that is accessed.

158
    account: Address

slots

A tuple of storage slots that are accessed in the account.

163
    slots: Tuple[Bytes32, ...]

AccessListTransaction

The transaction type added in EIP-2930 to support access lists.

This transaction type extends the legacy transaction with an access list and chain ID. The access list specifies which addresses and storage slots the transaction will access.

169
@final
170
@slotted_freezable
171
@dataclass
class AccessListTransaction:

chain_id

The ID of the chain on which this transaction is executed.

183
    chain_id: U64

nonce

A scalar value equal to the number of transactions sent by the sender.

188
    nonce: U256

gas_price

The price of gas for this transaction.

193
    gas_price: Uint

gas

The maximum amount of gas that can be used by this transaction.

198
    gas: Uint

to

The address of the recipient. If empty, the transaction is a contract creation.

203
    to: Bytes0 | Address

value

The amount of ether (in wei) to send with this transaction.

209
    value: U256

data

The data payload of the transaction, which can be used to call functions on contracts or to create new contracts.

214
    data: Bytes

access_list

A tuple of Access objects that specify which addresses and storage slots are accessed in the transaction.

220
    access_list: Tuple[Access, ...]

y_parity

The recovery id of the signature.

226
    y_parity: U256

r

The first part of the signature.

231
    r: U256

s

The second part of the signature.

236
    s: U256

FeeMarketTransaction

The transaction type added in EIP-1559.

This transaction type introduces a new fee market mechanism with two gas price parameters: max_priority_fee_per_gas and max_fee_per_gas.

242
@final
243
@slotted_freezable
244
@dataclass
class FeeMarketTransaction:

chain_id

The ID of the chain on which this transaction is executed.

255
    chain_id: U64

nonce

A scalar value equal to the number of transactions sent by the sender.

260
    nonce: U256

max_priority_fee_per_gas

The maximum priority fee per gas that the sender is willing to pay.

265
    max_priority_fee_per_gas: Uint

max_fee_per_gas

The maximum fee per gas that the sender is willing to pay, including the base fee and priority fee.

270
    max_fee_per_gas: Uint

gas

The maximum amount of gas that can be used by this transaction.

276
    gas: Uint

to

The address of the recipient. If empty, the transaction is a contract creation.

281
    to: Bytes0 | Address

value

The amount of ether (in wei) to send with this transaction.

287
    value: U256

data

The data payload of the transaction, which can be used to call functions on contracts or to create new contracts.

292
    data: Bytes

access_list

A tuple of Access objects that specify which addresses and storage slots are accessed in the transaction.

298
    access_list: Tuple[Access, ...]

y_parity

The recovery id of the signature.

304
    y_parity: U256

r

The first part of the signature.

309
    r: U256

s

The second part of the signature.

314
    s: U256

BlobTransaction

The transaction type added in EIP-4844.

This transaction type extends the fee market transaction to support blob-carrying transactions.

320
@final
321
@slotted_freezable
322
@dataclass
class BlobTransaction:

chain_id

The ID of the chain on which this transaction is executed.

333
    chain_id: U64

nonce

A scalar value equal to the number of transactions sent by the sender.

338
    nonce: U256

max_priority_fee_per_gas

The maximum priority fee per gas that the sender is willing to pay.

343
    max_priority_fee_per_gas: Uint

max_fee_per_gas

The maximum fee per gas that the sender is willing to pay, including the base fee and priority fee.

348
    max_fee_per_gas: Uint

gas

The maximum amount of gas that can be used by this transaction.

354
    gas: Uint

to

The address of the recipient. If empty, the transaction is a contract creation.

359
    to: Address

value

The amount of ether (in wei) to send with this transaction.

365
    value: U256

data

The data payload of the transaction, which can be used to call functions on contracts or to create new contracts.

370
    data: Bytes

access_list

A tuple of Access objects that specify which addresses and storage slots are accessed in the transaction.

376
    access_list: Tuple[Access, ...]

max_fee_per_blob_gas

The maximum fee per blob gas that the sender is willing to pay.

382
    max_fee_per_blob_gas: U256

blob_versioned_hashes

A tuple of objects that represent the versioned hashes of the blobs included in the transaction.

387
    blob_versioned_hashes: Tuple[VersionedHash, ...]

y_parity

The recovery id of the signature.

393
    y_parity: U256

r

The first part of the signature.

398
    r: U256

s

The second part of the signature.

403
    s: U256

SetCodeTransaction

The transaction type added in EIP-7702.

This transaction type allows Ethereum Externally Owned Accounts (EOAs) to set code on their account, enabling them to act as smart contracts.

409
@final
410
@slotted_freezable
411
@dataclass
class SetCodeTransaction:

chain_id

The ID of the chain on which this transaction is executed.

422
    chain_id: U64

nonce

A scalar value equal to the number of transactions sent by the sender.

427
    nonce: U64

max_priority_fee_per_gas

The maximum priority fee per gas that the sender is willing to pay.

432
    max_priority_fee_per_gas: Uint

max_fee_per_gas

The maximum fee per gas that the sender is willing to pay, including the base fee and priority fee.

437
    max_fee_per_gas: Uint

gas

The maximum amount of gas that can be used by this transaction.

443
    gas: Uint

to

The address of the recipient. If empty, the transaction is a contract creation.

448
    to: Address

value

The amount of ether (in wei) to send with this transaction.

454
    value: U256

data

The data payload of the transaction, which can be used to call functions on contracts or to create new contracts.

459
    data: Bytes

access_list

A tuple of Access objects that specify which addresses and storage slots are accessed in the transaction.

465
    access_list: Tuple[Access, ...]

authorizations

A tuple of Authorization objects that specify what code the signer desires to execute in the context of their EOA.

471
    authorizations: Tuple[Authorization, ...]

y_parity

The recovery id of the signature.

477
    y_parity: U256

r

The first part of the signature.

482
    r: U256

s

The second part of the signature.

487
    s: U256

Transaction

Union type representing any valid transaction type.

493
Transaction = (
494
    LegacyTransaction
495
    | AccessListTransaction
496
    | FeeMarketTransaction
497
    | BlobTransaction
498
    | SetCodeTransaction
499
)

AccessListCapableTransaction

Transaction types that include an EIP-2930-style access list.

See has_access_list and Access for more details.

505
AccessListCapableTransaction = (
506
    AccessListTransaction
507
    | FeeMarketTransaction
508
    | BlobTransaction
509
    | SetCodeTransaction
510
)

FeeMarketCapableTransaction

Transaction types that include the EIP-1559-style fee structure.

See FeeMarketTransaction for more details.

522
FeeMarketCapableTransaction = (
523
    FeeMarketTransaction | BlobTransaction | SetCodeTransaction
524
)

encode_transaction

Encode a transaction into its RLP or typed transaction format. Needed because non-legacy transactions aren't RLP.

Legacy transactions are returned as-is, while other transaction types are prefixed with their type identifier and RLP encoded.

def encode_transaction(​tx: Transaction​) -> LegacyTransaction | Bytes:
536
    <snip>
543
    if isinstance(tx, LegacyTransaction):
544
        return tx
545
    elif isinstance(tx, AccessListTransaction):
546
        return b"\x01" + rlp.encode(tx)
547
    elif isinstance(tx, FeeMarketTransaction):
548
        return b"\x02" + rlp.encode(tx)
549
    elif isinstance(tx, BlobTransaction):
550
        return b"\x03" + rlp.encode(tx)
551
    elif isinstance(tx, SetCodeTransaction):
552
        return b"\x04" + rlp.encode(tx)
553
    else:
554
        raise Exception(f"Unable to encode transaction of type {type(tx)}")

decode_transaction

Decode a transaction from its RLP or typed transaction format. Needed because non-legacy transactions aren't RLP.

Legacy transactions are returned as-is, while other transaction typesAccept a LegacyTransaction object (returned as-is) or raw are decoded based on their type identifier prefix.bytes.

EIP-2718 states that the first byte distinguishes the format: [0x00, 0x7f] is a typed transaction, [0xc0, 0xfe] is a legacy transaction (RLP list prefix).

def decode_transaction(​tx: LegacyTransaction | Bytes​) -> Transaction:
558
    <snip>
569
    if isinstance(tx, Bytes):
570
        if len(tx) == 0:
571
            raise InvalidBlock("empty transaction")
572
        if tx[0] == 1:
573
            return rlp.decode_to(AccessListTransaction, tx[1:])
574
        elif tx[0] == 2:
575
            return rlp.decode_to(FeeMarketTransaction, tx[1:])
576
        elif tx[0] == 3:
577
            return rlp.decode_to(BlobTransaction, tx[1:])
578
        elif tx[0] == 4:
579
            return rlp.decode_to(SetCodeTransaction, tx[1:])
540
        else:
541
            raise TransactionTypeError(tx[0])
580
        elif 0xC0 <= tx[0] <= 0xFE:
581
            return rlp.decode_to(LegacyTransaction, tx)
582
        else:
583
            raise TransactionTypeError(tx[0])
584
    else:
585
        return tx

validate_transaction

Verifies a transaction.

The gas in a transaction gets used to pay for the intrinsic cost of operations, therefore if there is insufficient gas then it would not be possible to execute a transaction and it will be declared invalid.

Additionally, the nonce of a transaction must not equal or exceed the limit defined in EIP-2681. In practice, defining the limit as 2**64-1 has no impact because sending 2**64-1 transactions is improbable. It's not strictly impossible though, 2**64-1 transactions is the entire capacity of the Ethereum blockchain at 2022 gas limits for a little over 22 years.

Also, the code size of a contract creation transaction must be within limits of the protocol.

This function takes a transaction as a parameter and returns the intrinsicThe gas limit of a transaction may not exceed TX_MAX_TOTAL_GAS_LIMIT gas cost and the minimum calldata gas cost for the transaction after(EIP-8037). TX_MAX_GAS_LIMIT (EIP-7825) bounds only the validation. It throws an InsufficientTransactionGasError exception ifexecution-gas a transaction can spend, so it is checked against the larger the transaction does not provide enough gas to cover the intrinsic cost,of the intrinsic execution cost and the EIP-7623 calldata floor rather and a NonceOverflowError exception if the nonce is greater than 2**64 - 2. It also raises an InitCodeTooLargeError if the code size of a contract creation transaction exceeds the maximum allowed size, and a PriorityFeeGreaterThanMaxFeeError if the maximum priority fee per gas of a fee market transaction exceeds its maximum fee per gas.than against the gas limit.

This function takes a transaction and gas_limit as parameters and returns the intrinsic gas costs for the transaction after validation. It throws an InsufficientTransactionGasError exception if the transaction does not provide enough gas to cover the intrinsic cost, and a NonceOverflowError exception if the nonce overflows. It also raises an InitCodeTooLargeError if the code size of a contract creation transaction exceeds the maximum allowed size, a TransactionGasLimitExceededError if the gas limit exceeds TX_MAX_TOTAL_GAS_LIMIT, and a PriorityFeeGreaterThanMaxFeeError if the maximum priority fee per gas of a fee market transaction exceeds its maximum fee per gas.

def validate_transaction(​tx: Transaction, ​​sender: Address​) -> IntrinsicGasCost:
547
    <snip>
589
    <snip>  # noqa: E501
631
    from .vm.gas import GasCosts
632
    from .vm.interpreter import MAX_INIT_CODE_SIZE
633
580
    intrinsic = calculate_intrinsic_cost(tx)
581
    if max(intrinsic.regular, intrinsic.calldata_floor) > tx.gas:
582
        raise InsufficientTransactionGasError("Insufficient gas")
634
    if U256(tx.nonce) >= U256(U64.MAX_VALUE):
635
        raise NonceOverflowError("Nonce too high")
636
637
    if tx.to == Bytes0(b"") and len(tx.data) > MAX_INIT_CODE_SIZE:
638
        raise InitCodeTooLargeError("Code size too large")
585
    if tx.gas > GasCosts.TX_MAX_GAS_LIMIT:
639
640
    if tx.gas > GasCosts.TX_MAX_TOTAL_GAS_LIMIT:
641
        raise TransactionGasLimitExceededError("Gas limit too high")
587
    if U256(tx.nonce) >= U256(U64.MAX_VALUE):
588
        raise NonceOverflowError("Nonce too high")
642
643
    if isinstance(tx, FeeMarketCapableTransaction):
644
        if tx.max_fee_per_gas < tx.max_priority_fee_per_gas:
645
            raise PriorityFeeGreaterThanMaxFeeError(
646
                "priority fee greater than max fee"
647
            )
648
649
    if isinstance(tx, BlobTransaction):
650
        blob_count = len(tx.blob_versioned_hashes)
651
        if blob_count == 0:
652
            raise NoBlobDataError("no blob data in transaction")
653
        if blob_count > BLOB_COUNT_LIMIT:
654
            raise BlobCountExceededError(
655
                f"Tx has {blob_count} blobs. Max allowed: {BLOB_COUNT_LIMIT}"
656
            )
657
        for blob_versioned_hash in tx.blob_versioned_hashes:
658
            if blob_versioned_hash[0:1] != VERSIONED_HASH_VERSION_KZG:
659
                raise InvalidBlobVersionedHashError(
660
                    "invalid blob versioned hash"
661
                )
662
663
    if isinstance(tx, (BlobTransaction, SetCodeTransaction)):
664
        if not isinstance(tx.to, Address):
665
            raise TransactionTypeContractCreationError(tx)
666
667
    if isinstance(tx, SetCodeTransaction):
668
        if not any(tx.authorizations):
669
            raise EmptyAuthorizationListError("empty authorization list")
670
671
    intrinsic = calculate_intrinsic_cost(tx, sender)
672
    intrinsic_gas = Uint(intrinsic.execution)
673
    if intrinsic_gas > tx.gas:
674
        raise InsufficientTransactionGasError("Insufficient intrinsic gas")
675
    if intrinsic.calldata_floor > tx.gas:
676
        raise InsufficientTransactionGasError("Insufficient calldata floor")
677
    if intrinsic.execution > GasCosts.TX_MAX_GAS_LIMIT:
678
        raise InsufficientTransactionGasError(
679
            "Intrinsic execution gas exceeds TX_MAX_GAS_LIMIT"
680
        )
681
    if intrinsic.calldata_floor > GasCosts.TX_MAX_GAS_LIMIT:
682
        raise InsufficientTransactionGasError(
683
            "Intrinsic calldata floor exceeds TX_MAX_GAS_LIMIT"
684
        )
685
686
    return intrinsic

calculate_intrinsic_cost

Calculates the gas that is charged before execution is started.Calculate the gas charged before execution starts and the data floor.

The intrinsic cost of the transaction is charged before execution has begun. Functions/operations in the EVM cost money to execute so this intrinsic cost is for the operations that need to be paid for as part of the transaction. Data transfer, for example, is part of this intrinsic cost. It costs ether to send data over the wire and that ether is accounted for in the intrinsic cost calculated in this function. This intrinsic cost must be calculated and paid for before execution in order for all operations to be implemented.

The intrinsic cost includes:

  1. Base cost (Sender cost (TX_BASE)).

  2. Cost for data (zero and non-zero bytes)Recipient cost (COLD_ACCOUNT_ACCESS for a non-self-transfer call, or CREATE_ACCESS for a contract creation). The created account's NEW_ACCOUNT state gas is state-dependent and is charged at the top frame, not here.

  3. Cost for contract creation (if applicable)Value cost (TX_VALUE_COST for a non-self-transfer call) when tx.value > 0.

  4. Cost for access list entries (if applicable)Calldata cost (zero and non-zero bytes).

  5. Cost for authorizations (if applicable)Access list entry charges and the data surcharge (if applicable).

  6. Authorizations (if applicable): only the state-independent base cost (EXECUTION_PER_AUTH_BASE_COST) per tuple. The state-dependent account-creation and delegation-write costs are charged at the top frame by set_delegation.

This function takes a transaction as a parameter and returns the intrinsicSelf-transfers (sender == tx.to) skip the recipient and value gas cost of the transaction and the minimum gas cost used by the transaction based on the calldata size.charges.

This function takes a transaction and its sender as parameters and returns the intrinsic execution gas cost and the minimum (floor) gas cost based on the calldata size and access list data surcharge. The surcharge is added to both costs, so it is charged regardless of which side determines the gas used. The floor is anchored on the execution-gas portion of items 1 to 3 above rather than TX_BASE alone, so it never undercuts the transaction's own intrinsic base.

def calculate_intrinsic_cost(​tx: Transaction, ​​sender: Address​) -> IntrinsicGasCost:
692
    <snip>
730
    from .vm.gas import GasCosts, init_code_cost
731
625
    num_zeros = Uint(tx.data.count(0))
626
    num_non_zeros = ulen(tx.data) - num_zeros
627
628
    tokens_in_calldata = num_zeros + num_non_zeros * Uint(4)
629
    # EIP-7623 floor price (note: no EVM costs)
630
    calldata_floor_gas_cost = (
631
        tokens_in_calldata * GasCosts.TX_DATA_TOKEN_FLOOR + GasCosts.TX_BASE
632
    )
732
    tokens_in_calldata = count_tokens_in_data(tx.data)
733
734
    data_cost = tokens_in_calldata * GasCosts.TX_DATA_TOKEN_STANDARD
735
636
    if tx.to == Bytes0(b""):
637
        create_cost = GasCosts.TX_CREATE + init_code_cost(ulen(tx.data))
638
    else:
639
        create_cost = Uint(0)
736
    is_create = tx.to == Bytes0(b"")
737
    is_self_transfer = tx.to == sender
738
739
    recipient_execution_gas = Uint(0)
740
    init_code_gas = Uint(0)
741
    if is_create:
742
        recipient_execution_gas = GasCosts.CREATE_ACCESS
743
        init_code_gas = init_code_cost(ulen(tx.data))
744
    elif not is_self_transfer:
745
        recipient_execution_gas = GasCosts.COLD_ACCOUNT_ACCESS
746
        if tx.value > U256(0):
747
            recipient_execution_gas += GasCosts.TX_VALUE_COST
748
749
    access_list_cost = Uint(0)
750
    tokens_in_access_list = Uint(0)
751
    if has_access_list(tx):
752
        for access in tx.access_list:
753
            access_list_cost += GasCosts.TX_ACCESS_LIST_ADDRESS
754
            access_list_cost += (
755
                ulen(access.slots) * GasCosts.TX_ACCESS_LIST_STORAGE_KEY
756
            )
757
            tokens_in_access_list += ACCESS_LIST_ADDRESS_FLOOR_TOKENS
758
            tokens_in_access_list += (
759
                ulen(access.slots) * ACCESS_LIST_STORAGE_KEY_FLOOR_TOKENS
760
            )
761
762
    # Charge the access list data surcharge on both sides of the gas-used
763
    # maximum, independently of the existing per-entry access charges.
764
    access_list_data_cost = (
765
        tokens_in_access_list * GasCosts.TX_DATA_TOKEN_FLOOR
766
    )
767
768
    auth_cost = Uint(0)
769
    if isinstance(tx, SetCodeTransaction):
651
        auth_cost += Uint(
652
            GasCosts.AUTH_PER_EMPTY_ACCOUNT * len(tx.authorizations)
653
        )
770
        auth_cost = GasCosts.EXECUTION_PER_AUTH_BASE_COST * ulen(
771
            tx.authorizations
772
        )
773
774
    # EIP-7976 floor tokens: all calldata bytes count uniformly.
775
    floor_tokens_in_calldata = ulen(tx.data) * GasCosts.TX_DATA_TOKEN_STANDARD
776
777
    # Decomposed execution-gas intrinsic base (EIP-2780), which also
778
    # anchors the calldata floor.
779
    base_execution_gas = GasCosts.TX_BASE + recipient_execution_gas
780
781
    # Floor gas cost (EIP-7623: minimum gas for data-heavy transactions).
782
    data_floor_gas_cost = (
783
        base_execution_gas
784
        + floor_tokens_in_calldata * GasCosts.TX_DATA_TOKEN_FLOOR
785
        + access_list_data_cost
786
    )
787
788
    return IntrinsicGasCost(
656
        regular=Uint(
657
            GasCosts.TX_BASE
789
        execution=ExecutionGas(
790
            base_execution_gas
791
            + init_code_gas
792
            + data_cost
659
            + create_cost
660
            + access_list_cost
793
            + access_list_cost
794
            + access_list_data_cost
795
            + auth_cost
796
        ),
663
        calldata_floor=calldata_floor_gas_cost,
797
        calldata_floor=ExecutionGas(data_floor_gas_cost),
798
    )

count_tokens_in_data

Count the data tokens in arbitrary input bytes.

Zero bytes count as 1 token; non-zero bytes count as 4 tokens.

def count_tokens_in_data(​data: bytes​) -> Uint:
802
    <snip>
807
    num_zeros = Uint(data.count(0))
808
    num_non_zeros = ulen(data) - num_zeros
809
810
    return num_zeros + num_non_zeros * Uint(4)

calculate_effective_gas_price

Calculate the price per unit of gas the transaction actually pays.

A fee-market transaction pays the base fee plus a priority fee capped by both of its fee caps; its maximum fee must cover the base fee, or an InsufficientMaxFeePerGasError is raised. A transaction priced with a plain gas price pays that price outright, which must likewise cover the base fee.

def calculate_effective_gas_price(​tx: Transaction, ​​base_fee_per_gas: Uint​) -> Uint:
816
    <snip>
825
    if isinstance(tx, FeeMarketCapableTransaction):
826
        if tx.max_fee_per_gas < base_fee_per_gas:
827
            raise InsufficientMaxFeePerGasError(
828
                tx.max_fee_per_gas, base_fee_per_gas
829
            )
830
831
        priority_fee_per_gas = min(
832
            tx.max_priority_fee_per_gas,
833
            tx.max_fee_per_gas - base_fee_per_gas,
834
        )
835
        return priority_fee_per_gas + base_fee_per_gas
836
837
    if tx.gas_price < base_fee_per_gas:
838
        raise InvalidBlock
839
    return tx.gas_price

calculate_max_gas_fee

Calculate the largest execution-gas fee the transaction can incur: gas_limit priced at the transaction's fee cap.

def calculate_max_gas_fee(​tx: Transaction, ​​gas_limit: Uint​) -> Uint:
843
    <snip>
847
    if isinstance(tx, FeeMarketCapableTransaction):
848
        return gas_limit * tx.max_fee_per_gas
849
    return gas_limit * tx.gas_price

check_nonce

Check that the transaction's nonce equals the sender's next nonce.

def check_nonce(​tx: Transaction, ​​sender_nonce: Uint​) -> None:
853
    <snip>
856
    if sender_nonce > Uint(tx.nonce):
857
        raise NonceMismatchError("nonce too low")
858
    elif sender_nonce < Uint(tx.nonce):
859
        raise NonceMismatchError("nonce too high")

chain_id

Extract the chain identifier from a transaction. See EIP-155.

def chain_id(​tx: Transaction​) -> None | U64:
863
    <snip>
868
    if isinstance(tx, LegacyTransaction):
869
        if tx.v == 27 or tx.v == 28:
870
            return None
871
872
        if tx.v < U256(35):
873
            raise InvalidSignatureError("bad v")
874
875
        tx_chain_id = (tx.v - U256(35)) >> U256(1)
876
        if tx_chain_id > U256(U64.MAX_VALUE):
877
            raise InvalidSignatureError("bad v")
878
        return U64(tx_chain_id)
879
    else:
880
        return tx.chain_id

recover_sender

Extracts the sender address from a transaction.

The v, r, and s values are the three parts that make up the signature of a transaction. In order to recover the sender of a transaction the two components needed are the signature (v, r, and s) and the signing hash of the transaction. The sender's public key can be obtained with these two values and therefore the sender address can be retrieved.

This function takes chain_id and a transaction as parameters and returns the address of the sender of the transaction. It raises an InvalidSignatureError if the signature values (r, s, v) are invalid.

def recover_sender(​tx: Transaction​) -> Address:
884
    <snip>
897
    r, s = tx.r, tx.s
898
    if U256(0) >= r or r >= SECP256K1N:
899
        raise InvalidSignatureError("bad r")
900
    if U256(0) >= s or s > SECP256K1N // U256(2):
901
        raise InvalidSignatureError("bad s")
902
903
    if isinstance(tx, LegacyTransaction):
904
        v = tx.v
905
        if v == 27 or v == 28:
906
            public_key = secp256k1_recover(
907
                r, s, v - U256(27), signing_hash_pre155(tx)
908
            )
909
        else:
910
            assert v >= U256(35), "call chain_id before recover_sender"
911
            tx_chain_id = U64((v - U256(35)) >> U256(1))
912
            v = (v - U256(35)) & U256(1)
913
            public_key = secp256k1_recover(
914
                r,
915
                s,
916
                v,
917
                signing_hash_155(tx, tx_chain_id),
918
            )
919
    elif isinstance(tx, AccessListTransaction):
920
        if tx.y_parity not in (U256(0), U256(1)):
921
            raise InvalidSignatureError("bad y_parity")
922
        public_key = secp256k1_recover(
923
            r, s, tx.y_parity, signing_hash_2930(tx)
924
        )
925
    elif isinstance(tx, FeeMarketTransaction):
926
        if tx.y_parity not in (U256(0), U256(1)):
927
            raise InvalidSignatureError("bad y_parity")
928
        public_key = secp256k1_recover(
929
            r, s, tx.y_parity, signing_hash_1559(tx)
930
        )
931
    elif isinstance(tx, BlobTransaction):
932
        if tx.y_parity not in (U256(0), U256(1)):
933
            raise InvalidSignatureError("bad y_parity")
934
        public_key = secp256k1_recover(
935
            r, s, tx.y_parity, signing_hash_4844(tx)
936
        )
937
    elif isinstance(tx, SetCodeTransaction):
938
        if tx.y_parity not in (U256(0), U256(1)):
939
            raise InvalidSignatureError("bad y_parity")
940
        public_key = secp256k1_recover(
941
            r, s, tx.y_parity, signing_hash_7702(tx)
942
        )
943
944
    return Address(keccak256(public_key)[12:32])

signing_hash_pre155

Compute the hash of a transaction used in a legacy (pre EIP-155) signature.

This function takes a legacy transaction as a parameter and returns the signing hash of the transaction.

def signing_hash_pre155(​tx: LegacyTransaction​) -> Hash32:
948
    <snip>
957
    return keccak256(
958
        rlp.encode(
959
            (
960
                tx.nonce,
961
                tx.gas_price,
962
                tx.gas,
963
                tx.to,
964
                tx.value,
965
                tx.data,
966
            )
967
        )
968
    )

signing_hash_155

Compute the hash of a transaction used in a EIP-155 signature.

This function takes a legacy transaction and a chain ID as parameters and returns the hash of the transaction used in an EIP-155 signature.

def signing_hash_155(​tx: LegacyTransaction, ​​chain_id: U64​) -> Hash32:
972
    <snip>
980
    return keccak256(
981
        rlp.encode(
982
            (
983
                tx.nonce,
984
                tx.gas_price,
985
                tx.gas,
986
                tx.to,
987
                tx.value,
988
                tx.data,
989
                chain_id,
990
                Uint(0),
991
                Uint(0),
992
            )
993
        )
994
    )

signing_hash_2930

Compute the hash of a transaction used in a EIP-2930 signature.

This function takes an access list transaction as a parameter and returns the hash of the transaction used in an EIP-2930 signature.

def signing_hash_2930(​tx: AccessListTransaction​) -> Hash32:
998
    <snip>
1006
    return keccak256(
1007
        b"\x01"
1008
        + rlp.encode(
1009
            (
1010
                tx.chain_id,
1011
                tx.nonce,
1012
                tx.gas_price,
1013
                tx.gas,
1014
                tx.to,
1015
                tx.value,
1016
                tx.data,
1017
                tx.access_list,
1018
            )
1019
        )
1020
    )

signing_hash_1559

Compute the hash of a transaction used in an EIP-1559 signature.

This function takes a fee market transaction as a parameter and returns the hash of the transaction used in an EIP-1559 signature.

def signing_hash_1559(​tx: FeeMarketTransaction​) -> Hash32:
1024
    <snip>
1032
    return keccak256(
1033
        b"\x02"
1034
        + rlp.encode(
1035
            (
1036
                tx.chain_id,
1037
                tx.nonce,
1038
                tx.max_priority_fee_per_gas,
1039
                tx.max_fee_per_gas,
1040
                tx.gas,
1041
                tx.to,
1042
                tx.value,
1043
                tx.data,
1044
                tx.access_list,
1045
            )
1046
        )
1047
    )

signing_hash_4844

Compute the hash of a transaction used in an EIP-4844 signature.

This function takes a transaction as a parameter and returns the signing hash of the transaction used in an EIP-4844 signature.

def signing_hash_4844(​tx: BlobTransaction​) -> Hash32:
1051
    <snip>
1059
    return keccak256(
1060
        b"\x03"
1061
        + rlp.encode(
1062
            (
1063
                tx.chain_id,
1064
                tx.nonce,
1065
                tx.max_priority_fee_per_gas,
1066
                tx.max_fee_per_gas,
1067
                tx.gas,
1068
                tx.to,
1069
                tx.value,
1070
                tx.data,
1071
                tx.access_list,
1072
                tx.max_fee_per_blob_gas,
1073
                tx.blob_versioned_hashes,
1074
            )
1075
        )
1076
    )

signing_hash_7702

Compute the hash of a transaction used in a EIP-7702 signature.

This function takes a transaction as a parameter and returns the signing hash of the transaction used in a EIP-7702 signature.

def signing_hash_7702(​tx: SetCodeTransaction​) -> Hash32:
1080
    <snip>
1088
    return keccak256(
1089
        b"\x04"
1090
        + rlp.encode(
1091
            (
1092
                tx.chain_id,
1093
                tx.nonce,
1094
                tx.max_priority_fee_per_gas,
1095
                tx.max_fee_per_gas,
1096
                tx.gas,
1097
                tx.to,
1098
                tx.value,
1099
                tx.data,
1100
                tx.access_list,
1101
                tx.authorizations,
1102
            )
1103
        )
1104
    )

get_transaction_hash

Compute the hash of a transaction.

This function takes a transaction as a parameter and returns the keccak256 hash of the transaction. It can handle both legacy transactions and typed transactions (AccessListTransaction, FeeMarketTransaction, etc.).

def get_transaction_hash(​tx: Bytes | LegacyTransaction​) -> Hash32:
1108
    <snip>
1116
    assert isinstance(tx, (LegacyTransaction, Bytes))
1117
    if isinstance(tx, LegacyTransaction):
1118
        return keccak256(rlp.encode(tx))
1119
    else:
1120
        return keccak256(tx)

has_access_list

Return whether the transaction has an EIP-2930-style access list.

def has_access_list(​tx: Transaction​) -> TypeGuard[AccessListCapableTransaction]:
1126
    <snip>
1131
    return isinstance(
1132
        tx,
1133
        AccessListCapableTransaction,
1134
    )