ethereum.cancun.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.

TX_BASE_COST

Base cost of a transaction in gas units. This is the minimum amount of gas required to execute a transaction.

25
TX_BASE_COST = Uint(21000)

TX_DATA_COST_PER_NON_ZERO

Gas cost per non-zero byte in the transaction data.

31
TX_DATA_COST_PER_NON_ZERO = Uint(16)

TX_DATA_COST_PER_ZERO

Gas cost per zero byte in the transaction data.

36
TX_DATA_COST_PER_ZERO = Uint(4)

TX_CREATE_COST

Additional gas cost for creating a new contract.

41
TX_CREATE_COST = Uint(32000)

TX_ACCESS_LIST_ADDRESS_COST

Gas cost for including an address in the access list of a transaction.

46
TX_ACCESS_LIST_ADDRESS_COST = Uint(2400)

TX_ACCESS_LIST_STORAGE_KEY_COST

Gas cost for including a storage key in the access list of a transaction.

51
TX_ACCESS_LIST_STORAGE_KEY_COST = Uint(1900)

LegacyTransaction

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

57
@slotted_freezable
58
@dataclass
class LegacyTransaction:

nonce

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

70
    nonce: U256

gas_price

The price of gas for this transaction, in wei.

75
    gas_price: Uint

gas

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

80
    gas: Uint

to

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

85
    to: Bytes0 | Address

value

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

91
    value: U256

data

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

96
    data: Bytes

v

The recovery id of the signature.

102
    v: U256

r

The first part of the signature.

107
    r: U256

s

The second part of the signature.

112
    s: U256

Access

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

118
@slotted_freezable
119
@dataclass
class Access:

account

The address of the account that is accessed.

126
    account: Address

slots

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

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

137
@slotted_freezable
138
@dataclass
class AccessListTransaction:

chain_id

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

150
    chain_id: U64

nonce

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

155
    nonce: U256

gas_price

The price of gas for this transaction.

160
    gas_price: Uint

gas

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

165
    gas: Uint

to

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

170
    to: Bytes0 | Address

value

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

176
    value: U256

data

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

181
    data: Bytes

access_list

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

187
    access_list: Tuple[Access, ...]

y_parity

The recovery id of the signature.

193
    y_parity: U256

r

The first part of the signature.

198
    r: U256

s

The second part of the signature.

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

209
@slotted_freezable
210
@dataclass
class FeeMarketTransaction:

chain_id

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

221
    chain_id: U64

nonce

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

226
    nonce: U256

max_priority_fee_per_gas

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

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

236
    max_fee_per_gas: Uint

gas

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

242
    gas: Uint

to

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

247
    to: Bytes0 | Address

value

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

253
    value: U256

data

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

258
    data: Bytes

access_list

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

264
    access_list: Tuple[Access, ...]

y_parity

The recovery id of the signature.

270
    y_parity: U256

r

The first part of the signature.

275
    r: U256

s

The second part of the signature.

280
    s: U256

BlobTransaction

The transaction type added in EIP-4844.

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

286
@slotted_freezable
287
@dataclass
class BlobTransaction:

chain_id

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

298
    chain_id: U64

nonce

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

303
    nonce: U256

max_priority_fee_per_gas

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

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

313
    max_fee_per_gas: Uint

gas

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

319
    gas: Uint

to

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

324
    to: Address

value

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

330
    value: U256

data

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

335
    data: Bytes

access_list

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

341
    access_list: Tuple[Access, ...]

max_fee_per_blob_gas

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

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

352
    blob_versioned_hashes: Tuple[VersionedHash, ...]

y_parity

The recovery id of the signature.

358
    y_parity: U256

r

The first part of the signature.

363
    r: U256

s

The second part of the signature.

368
    s: U256

Transaction

Union type representing any valid transaction type.

374
Transaction = (
375
    LegacyTransaction
376
    | AccessListTransaction
377
    | FeeMarketTransaction
378
    | BlobTransaction
379
)

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:
386
    """
387
    Encode a transaction into its RLP or typed transaction format.
388
    Needed because non-legacy transactions aren't RLP.
389
390
    Legacy transactions are returned as-is, while other transaction types
391
    are prefixed with their type identifier and RLP encoded.
392
    """
393
    if isinstance(tx, LegacyTransaction):
394
        return tx
395
    elif isinstance(tx, AccessListTransaction):
396
        return b"\x01" + rlp.encode(tx)
397
    elif isinstance(tx, FeeMarketTransaction):
398
        return b"\x02" + rlp.encode(tx)
399
    elif isinstance(tx, BlobTransaction):
400
        return b"\x03" + rlp.encode(tx)
401
    else:
402
        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:
406
    """
407
    Decode a transaction from its RLP or typed transaction format.
408
    Needed because non-legacy transactions aren't RLP.
409
410
    Legacy transactions are returned as-is, while other transaction types
411
    are decoded based on their type identifier prefix.
412
    """
413
    if isinstance(tx, Bytes):
414
        if tx[0] == 1:
415
            return rlp.decode_to(AccessListTransaction, tx[1:])
416
        elif tx[0] == 2:
417
            return rlp.decode_to(FeeMarketTransaction, tx[1:])
418
        elif tx[0] == 3:
419
            return rlp.decode_to(BlobTransaction, tx[1:])
420
        else:
421
            raise TransactionTypeError(tx[0])
422
    else:
423
        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 an InsufficientTransactionGasError exception if the transaction does not provide enough gas to cover the intrinsic cost, 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.

def validate_transaction(tx: Transaction) -> Uint:
427
    """
428
    Verifies a transaction.
429
430
    The gas in a transaction gets used to pay for the intrinsic cost of
431
    operations, therefore if there is insufficient gas then it would not
432
    be possible to execute a transaction and it will be declared invalid.
433
434
    Additionally, the nonce of a transaction must not equal or exceed the
435
    limit defined in [EIP-2681].
436
    In practice, defining the limit as ``2**64-1`` has no impact because
437
    sending ``2**64-1`` transactions is improbable. It's not strictly
438
    impossible though, ``2**64-1`` transactions is the entire capacity of the
439
    Ethereum blockchain at 2022 gas limits for a little over 22 years.
440
441
    Also, the code size of a contract creation transaction must be within
442
    limits of the protocol.
443
444
    This function takes a transaction as a parameter and returns the intrinsic
445
    gas cost of the transaction after validation. It throws an
446
    `InsufficientTransactionGasError` exception if the transaction does not
447
    provide enough gas to cover the intrinsic cost, and a `NonceOverflowError`
448
    exception if the nonce is greater than `2**64 - 2`. It also raises an
449
    `InitCodeTooLargeError` if the code size of a contract creation transaction
450
    exceeds the maximum allowed size.
451
452
    [EIP-2681]: https://eips.ethereum.org/EIPS/eip-2681
453
    """
454
    from .vm.interpreter import MAX_INIT_CODE_SIZE
455
456
    intrinsic_gas = calculate_intrinsic_cost(tx)
457
    if intrinsic_gas > tx.gas:
458
        raise InsufficientTransactionGasError("Insufficient gas")
459
    if U256(tx.nonce) >= U256(U64.MAX_VALUE):
460
        raise NonceOverflowError("Nonce too high")
461
    if tx.to == Bytes0(b"") and len(tx.data) > MAX_INIT_CODE_SIZE:
462
        raise InitCodeTooLargeError("Code size too large")
463
464
    return intrinsic_gas

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_COST)

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

  3. Cost for contract creation (if applicable)

  4. Cost for access list entries (if applicable)

This function takes a transaction as a parameter and returns the intrinsic gas cost of the transaction.

