-
-
Save banteg/49b45f574e850f13b46e609cba143806 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from typing import Any, Optional, Type | |
from devtools import debug | |
from msgspec import Struct | |
from msgspec.json import Decoder | |
class uint(int): | |
pass | |
class address(str): | |
pass | |
class hexbytes(bytes): | |
pass | |
def dec_hook(type: Type, obj: Any) -> Any: | |
if type is uint: | |
return uint(obj, 16) | |
if type is hexbytes: | |
return hexbytes.fromhex(obj[2:]) | |
if type is address and obj: | |
return address(obj.upper()) | |
renames = { | |
"sender": "from", | |
"max_fee": "maxFeePerGas", | |
"max_priority_fee": "maxPriorityFeePerGas", | |
} | |
rename_fn = lambda item: renames.get(item, item) | |
class TransactionBase(Struct, rename=rename_fn): | |
# the `type` field is omitted since it's used in the tagged union | |
sender: address | |
to: Optional[address] = None # <-- this works with str but not a subclass of str | |
class Transaction1559(TransactionBase, tag="0x2"): | |
max_fee: uint | |
max_priority_fee: uint | |
Transaction = Transaction1559 # | other types omitted here | |
samples = [ | |
b'{"from":"0xbe2cba3fe1b4287226c6f6d9d187891dab00b033","maxPriorityFeePerGas":"0x59682f00","maxFeePerGas":"0x4a817c800","to":"0xcc7c7d5dd10a2573a707cae403b3e40eb20fcd0c","type":"0x2"}', | |
b'{"from":"0xac9d54ca08740a608b6c474e5ca07d51ca8117fa","maxPriorityFeePerGas":"0x59682f00","maxFeePerGas":"0x59c3553db","to":null,"type":"0x2"}', | |
] | |
for sample in samples: | |
tx = Decoder(Transaction, dec_hook=dec_hook).decode(sample) | |
debug(tx) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment