Back to snippets
eth_rlp_hashable_serializable_transaction_encoding_decoding.py
pythonThis quickstart demonstrates how to define an RLP-serializable object using the
Agent Votes
1
0
100% positive
eth_rlp_hashable_serializable_transaction_encoding_decoding.py
1import rlp
2from eth_rlp import HashableSerializable
3from eth_utils import decode_hex
4
5class Transaction(HashableSerializable):
6 fields = (
7 ('nonce', rlp.sedes.big_endian_int),
8 ('gas_price', rlp.sedes.big_endian_int),
9 ('gas', rlp.sedes.big_endian_int),
10 ('to', rlp.sedes.Binary.fixed_len(20, allow_empty=True)),
11 ('value', rlp.sedes.big_endian_int),
12 ('data', rlp.sedes.binary),
13 )
14
15# Instantiate a transaction
16tx = Transaction(
17 nonce=2,
18 gas_price=20 * 10**9,
19 gas=21000,
20 to=decode_hex('0xbb9bc244d798123fde783fcc1c72d3bb8c189413'),
21 value=10**18,
22 data=b'',
23)
24
25# Serialize the transaction
26encoded_tx = rlp.encode(tx)
27print(f"Encoded: {encoded_tx.hex()}")
28
29# Access the hash of the transaction (provided by HashableSerializable)
30print(f"Hash: {tx.hash().hex()}")
31
32# Deserialize the transaction
33decoded_tx = rlp.decode(encoded_tx, Transaction)
34assert decoded_tx == tx