Web3.py Patterns - Decoding Signed Transactions
Web3.py Patterns - Decoding Signed Transactions
Web3.py
There's a small set of use cases where you might need to decode a signed
transaction which has not yet been included in a block. For example, MEV
protocols work with bundles of signed transactions separate from the main
transaction pool. If that series of words means nothing to you, there's a
reasonably good chance that you don't need the contents of this blog post and are
instead interested in fetching mined transaction data. So, let's start there.
w3 = Web3(HTTPProvider('...'))
w3.eth.get_transaction('0x5c504ed432cb51138bcf09aa5e8a410dd4a1e204ef84bfed1be16d
# AttributeDict({
# 'hash': HexBytes('0x5c504...'),
# 'blockHash': HexBytes('0x4e3a3...'),
# 'blockNumber': 46147,
# 'from': '0xA1E43...',
# 'gas': 21000,
# 'gasPrice': 50000000000000,
# 'input': '0x',
# 'nonce': 0,
# 'r': HexBytes('0x88ff6...'),
# 's': HexBytes('0x45e0a...'),
# 'to': '0x5DF9B...',
# 'transactionIndex': 0,
# 'type': '0x0',
# 'v': 28,
# 'value': 31337
# })
Under the hood, the logic for decoding transactions now needs to account for
"typed transactions," which were introduced to Ethereum in the Berlin network
upgrade. Legacy transactions continue to be supported after the upgrades, but
typed transactions have a dedicated range of values for the first byte of the
transaction hash. EIP-1559 transactions, for example, have transaction type of
0x02 , followed by the rlp-encoded transaction body: 0x02 || rlp([chain_id,
nonce, amount, data, ...]) .
By definition, each typed transaction has a unique data payload that must be
encoded and decoded. These mappings are collectively known as sedes, short for
serialization/deserialization. Luckily for us, py-evm hides these implementation
details within a TransactionBuilder class.
Putting it all together – the code below converts the transaction hash to bytes,
then decodes the payload with the latest TransactionBuilder from py-evm.
https://snakecharmers.ethereum.org/web3-py-patterns-decoding-signed-transactions/ 1/2
5/30/24, 8:03 PM Web3.py Patterns: Decoding Signed Transactions
Powered by Ghost
https://snakecharmers.ethereum.org/web3-py-patterns-decoding-signed-transactions/ 2/2