ethereum.forks.cancun.transactionsethereum.forks.prague.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.

33
@final
34
@dataclass
class IntrinsicGasCost:

regular

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

38
    regular: Uint

calldata_floor

Minimum gas cost based on calldata size per EIP-7623.

41
    calldata_floor: Uint

LegacyTransaction

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

49
@final
50
@slotted_freezable
51
@dataclass
class LegacyTransaction:

nonce

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

64
    nonce: U256

gas_price

The price of gas for this transaction, in wei.

69
    gas_price: Uint

gas

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

74
    gas: Uint

to

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

79
    to: Bytes0 | Address

value

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

85
    value: U256

data

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

90
    data: Bytes

v

The recovery id of the signature.

96
    v: U256

r

The first part of the signature.

101
    r: U256

s

The second part of the signature.

106
    s: U256

Access

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

112
@final
113
@slotted_freezable
114
@dataclass
class Access:

account

The address of the account that is accessed.

121
    account: Address

slots

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

126
    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.

132
@final
133
@slotted_freezable
134
@dataclass
class AccessListTransaction:

chain_id

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

146
    chain_id: U64

nonce

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

151
    nonce: U256

gas_price

The price of gas for this transaction.

156
    gas_price: Uint

gas

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

161
    gas: Uint

to

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

166
    to: Bytes0 | Address

value

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

172
    value: U256

data

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

177
    data: Bytes

access_list

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

183
    access_list: Tuple[Access, ...]

y_parity

The recovery id of the signature.

189
    y_parity: U256

r

The first part of the signature.

194
    r: U256

s

The second part of the signature.

199
    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.

205
@final
206
@slotted_freezable
207
@dataclass
class FeeMarketTransaction:

chain_id

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

218
    chain_id: U64

nonce

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

223
    nonce: U256

max_priority_fee_per_gas

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

228
    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.

233
    max_fee_per_gas: Uint

gas

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

239
    gas: Uint

to

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

244
    to: Bytes0 | Address

value

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

250
    value: U256

data

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

255
    data: Bytes

access_list

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

261
    access_list: Tuple[Access, ...]

y_parity

The recovery id of the signature.

267
    y_parity: U256

r

The first part of the signature.

272
    r: U256

s

The second part of the signature.

277
    s: U256

BlobTransaction

The transaction type added in EIP-4844.

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

283
@final
284
@slotted_freezable
285
@dataclass
class BlobTransaction:

chain_id

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

296
    chain_id: U64

nonce

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

301
    nonce: U256

max_priority_fee_per_gas

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

306
    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.

311
    max_fee_per_gas: Uint

gas

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

317
    gas: Uint

to

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

322
    to: Address

value

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

328
    value: U256

data

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

333
    data: Bytes

access_list

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

339
    access_list: Tuple[Access, ...]

max_fee_per_blob_gas

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

345
    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.

350
    blob_versioned_hashes: Tuple[VersionedHash, ...]

y_parity

The recovery id of the signature.

356
    y_parity: U256

r

The first part of the signature.

361
    r: U256

s

The second part of the signature.

366
    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.

372
@final
373
@slotted_freezable
374
@dataclass
class SetCodeTransaction:

chain_id

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

385
    chain_id: U64

nonce

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

390
    nonce: U64

max_priority_fee_per_gas

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

395
    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.

400
    max_fee_per_gas: Uint

gas

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

406
    gas: Uint

to

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

411
    to: Address

value

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

417
    value: U256

data

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

422
    data: Bytes

access_list

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

428
    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.

434
    authorizations: Tuple[Authorization, ...]

y_parity

The recovery id of the signature.

440
    y_parity: U256

r

The first part of the signature.

445
    r: U256

s

The second part of the signature.

450
    s: U256

Transaction

Union type representing any valid transaction type.

456
Transaction = (
356
    LegacyTransaction
357
    | AccessListTransaction
358
    | FeeMarketTransaction
359
    | BlobTransaction
457
    LegacyTransaction
458
    | AccessListTransaction
459
    | FeeMarketTransaction
460
    | BlobTransaction
461
    | SetCodeTransaction
462
)

AccessListCapableTransaction

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

See has_access_list and Access for more details.

468
AccessListCapableTransaction = (
469
    AccessListTransaction
470
    | FeeMarketTransaction
471
    | BlobTransaction
472
    | SetCodeTransaction
473
)

FeeMarketCapableTransaction

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

See FeeMarketTransaction for more details.

366
FeeMarketCapableTransaction = FeeMarketTransaction | BlobTransaction
485
FeeMarketCapableTransaction = (
486
    FeeMarketTransaction | BlobTransaction | SetCodeTransaction
487
)

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:
499
    <snip>
506
    if isinstance(tx, LegacyTransaction):
507
        return tx
508
    elif isinstance(tx, AccessListTransaction):
509
        return b"\x01" + rlp.encode(tx)
510
    elif isinstance(tx, FeeMarketTransaction):
511
        return b"\x02" + rlp.encode(tx)
512
    elif isinstance(tx, BlobTransaction):
513
        return b"\x03" + rlp.encode(tx)
393
    else:
394
        raise Exception(f"Unable to encode transaction of type {type(tx)}")
514
    elif isinstance(tx, SetCodeTransaction):
515
        return b"\x04" + rlp.encode(tx)
516
    else:
517
        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 types are decoded based on their type identifier prefix.

def decode_transaction(​tx: LegacyTransaction | Bytes​) -> Transaction:
521
    <snip>
528
    if isinstance(tx, Bytes):
529
        if len(tx) == 0:
530
            raise InvalidBlock("empty transaction")
531
        if tx[0] == 1:
532
            return rlp.decode_to(AccessListTransaction, tx[1:])
533
        elif tx[0] == 2:
534
            return rlp.decode_to(FeeMarketTransaction, tx[1:])
535
        elif tx[0] == 3:
536
            return rlp.decode_to(BlobTransaction, tx[1:])
414
        else:
415
            raise TransactionTypeError(tx[0])
537
        elif tx[0] == 4:
538
            return rlp.decode_to(SetCodeTransaction, tx[1:])
539
        else:
540
            raise TransactionTypeError(tx[0])
541
    else:
542
        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 intrinsic gas cost of the transaction after validation. It throws angas cost and the minimum calldata gas cost for the transaction after validation. It throws an InsufficientTransactionGasError exception if the transaction does not exception if provide enough gas to cover the intrinsic cost, and a the transaction does not provide enough gas to cover the intrinsic cost, and a NonceOverflowError exception if the nonce is greater than exception if the nonce is greater than 2**64 - 2. It also raises an. It also raises an InitCodeTooLargeError if the code size of InitCodeTooLargeError if the code size of a contract creation transactiona contract creation transaction exceeds the maximum allowed size, and a exceeds the maximum allowed size, and a PriorityFeeGreaterThanMaxFeeError if the maximum priority fee per gas if the maximum priority fee per gas of a fee market transaction exceeds its maximum fee per gas.of a fee market transaction exceeds its maximum fee per gas.

def validate_transaction(​tx: Transaction​) -> UintIntrinsicGasCost:
546
    <snip>
576
    from .vm.interpreter import MAX_INIT_CODE_SIZE
577
452
    intrinsic_gas = calculate_intrinsic_cost(tx)
453
    if intrinsic_gas > tx.gas:
578
    intrinsic = calculate_intrinsic_cost(tx)
579
    if max(intrinsic.regular, intrinsic.calldata_floor) > tx.gas:
580
        raise InsufficientTransactionGasError("Insufficient gas")
581
    if tx.to == Bytes0(b"") and len(tx.data) > MAX_INIT_CODE_SIZE:
582
        raise InitCodeTooLargeError("Code size too large")
583
    if U256(tx.nonce) >= U256(U64.MAX_VALUE):
584
        raise NonceOverflowError("Nonce too high")
585
    if isinstance(tx, FeeMarketCapableTransaction):
586
        if tx.max_fee_per_gas < tx.max_priority_fee_per_gas:
587
            raise PriorityFeeGreaterThanMaxFeeError(
588
                "priority fee greater than max fee"
589
            )
590
465
    return intrinsic_gas
591
    return intrinsic