def calculate_intrinsic_cost(tx: Transaction) -> Uint:
468
    """
469
    Calculates the gas that is charged before execution is started.
470
471
    The intrinsic cost of the transaction is charged before execution has
472
    begun. Functions/operations in the EVM cost money to execute so this
473
    intrinsic cost is for the operations that need to be paid for as part of
474
    the transaction. Data transfer, for example, is part of this intrinsic
475
    cost. It costs ether to send data over the wire and that ether is
476
    accounted for in the intrinsic cost calculated in this function. This
477
    intrinsic cost must be calculated and paid for before execution in order
478
    for all operations to be implemented.
479
480
    The intrinsic cost includes:
481
    1. Base cost (`TX_BASE_COST`)
482
    2. Cost for data (zero and non-zero bytes)
483
    3. Cost for contract creation (if applicable)
484
    4. Cost for access list entries (if applicable)
485
486
    This function takes a transaction as a parameter and returns the intrinsic
487
    gas cost of the transaction.
488
    """
489
    from .vm.gas import init_code_cost
490
491
    data_cost = Uint(0)
492
493
    for byte in tx.data:
494
        if byte == 0:
495
            data_cost += TX_DATA_COST_PER_ZERO
496
        else:
497
            data_cost += TX_DATA_COST_PER_NON_ZERO
498
499
    if tx.to == Bytes0(b""):
500
        create_cost = TX_CREATE_COST + init_code_cost(ulen(tx.data))
501
    else:
502
        create_cost = Uint(0)
503
504
    access_list_cost = Uint(0)
505
    if isinstance(
506
        tx, (AccessListTransaction, FeeMarketTransaction, BlobTransaction)
507
    ):
508
        for access in tx.access_list:
509
            access_list_cost += TX_ACCESS_LIST_ADDRESS_COST
510
            access_list_cost += (
511
                ulen(access.slots) * TX_ACCESS_LIST_STORAGE_KEY_COST
512
            )
513
514
    return TX_BASE_COST + data_cost + create_cost + access_list_cost

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(chain_id: U64, ​​tx: Transaction) -> Address:
518
    """
519
    Extracts the sender address from a transaction.
520
521
    The v, r, and s values are the three parts that make up the signature
522
    of a transaction. In order to recover the sender of a transaction the two
523
    components needed are the signature (``v``, ``r``, and ``s``) and the
524
    signing hash of the transaction. The sender's public key can be obtained
525
    with these two values and therefore the sender address can be retrieved.
526
527
    This function takes chain_id and a transaction as parameters and returns
528
    the address of the sender of the transaction. It raises an
529
    `InvalidSignatureError` if the signature values (r, s, v) are invalid.
530
    """
531
    r, s = tx.r, tx.s
532
    if U256(0) >= r or r >= SECP256K1N:
533
        raise InvalidSignatureError("bad r")
534
    if U256(0) >= s or s > SECP256K1N // U256(2):
535
        raise InvalidSignatureError("bad s")
536
537
    if isinstance(tx, LegacyTransaction):
538
        v = tx.v
539
        if v == 27 or v == 28:
540
            public_key = secp256k1_recover(
541
                r, s, v - U256(27), signing_hash_pre155(tx)
542
            )
543
        else:
544
            chain_id_x2 = U256(chain_id) * U256(2)
545
            if v != U256(35) + chain_id_x2 and v != U256(36) + chain_id_x2:
546
                raise InvalidSignatureError("bad v")
547
            public_key = secp256k1_recover(
548
                r,
549
                s,
550
                v - U256(35) - chain_id_x2,
551
                signing_hash_155(tx, chain_id),
552
            )
553
    elif isinstance(tx, AccessListTransaction):
554
        if tx.y_parity not in (U256(0), U256(1)):
555
            raise InvalidSignatureError("bad y_parity")
556
        public_key = secp256k1_recover(
557
            r, s, tx.y_parity, signing_hash_2930(tx)
558
        )
559
    elif isinstance(tx, FeeMarketTransaction):
560
        if tx.y_parity not in (U256(0), U256(1)):
561
            raise InvalidSignatureError("bad y_parity")
562
        public_key = secp256k1_recover(
563
            r, s, tx.y_parity, signing_hash_1559(tx)
564
        )
565
    elif isinstance(tx, BlobTransaction):
566
        if tx.y_parity not in (U256(0), U256(1)):
567
            raise InvalidSignatureError("bad y_parity")
