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.

28
@final
29
@dataclass
class IntrinsicGasCost:

regular

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

33
    regular: Uint

calldata_floor

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

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

44
@final
45
@slotted_freezable
46
@dataclass
class LegacyTransaction:

nonce

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

59
    nonce: U256

gas_price

The price of gas for this transaction, in wei.

64
    gas_price: Uint

gas

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

69
    gas: Uint

to

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

74
    to: Bytes0 | Address

value

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

80
    value: U256

data

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

85
    data: Bytes

v

The recovery id of the signature.

91
    v: U256

r

The first part of the signature.

96
    r: U256

s

The second part of the signature.

101
    s: U256

Access

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

107
@final
108
@slotted_freezable
109
@dataclass
class Access:

account

The address of the account that is accessed.

116
    account: Address

slots

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

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

127
@final
128
@slotted_freezable
129
@dataclass
class AccessListTransaction:

chain_id

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

141
    chain_id: U64

nonce

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

146
    nonce: U256

gas_price

The price of gas for this transaction.

151
    gas_price: Uint

gas

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

156
    gas: Uint

to

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

161
    to: Bytes0 | Address

value

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

167
    value: U256

data

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

172
    data: Bytes

access_list

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

178
    access_list: Tuple[Access, ...]

y_parity

The recovery id of the signature.

184
    y_parity: U256

r

The first part of the signature.

189
    r: U256

s

The second part of the signature.

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

200
@final
201
@slotted_freezable
202
@dataclass
class FeeMarketTransaction:

chain_id

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

213
    chain_id: U64

nonce

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

218
    nonce: U256

max_priority_fee_per_gas

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

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

228
    max_fee_per_gas: Uint

gas

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

234
    gas: Uint

to

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

239
    to: Bytes0 | Address

value

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

245
    value: U256

data

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

250
    data: Bytes

access_list

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

256
    access_list: Tuple[Access, ...]

y_parity

The recovery id of the signature.

262
    y_parity: U256

r

The first part of the signature.

267
    r: U256

s

The second part of the signature.

272
    s: U256

BlobTransaction

The transaction type added in EIP-4844.

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

278
@final
279
@slotted_freezable
280
@dataclass
class BlobTransaction:

chain_id

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

291
    chain_id: U64

nonce

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

296
    nonce: U256

max_priority_fee_per_gas

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

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

306
    max_fee_per_gas: Uint

gas

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

312
    gas: Uint

to

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

317
    to: Address

value

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

323
    value: U256

data

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

328
    data: Bytes

access_list

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

334
    access_list: Tuple[Access, ...]

max_fee_per_blob_gas

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

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

345
    blob_versioned_hashes: Tuple[VersionedHash, ...]

y_parity

The recovery id of the signature.

351
    y_parity: U256

r

The first part of the signature.

356
    r: U256

s

The second part of the signature.

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

367
@final
368
@slotted_freezable
369
@dataclass
class SetCodeTransaction:

chain_id

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

380
    chain_id: U64

nonce

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

385
    nonce: U64

max_priority_fee_per_gas

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

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

395
    max_fee_per_gas: Uint

gas

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

401
    gas: Uint

to

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

406
    to: Address

value

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

412
    value: U256

data

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

417
    data: Bytes

access_list

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

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

429
    authorizations: Tuple[Authorization, ...]

y_parity

The recovery id of the signature.

435
    y_parity: U256

r

The first part of the signature.

440
    r: U256

s

The second part of the signature.

445
    s: U256

Transaction

Union type representing any valid transaction type.

451
Transaction = (
351
    LegacyTransaction
352
    | AccessListTransaction
353
    | FeeMarketTransaction
354
    | BlobTransaction
452
    LegacyTransaction
453
    | AccessListTransaction
454
    | FeeMarketTransaction
455
    | BlobTransaction
456
    | SetCodeTransaction
457
)

AccessListCapableTransaction

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

See has_access_list and Access for more details.

463
AccessListCapableTransaction = (
464
    AccessListTransaction
465
    | FeeMarketTransaction
466
    | BlobTransaction
467
    | SetCodeTransaction
468
)

FeeMarketCapableTransaction

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

See FeeMarketTransaction for more details.

361
FeeMarketCapableTransaction = FeeMarketTransaction | BlobTransaction
480
FeeMarketCapableTransaction = (
481
    FeeMarketTransaction | BlobTransaction | SetCodeTransaction
482
)

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:
494
    <snip>
501
    if isinstance(tx, LegacyTransaction):
502
        return tx
503
    elif isinstance(tx, AccessListTransaction):
504
        return b"\x01" + rlp.encode(tx)
505
    elif isinstance(tx, FeeMarketTransaction):
506
        return b"\x02" + rlp.encode(tx)
