Skip to content

Instantly share code, notes, and snippets.

  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save miohtama/3dcb8425c0a1d8a6daba8036a9d7937a to your computer and use it in GitHub Desktop.
Ethereum address to for SQLAlchemy
class EthereumAddress(types.TypeDecorator):
"""SQLAlchemy class to store Ethereum addresses as binary in SQL database.
Ethereum address is 160 bits, the last bytes of 256 bit public key of the address's signer.
Ethereum address checksum is encoded in the case of hex letters.
We skip any Ethereum address checksum checks, as they slow down large data processing too much.
Any returned address data will be in lowercase.
"""
# Address is 20 bytes (160 bits)
impl = types.LargeBinary(20)
cache_ok = True
def load_dialect_impl(self, dialect):
return dialect.type_descriptor(types.LargeBinary(20))
def process_bind_param(self, val: str, dialect):
assert val.startswith("0x"), f"Bad Ethereum address {val}"
val = bytearray.fromhex(val[2:])
assert len(val) == 20, f"Ethereum address length not 160 bits: {val}"
return val
def process_result_value(self, val: bytes, dialect):
assert type(val) == bytes
assert len(val) == 20
return "0x" + bytearray(val).hex()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment