ethereum.berlin.transactionsethereum.london.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.

21
TX_BASE_COST = Uint(21000)

TX_DATA_COST_PER_NON_ZERO

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

27
TX_DATA_COST_PER_NON_ZERO = Uint(16)

TX_DATA_COST_PER_ZERO

Gas cost per zero byte in the transaction data.

32
TX_DATA_COST_PER_ZERO = Uint(4)

TX_CREATE_COST

Additional gas cost for creating a new contract.

37
TX_CREATE_COST = Uint(32000)

TX_ACCESS_LIST_ADDRESS_COST

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

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

47
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, and EIP-2930.

53
@slotted_freezable
54
@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
@slotted_freezable
113
@dataclass
class Access:

account

The address of the account that is accessed.

120
    account: Address

slots

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

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

131
@slotted_freezable
132
@dataclass
class AccessListTransaction:

chain_id

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

144
    chain_id: U64

nonce

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

149
    nonce: U256

gas_price

The price of gas for this transaction.

154
    gas_price: Uint

gas

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

159
    gas: Uint

to

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

164
    to: Bytes0 | Address

value

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

170
    value: U256

data

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

175
    data: Bytes

access_list

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

181
    access_list: Tuple[Access, ...]

y_parity

The recovery id of the signature.

187
    y_parity: U256

r

The first part of the signature.

192
    r: U256

s

The second part of the signature.

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

203
@slotted_freezable
204
@dataclass
class FeeMarketTransaction:

chain_id

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

215
    chain_id: U64

nonce

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

220
    nonce: U256

max_priority_fee_per_gas

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

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

230
    max_fee_per_gas: Uint

gas

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

236
    gas: Uint

to

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

241
    to: Bytes0 | Address

value

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

247
    value: U256

data

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

252
    data: Bytes

access_list

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

258
    access_list: Tuple[Access, ...]

y_parity

The recovery id of the signature.

264
    y_parity: U256

r

The first part of the signature.

269
    r: U256

s

The second part of the signature.

274
    s: U256

Transaction

Union type representing any valid transaction type.

202
Transaction = LegacyTransaction | AccessListTransaction
280
Transaction = LegacyTransaction | AccessListTransaction | FeeMarketTransaction

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:
287
    """
288
    Encode a transaction into its RLP or typed transaction format.
289
    Needed because non-legacy transactions aren't RLP.
290
291
    Legacy transactions are returned as-is, while other transaction types
292
    are prefixed with their type identifier and RLP encoded.
293
    """
294
    if isinstance(tx, LegacyTransaction):
295
        return tx
296
    elif isinstance(tx, AccessListTransaction):
297
        return b"\x01" + rlp.encode(tx)
220
    else:
221
        raise Exception(f"Unable to encode transaction of type {type(tx)}")
298
    elif isinstance(tx, FeeMarketTransaction):
299
        return b"\x02" + rlp.encode(tx)
300
    else:
301
        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:
305
    """
306
    Decode a transaction from its RLP or typed transaction format.
307
    Needed because non-legacy transactions aren't RLP.
308
309
    Legacy transactions are returned as-is, while other transaction types
310
    are decoded based on their type identifier prefix.
311
    """
312
    if isinstance(tx, Bytes):
233
        if tx[0] != 1:
234
            raise TransactionTypeError(tx[0])
235
        return rlp.decode_to(AccessListTransaction, tx[1:])
313
        if tx[0] == 1:
314
            return rlp.decode_to(AccessListTransaction, tx[1:])
315
        elif tx[0] == 2:
316
            return rlp.decode_to(FeeMarketTransaction, tx[1:])
317
        else:
318
            raise TransactionTypeError(tx[0])
319
    else:
320
        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.

This function takes a transaction as a parameter and returns the intrinsic gas cost of the transaction after validation. It throws an InvalidTransaction exception if the transaction is invalid.

def validate_transaction(tx: Transaction) -> Uint:
324
    """
325
    Verifies a transaction.
326
327
    The gas in a transaction gets used to pay for the intrinsic cost of
328
    operations, therefore if there is insufficient gas then it would not
329
    be possible to execute a transaction and it will be declared invalid.
330
331
    Additionally, the nonce of a transaction must not equal or exceed the
332
    limit defined in [EIP-2681].
333
    In practice, defining the limit as ``2**64-1`` has no impact because
334
    sending ``2**64-1`` transactions is improbable. It's not strictly
335
    impossible though, ``2**64-1`` transactions is the entire capacity of the
336
    Ethereum blockchain at 2022 gas limits for a little over 22 years.
337
338
    This function takes a transaction as a parameter and returns the intrinsic
339
    gas cost of the transaction after validation. It throws an
340
    `InvalidTransaction` exception if the transaction is invalid.
341
342
    [EIP-2681]: https://eips.ethereum.org/EIPS/eip-2681
343
    """