calculate_intrinsic_cost

Calculates the gas that is charged before execution is started.

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 (TX_BASE)

  2. Cost for data (zero and non-zero bytes)

  3. Cost for contract creation (if applicable)

  4. Cost for access list entries (if applicable)

  5. Cost for authorizations (if applicable)

This function takes a transaction as a parameter and returns the intrinsic gas cost of the transaction.gas cost of the transaction and the minimum gas cost used by the transaction based on the calldata size.

def calculate_intrinsic_cost(​tx: Transaction​) -> UintIntrinsicGasCost:
595
    <snip>
619
    from .vm.gas import GasCosts, init_code_cost
620
621
    num_zeros = Uint(tx.data.count(0))
622
    num_non_zeros = ulen(tx.data) - num_zeros
494
    data_cost = (
495
        num_zeros * GasCosts.TX_DATA_PER_ZERO
496
        + num_non_zeros * GasCosts.TX_DATA_PER_NON_ZERO
623
624
    tokens_in_calldata = num_zeros + num_non_zeros * Uint(4)
625
    # EIP-7623 floor price (note: no EVM costs)
626
    calldata_floor_gas_cost = (
627
        tokens_in_calldata * GasCosts.TX_DATA_TOKEN_FLOOR + GasCosts.TX_BASE
628
    )
629
630
    data_cost = tokens_in_calldata * GasCosts.TX_DATA_TOKEN_STANDARD
631
632
    if tx.to == Bytes0(b""):
633
        create_cost = GasCosts.TX_CREATE + init_code_cost(ulen(tx.data))
634
    else:
635
        create_cost = Uint(0)
636
637
    access_list_cost = Uint(0)
505
    if isinstance(
506
        tx, (AccessListTransaction, FeeMarketTransaction, BlobTransaction)
507
    ):
638
    if has_access_list(tx):
639
        for access in tx.access_list:
640
            access_list_cost += GasCosts.TX_ACCESS_LIST_ADDRESS
641
            access_list_cost += (
642
                ulen(access.slots) * GasCosts.TX_ACCESS_LIST_STORAGE_KEY
643
            )
644
514
    return GasCosts.TX_BASE + data_cost + create_cost + access_list_cost
645
    auth_cost = Uint(0)
646
    if isinstance(tx, SetCodeTransaction):
647
        auth_cost += Uint(
648
            GasCosts.AUTH_PER_EMPTY_ACCOUNT * len(tx.authorizations)
649
        )
650
651
    return IntrinsicGasCost(
652
        regular=Uint(
653
            GasCosts.TX_BASE
654
            + data_cost
655
            + create_cost
656
            + access_list_cost
657
            + auth_cost
658
        ),
659
        calldata_floor=calldata_floor_gas_cost,
660
    )

chain_id

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

def chain_id(​tx: Transaction​) -> None | U64:
664
    <snip>
669
    if isinstance(tx, LegacyTransaction):
670
        if tx.v == 27 or tx.v == 28:
671
            return None
672
673
        if tx.v < U256(35):
674
            raise InvalidSignatureError("bad v")
675
676
        tx_chain_id = (tx.v - U256(35)) >> U256(1)
677
        if tx_chain_id > U256(U64.MAX_VALUE):
678
            raise InvalidSignatureError("bad v")
679
        return U64(tx_chain_id)
680
    else:
681
        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:
685
    <snip>
698
    r, s = tx.r, tx.s
699
    if U256(0) >= r or r >= SECP256K1N:
700
        raise InvalidSignatureError("bad r")
701
    if U256(0) >= s or s > SECP256K1N // U256(2):
702
        raise InvalidSignatureError("bad s")
703
704
    if isinstance(tx, LegacyTransaction):
705
        v = tx.v
706
        if v == 27 or v == 28:
707
            public_key = secp256k1_recover(
708
                r, s, v - U256(27), signing_hash_pre155(tx)
709
            )
710
        else:
711
            assert v >= U256(35), "call chain_id before recover_sender"
712
            tx_chain_id = U64((v - U256(35)) >> U256(1))
713
            v = (v - U256(35)) & U256(1)
714
            public_key = secp256k1_recover(
715
                r,
716
                s,
717
                v,
718
                signing_hash_155(tx, tx_chain_id),
719
            )
720
    elif isinstance(tx, AccessListTransaction):
721
        if tx.y_parity not in (U256(0), U256(1)):
722
            raise InvalidSignatureError("bad y_parity")
723
        public_key = secp256k1_recover(
724
            r, s, tx.y_parity, signing_hash_2930(tx)
725
        )
726
    elif isinstance(tx, FeeMarketTransaction):
727
        if tx.y_parity not in (U256(0), U256(1)):
728
            raise InvalidSignatureError("bad y_parity")
729
        public_key = secp256k1_recover(
730
            r, s, tx.y_parity, signing_hash_1559(tx)
731
        )
732
    elif isinstance(tx, BlobTransaction):
733
        if tx.y_parity not in (U256(0), U256(1)):
734
            raise InvalidSignatureError("bad y_parity")
735
        public_key = secp256k1_recover(
736
            r, s, tx.y_parity, signing_hash_4844(tx)
591
        )
737
        )