568
        public_key = secp256k1_recover(
569
            r, s, tx.y_parity, signing_hash_4844(tx)
570
        )
571
572
    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:
576
    """
577
    Compute the hash of a transaction used in a legacy (pre [EIP-155])
578
    signature.
579
580
    This function takes a legacy transaction as a parameter and returns the
581
    signing hash of the transaction.
582
583
    [EIP-155]: https://eips.ethereum.org/EIPS/eip-155
584
    """
585
    return keccak256(
586
        rlp.encode(
587
            (
588
                tx.nonce,
589
                tx.gas_price,
590
                tx.gas,
591
                tx.to,
592
                tx.value,
593
                tx.data,
594
            )
595
        )
596
    )

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:
600
    """
601
    Compute the hash of a transaction used in a [EIP-155] signature.
602
603
    This function takes a legacy transaction and a chain ID as parameters
604
    and returns the hash of the transaction used in an [EIP-155] signature.
605
606
    [EIP-155]: https://eips.ethereum.org/EIPS/eip-155
607
    """
608
    return keccak256(
609
        rlp.encode(
610
            (
611
                tx.nonce,
612
                tx.gas_price,
613
                tx.gas,
614
                tx.to,
615
                tx.value,
616
                tx.data,
617
                chain_id,
618
                Uint(0),
619
                Uint(0),
620
            )
621
        )
622
    )

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:
626
    """
627
    Compute the hash of a transaction used in a [EIP-2930] signature.
628
629
    This function takes an access list transaction as a parameter
630
    and returns the hash of the transaction used in an [EIP-2930] signature.
631
632
    [EIP-2930]: https://eips.ethereum.org/EIPS/eip-2930
633
    """
634
    return keccak256(
635
        b"\x01"
636
        + rlp.encode(
637
            (
638
                tx.chain_id,
639
                tx.nonce,
640
                tx.gas_price,
641
                tx.gas,
642
                tx.to,
643
                tx.value,
644
                tx.data,
645
                tx.access_list,
646
            )
647
        )
648
    )

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:
652
    """
653
    Compute the hash of a transaction used in an [EIP-1559] signature.
654
655
    This function takes a fee market transaction as a parameter
656
    and returns the hash of the transaction used in an [EIP-1559] signature.
657
658
    [EIP-1559]: https://eips.ethereum.org/EIPS/eip-1559
659
    """
660
    return keccak256(
661
        b"\x02"
662
        + rlp.encode(
663
            (
664
                tx.chain_id,
665
                tx.nonce,
666
                tx.max_priority_fee_per_gas,
667
                tx.max_fee_per_gas,
668
                tx.gas,
669
                tx.to,
670
                tx.value,
671
                tx.data,
672
                tx.access_list,
673
            )
674
        )
675
    )

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:
679
    """
680
    Compute the hash of a transaction used in an [EIP-4844] signature.
681
682
    This function takes a transaction as a parameter and returns the
683
    signing hash of the transaction used in an [EIP-4844] signature.
684
685
    [EIP-4844]: https://eips.ethereum.org/EIPS/eip-4844
686
    """
687
    return keccak256(
688
        b"\x03"
689
        + rlp.encode(
690
            (
691
                tx.chain_id,
692
                tx.nonce,
693
                tx.max_priority_fee_per_gas,
694
                tx.max_fee_per_gas,
695
                tx.gas,
696
                tx.to,
697
                tx.value,
698
                tx.data,
699
                tx.access_list,
700
                tx.max_fee_per_blob_gas,
701
                tx.blob_versioned_hashes,
702
            )
703
        )
704
    )

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:
708
    """
709
    Compute the hash of a transaction.
710
711
    This function takes a transaction as a parameter and returns the
712
    keccak256 hash of the transaction. It can handle both legacy transactions
713
    and typed transactions (`AccessListTransaction`, `FeeMarketTransaction`,
714
    etc.).
715
    """
716
    assert isinstance(tx, (LegacyTransaction, Bytes))
717
    if isinstance(tx, LegacyTransaction):
718
        return keccak256(rlp.encode(tx))
719
    else:
720
        return keccak256(tx)