344
    intrinsic_gas = calculate_intrinsic_cost(tx)
345
    if intrinsic_gas > tx.gas:
346
        raise InvalidTransaction("Insufficient gas")
347
    if U256(tx.nonce) >= U256(U64.MAX_VALUE):
348
        raise InvalidTransaction("Nonce too high")
349
    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:
353
    """
354
    Calculates the gas that is charged before execution is started.
355
356
    The intrinsic cost of the transaction is charged before execution has
357
    begun. Functions/operations in the EVM cost money to execute so this
358
    intrinsic cost is for the operations that need to be paid for as part of
359
    the transaction. Data transfer, for example, is part of this intrinsic
360
    cost. It costs ether to send data over the wire and that ether is
361
    accounted for in the intrinsic cost calculated in this function. This
362
    intrinsic cost must be calculated and paid for before execution in order
363
    for all operations to be implemented.
364
365
    The intrinsic cost includes:
366
    1. Base cost (`TX_BASE_COST`)
367
    2. Cost for data (zero and non-zero bytes)
368
    3. Cost for contract creation (if applicable)
369
    4. Cost for access list entries (if applicable)
370
371
    This function takes a transaction as a parameter and returns the intrinsic
372
    gas cost of the transaction.
373
    """
374
    data_cost = Uint(0)
375
376
    for byte in tx.data:
377
        if byte == 0:
378
            data_cost += TX_DATA_COST_PER_ZERO
379
        else:
380
            data_cost += TX_DATA_COST_PER_NON_ZERO
381
382
    if tx.to == Bytes0(b""):
383
        create_cost = TX_CREATE_COST
384
    else:
385
        create_cost = Uint(0)
386
387
    access_list_cost = Uint(0)
305
    if isinstance(tx, AccessListTransaction):
388
    if isinstance(tx, (AccessListTransaction, FeeMarketTransaction)):
389
        for access in tx.access_list:
390
            access_list_cost += TX_ACCESS_LIST_ADDRESS_COST
391
            access_list_cost += (
392
                ulen(access.slots) * TX_ACCESS_LIST_STORAGE_KEY_COST
393
            )
394
395
    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:
399
    """
400
    Extracts the sender address from a transaction.
401
402
    The v, r, and s values are the three parts that make up the signature
403
    of a transaction. In order to recover the sender of a transaction the two
404
    components needed are the signature (``v``, ``r``, and ``s``) and the
405
    signing hash of the transaction. The sender's public key can be obtained
406
    with these two values and therefore the sender address can be retrieved.
407
408
    This function takes chain_id and a transaction as parameters and returns
409
    the address of the sender of the transaction. It raises an
410
    `InvalidSignatureError` if the signature values (r, s, v) are invalid.
411
    """
412
    r, s = tx.r, tx.s
413
    if U256(0) >= r or r >= SECP256K1N:
414
        raise InvalidSignatureError("bad r")
415
    if U256(0) >= s or s > SECP256K1N // U256(2):
416
        raise InvalidSignatureError("bad s")
417
418
    if isinstance(tx, LegacyTransaction):
419
        v = tx.v
420
        if v == 27 or v == 28:
421
            public_key = secp256k1_recover(
422
                r, s, v - U256(27), signing_hash_pre155(tx)
423
            )
424
        else:
425
            chain_id_x2 = U256(chain_id) * U256(2)
426
            if v != U256(35) + chain_id_x2 and v != U256(36) + chain_id_x2:
427
                raise InvalidSignatureError("bad v")
428
            public_key = secp256k1_recover(
429
                r,
430
                s,
431
                v - U256(35) - chain_id_x2,
432
                signing_hash_155(tx, chain_id),
433
            )
434
    elif isinstance(tx, AccessListTransaction):
435
        if tx.y_parity not in (U256(0), U256(1)):
436
            raise InvalidSignatureError("bad y_parity")
437
        public_key = secp256k1_recover(
438
            r, s, tx.y_parity, signing_hash_2930(tx)
356
        )