507
    elif isinstance(tx, BlobTransaction):
508
        return b"\x03" + rlp.encode(tx)
388
    else:
389
        raise Exception(f"Unable to encode transaction of type {type(tx)}")
509
    elif isinstance(tx, SetCodeTransaction):
510
        return b"\x04" + rlp.encode(tx)
511
    else:
512
        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:
516
    <snip>
523
    if isinstance(tx, Bytes):
524
        if tx[0] == 1:
525
            return rlp.decode_to(AccessListTransaction, tx[1:])
526
        elif tx[0] == 2:
527
            return rlp.decode_to(FeeMarketTransaction, tx[1:])
528
        elif tx[0] == 3:
529
            return rlp.decode_to(BlobTransaction, tx[1:])
407
        else:
408
            raise TransactionTypeError(tx[0])
530
        elif tx[0] == 4:
531
            return rlp.decode_to(SetCodeTransaction, tx[1:])
532
        else:
533
            raise TransactionTypeError(tx[0])
534
    else:
535
        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 transaction exceeds the maximum allowed size.a contract creation transaction exceeds the maximum allowed size.

def validate_transaction(tx: Transaction) -> UintIntrinsicGasCost:
539
    <snip>
567
    from .vm.interpreter import MAX_INIT_CODE_SIZE
568
443
    intrinsic_gas = calculate_intrinsic_cost(tx)
444
    if intrinsic_gas > tx.gas:
569
    intrinsic = calculate_intrinsic_cost(tx)
570
    if max(intrinsic.regular, intrinsic.calldata_floor) > tx.gas:
571
        raise InsufficientTransactionGasError("Insufficient gas")
572
    if U256(tx.nonce) >= U256(U64.MAX_VALUE):
573
        raise NonceOverflowError("Nonce too high")
574
    if tx.to == Bytes0(b"") and len(tx.data) > MAX_INIT_CODE_SIZE:
575
        raise InitCodeTooLargeError("Code size too large")
576
451
    return intrinsic_gas
577
    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:
581
    <snip>
605
    from .vm.gas import GasCosts, init_code_cost
606
607
    num_zeros = Uint(tx.data.count(0))
608
    num_non_zeros = ulen(tx.data) - num_zeros
480
    data_cost = (
481
        num_zeros * GasCosts.TX_DATA_PER_ZERO
482
        + num_non_zeros * GasCosts.TX_DATA_PER_NON_ZERO
609
610
    tokens_in_calldata = num_zeros + num_non_zeros * Uint(4)
611
    # EIP-7623 floor price (note: no EVM costs)
612
    calldata_floor_gas_cost = (
613
        tokens_in_calldata * GasCosts.TX_DATA_TOKEN_FLOOR + GasCosts.TX_BASE
614
    )
615
616
    data_cost = tokens_in_calldata * GasCosts.TX_DATA_TOKEN_STANDARD
617
618
    if tx.to == Bytes0(b""):
619
        create_cost = GasCosts.TX_CREATE + init_code_cost(ulen(tx.data))
620
    else:
621
        create_cost = Uint(0)
622
623
    access_list_cost = Uint(0)
491
    if isinstance(
492
        tx, (AccessListTransaction, FeeMarketTransaction, BlobTransaction)
493
    ):
624
    if has_access_list(tx):
625
        for access in tx.access_list:
626
            access_list_cost += GasCosts.TX_ACCESS_LIST_ADDRESS
627
            access_list_cost += (
628
                ulen(access.slots) * GasCosts.TX_ACCESS_LIST_STORAGE_KEY
629
            )
630
500
    return GasCosts.TX_BASE + data_cost + create_cost + access_list_cost
631
    auth_cost = Uint(0)
632
    if isinstance(tx, SetCodeTransaction):
633
        auth_cost += Uint(
634
            GasCosts.AUTH_PER_EMPTY_ACCOUNT * len(tx.authorizations)
635
        )
636
637
    return IntrinsicGasCost(
638
        regular=Uint(
639
            GasCosts.TX_BASE
640
            + data_cost
641
            + create_cost
642
            + access_list_cost
643
            + auth_cost
644
        ),
645
        calldata_floor=calldata_floor_gas_cost,
646
    )

chain_id

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

def chain_id(tx: Transaction) -> None | U64:
650
    <snip>
655
    if isinstance(tx, LegacyTransaction):
656
        if tx.v == 27 or tx.v == 28:
657
            return None
658
659
        if tx.v < U256(35):
660
            raise InvalidSignatureError("bad v")
661
662
        return U64((tx.v - U256(35)) >> U256(1))
663
    else:
664
        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:
668
    <snip>
681
    r, s = tx.r, tx.s
682
    if U256(0) >= r or r >= SECP256K1N:
683
        raise InvalidSignatureError("bad r")
684
    if U256(0) >= s or s > SECP256K1N // U256(2):
685
        raise InvalidSignatureError("bad s")
686
687
    if isinstance(tx, LegacyTransaction):
688
        v = tx.v
689
        if v == 27 or v == 28:
690
            public_key = secp256k1_recover(
691
                r, s, v - U256(27), signing_hash_pre155(tx)
692
            )
693
        else:
694
            assert v >= U256(35), "call chain_id before recover_sender"
695
            tx_chain_id = U64((v - U256(35)) >> U256(1))
696
            v = (v - U256(35)) & U256(1)
697
            public_key = secp256k1_recover(
698
                r,
699
                s,
700
                v,
701
                signing_hash_155(tx, tx_chain_id),
702
            )
703
    elif isinstance(tx, AccessListTransaction):
704
        if tx.y_parity not in (U256(0), U256(1)):
705
            raise InvalidSignatureError("bad y_parity")
706
        public_key = secp256k1_recover(
707
            r, s, tx.y_parity, signing_hash_2930(tx)
708
        )
709
    elif isinstance(tx, FeeMarketTransaction):
710
        if tx.y_parity not in (U256(0), U256(1)):
711
            raise InvalidSignatureError("bad y_parity")
712
        public_key = secp256k1_recover(
713
            r, s, tx.y_parity, signing_hash_1559(tx)
714
        )
715
    elif isinstance(tx, BlobTransaction):
716
        if tx.y_parity not in (U256(0), U256(1)):
717
            raise InvalidSignatureError("bad y_parity")
718
        public_key = secp256k1_recover(
719
            r, s, tx.y_parity, signing_hash_4844(tx)
574
        )
720
        )