738
    elif isinstance(tx, SetCodeTransaction):
739
        if tx.y_parity not in (U256(0), U256(1)):
740
            raise InvalidSignatureError("bad y_parity")
741
        public_key = secp256k1_recover(
742
            r, s, tx.y_parity, signing_hash_7702(tx)
743
        )
744
745
    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:
749
    <snip>
758
    return keccak256(
759
        rlp.encode(
760
            (
761
                tx.nonce,
762
                tx.gas_price,
763
                tx.gas,
764
                tx.to,
765
                tx.value,
766
                tx.data,
767
            )
768
        )
769
    )

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:
773
    <snip>
781
    return keccak256(
782
        rlp.encode(
783
            (
784
                tx.nonce,
785
                tx.gas_price,
786
                tx.gas,
787
                tx.to,
788
                tx.value,
789
                tx.data,
790
                chain_id,
791
                Uint(0),
792
                Uint(0),
793
            )
794
        )
795
    )

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:
799
    <snip>
807
    return keccak256(
808
        b"\x01"
809
        + rlp.encode(
810
            (
811
                tx.chain_id,
812
                tx.nonce,
813
                tx.gas_price,
814
                tx.gas,
815
                tx.to,
816
                tx.value,
817
                tx.data,
818
                tx.access_list,
819
            )
820
        )
821
    )

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:
825
    <snip>
833
    return keccak256(
834
        b"\x02"
835
        + rlp.encode(
836
            (
837
                tx.chain_id,
838
                tx.nonce,
839
                tx.max_priority_fee_per_gas,
840
                tx.max_fee_per_gas,
841
                tx.gas,
842
                tx.to,
843
                tx.value,
844
                tx.data,
845
                tx.access_list,
846
            )
847
        )
848
    )

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:
852
    <snip>
860
    return keccak256(
861
        b"\x03"
862
        + rlp.encode(
863
            (
864
                tx.chain_id,
865
                tx.nonce,
866
                tx.max_priority_fee_per_gas,
867
                tx.max_fee_per_gas,
868
                tx.gas,
869
                tx.to,
870
                tx.value,
871
                tx.data,
872
                tx.access_list,
873
                tx.max_fee_per_blob_gas,
874
                tx.blob_versioned_hashes,
875
            )
876
        )
877
    )

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:
881
    <snip>
889
    return keccak256(
890
        b"\x04"
891
        + rlp.encode(
892
            (
893
                tx.chain_id,
894
                tx.nonce,
895
                tx.max_priority_fee_per_gas,
896
                tx.max_fee_per_gas,
897
                tx.gas,
898
                tx.to,
899
                tx.value,
900
                tx.data,
901
                tx.access_list,
902
                tx.authorizations,
903
            )
904
        )
905
    )

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:
909
    <snip>
917
    assert isinstance(tx, (LegacyTransaction, Bytes))
918
    if isinstance(tx, LegacyTransaction):
919
        return keccak256(rlp.encode(tx))
920
    else:
921
        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]:
927
    <snip>
932
    return isinstance(
933
        tx,
934
        AccessListCapableTransaction,
935
    )