439
        )
440
    elif isinstance(tx, FeeMarketTransaction):
441
        if tx.y_parity not in (U256(0), U256(1)):
442
            raise InvalidSignatureError("bad y_parity")
443
        public_key = secp256k1_recover(
444
            r, s, tx.y_parity, signing_hash_1559(tx)
445
        )
446
447
    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 transaction as a parameter and returns theThis function takes a legacy transaction as a parameter and returns the hash of the transaction used in a legacy signature.signing hash of the transaction.

def signing_hash_pre155(tx: TransactionLegacyTransaction) -> Hash32:
451
    """
452
    Compute the hash of a transaction used in a legacy (pre [EIP-155])
453
    signature.
454
366
    This function takes a transaction as a parameter and returns the
367
    hash of the transaction used in a legacy signature.
455
    This function takes a legacy transaction as a parameter and returns the
456
    signing hash of the transaction.
457
458
    [EIP-155]: https://eips.ethereum.org/EIPS/eip-155
459
    """
460
    return keccak256(
461
        rlp.encode(
462
            (
463
                tx.nonce,
464
                tx.gas_price,
465
                tx.gas,
466
                tx.to,
467
                tx.value,
468
                tx.data,
469
            )
470
        )
471
    )

signing_hash_155

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

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

def signing_hash_155(tx: TransactionLegacyTransaction, ​​chain_id: U64) -> Hash32:
475
    """
476
    Compute the hash of a transaction used in a [EIP-155] signature.
477
389
    This function takes a transaction and chain ID as parameters and returns
390
    the hash of the transaction used in a [EIP-155] signature.
478
    This function takes a legacy transaction and a chain ID as parameters
479
    and returns the hash of the transaction used in an [EIP-155] signature.
480
481
    [EIP-155]: https://eips.ethereum.org/EIPS/eip-155
482
    """
483
    return keccak256(
484
        rlp.encode(
485
            (
486
                tx.nonce,
487
                tx.gas_price,
488
                tx.gas,
489
                tx.to,
490
                tx.value,
491
                tx.data,
492
                chain_id,
493
                Uint(0),
494
                Uint(0),
495
            )
496
        )
497
    )

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:
501
    """
502
    Compute the hash of a transaction used in a [EIP-2930] signature.
503
504
    This function takes an access list transaction as a parameter
505
    and returns the hash of the transaction used in an [EIP-2930] signature.
506
507
    [EIP-2930]: https://eips.ethereum.org/EIPS/eip-2930
508
    """
509
    return keccak256(
510
        b"\x01"
511
        + rlp.encode(
512
            (
513
                tx.chain_id,
514
                tx.nonce,
515
                tx.gas_price,
516
                tx.gas,
517
                tx.to,
518
                tx.value,
519
                tx.data,
520
                tx.access_list,
521
            )
522
        )
523
    )

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:
527
    """
528
    Compute the hash of a transaction used in an [EIP-1559] signature.
529
530
    This function takes a fee market transaction as a parameter
531
    and returns the hash of the transaction used in an [EIP-1559] signature.
532
533
    [EIP-1559]: https://eips.ethereum.org/EIPS/eip-1559
534
    """
535
    return keccak256(
536
        b"\x02"
537
        + rlp.encode(
538
            (
539
                tx.chain_id,
540
                tx.nonce,
541
                tx.max_priority_fee_per_gas,
542
                tx.max_fee_per_gas,
543
                tx.gas,
544
                tx.to,
545
                tx.value,
546
                tx.data,
547
                tx.access_list,
548
            )
549
        )
550
    )

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 (eg. and typed transactions (AccessListTransaction)., FeeMarketTransaction, etc.).

def get_transaction_hash(tx: Bytes | LegacyTransaction) -> Hash32:
554
    """
555
    Compute the hash of a transaction.
556
557
    This function takes a transaction as a parameter and returns the
558
    keccak256 hash of the transaction. It can handle both legacy transactions
443
    and typed transactions (eg. `AccessListTransaction`).
559
    and typed transactions (`AccessListTransaction`, `FeeMarketTransaction`,
560
    etc.).
561
    """
562
    assert isinstance(tx, (LegacyTransaction, Bytes))
563
    if isinstance(tx, LegacyTransaction):
564
        return keccak256(rlp.encode(tx))
565
    else:
566
        return keccak256(tx)