721
    elif isinstance(tx, SetCodeTransaction):
722
        if tx.y_parity not in (U256(0), U256(1)):
723
            raise InvalidSignatureError("bad y_parity")
724
        public_key = secp256k1_recover(
725
            r, s, tx.y_parity, signing_hash_7702(tx)
726
        )
727
728
    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:
732
    <snip>
741
    return keccak256(
742
        rlp.encode(
743
            (
744
                tx.nonce,
745
                tx.gas_price,
746
                tx.gas,
747
                tx.to,
748
                tx.value,
749
                tx.data,
750
            )
751
        )
752
    )

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:
756
    <snip>
764
    return keccak256(
765
        rlp.encode(
766
            (
767
                tx.nonce,
768
                tx.gas_price,
769
                tx.gas,
770
                tx.to,
771
                tx.value,
772
                tx.data,
773
                chain_id,
774
                Uint(0),
775
                Uint(0),
776
            )
777
        )
778
    )

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:
782
    <snip>
790
    return keccak256(
791
        b"\x01"
792
        + rlp.encode(
793
            (
794
                tx.chain_id,
795
                tx.nonce,
796
                tx.gas_price,
797
                tx.gas,
798
                tx.to,
799
                tx.value,
800
                tx.data,
801
                tx.access_list,
802
            )
803
        )
804
    )

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:
808
    <snip>
816
    return keccak256(
817
        b"\x02"
818
        + rlp.encode(
819
            (
820
                tx.chain_id,
821
                tx.nonce,
822
                tx.max_priority_fee_per_gas,
823
                tx.max_fee_per_gas,
824
                tx.gas,
825
                tx.to,
826
                tx.value,
827
                tx.data,
828
                tx.access_list,
829
            )
830
        )
831
    )

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:
835
    <snip>
843
    return keccak256(
844
        b"\x03"
845
        + rlp.encode(
846
            (
847
                tx.chain_id,
848
                tx.nonce,
849
                tx.max_priority_fee_per_gas,
850
                tx.max_fee_per_gas,
851
                tx.gas,
852
                tx.to,
853
                tx.value,
854
                tx.data,
855
                tx.access_list,
856
                tx.max_fee_per_blob_gas,
857
                tx.blob_versioned_hashes,
858
            )
859
        )
860
    )

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:
864
    <snip>
872
    return keccak256(
873
        b"\x04"
874
        + rlp.encode(
875
            (
876
                tx.chain_id,
877
                tx.nonce,
878
                tx.max_priority_fee_per_gas,
879
                tx.max_fee_per_gas,
880
                tx.gas,
881
                tx.to,
882
                tx.value,
883
                tx.data,
884
                tx.access_list,
885
                tx.authorizations,
886
            )
887
        )
888
    )

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:
892
    <snip>
900
    assert isinstance(tx, (LegacyTransaction, Bytes))
901
    if isinstance(tx, LegacyTransaction):
902
        return keccak256(rlp.encode(tx))
903
    else:
904
        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]:
910
    <snip>
915
    return isinstance(
916
        tx,
917
        AccessListCapableTransaction,
918
    )