### Create Custom Hex Types by Subclassing HexStr32 Source: https://github.com/apeworx/eth-pydantic-types/blob/main/README.md Build custom hex types by subclassing existing types like HexStr32 and overriding validation logic. This example creates a 32-byte hash type without the '0x' prefix. ```python from pydantic import BaseModel from pydantic_core.core_schema import with_info_before_validator_function, str_schema from eth_pydantic_types import HexStr32 class MyAddress(HexStr32): @classmethod def __get_pydantic_core_schema__(cls, value, handler=None): str_size = cls.size * 2 return with_info_before_validator_function( cls.__eth_pydantic_validate__, str_schema(max_length=str_size, min_length=str_size), ) @classmethod def __eth_pydantic_validate__(cls, value, info=None, **kwargs): return super().__eth_pydantic_validate__(value, info=info, prefixed=False, **kwargs) class MyModel(BaseModel): address: MyAddress model = MyModel(address="0x" + "ab" * 32) ``` -------------------------------- ### Control Padding for HexStr and HexBytes with field_validator Source: https://github.com/apeworx/eth-pydantic-types/blob/main/README.md Customize padding for HexStr and HexBytes types using Pydantic's @field_validator. This example demonstrates right-padding for HexStr20 and HexBytes20. ```python from pydantic import BaseModel, field_validator from eth_pydantic_types import HexStr20, HexBytes20 from eth_pydantic_types.utils import Pad class MyModel(BaseModel): my_str: HexStr20 my_bytes: HexBytes20 @field_validator("my_str", "my_bytes", mode="before") @classmethod def validate_value(cls, value, info): field_type = cls.model_fields[info.field_name].annotation return field_type.__eth_pydantic_validate__(value, pad=Pad.RIGHT) ``` -------------------------------- ### Pydantic Model with Field Validator for Padding Source: https://context7.com/apeworx/eth-pydantic-types/llms.txt Demonstrates using a Pydantic field_validator with HexStr20 and __eth_pydantic_validate__ to automatically pad the selector on model instantiation. ```python from pydantic import BaseModel, field_validator from eth_pydantic_types import HexStr20 class TokenSelector(BaseModel): selector: HexStr20 @field_validator("selector", mode="before") @classmethod def pad_right(cls, value, info): field_type = cls.model_fields[info.field_name].annotation return field_type.__eth_pydantic_validate__(value, pad=PadDirection.RIGHT) m = TokenSelector(selector=1) print(m.selector) # "0x0100000000000000000000000000000000000000" ``` -------------------------------- ### Utilize Padding and Validation Utilities Source: https://context7.com/apeworx/eth-pydantic-types/llms.txt Use PadDirection enum and utility functions like validate_hex_str, validate_str_size, validate_bytes_size, and validate_int_size for custom validation logic in Ethereum data types. ```python from eth_pydantic_types.utils import ( PadDirection, validate_hex_str, validate_str_size, validate_bytes_size, validate_int_size, ) # validate_hex_str — normalise any hex string to 0x-prefixed, lowercase, even length print(validate_hex_str("abc")) # "0x0abc" print(validate_hex_str("0xABCDEF")) # "0xabcdef" ``` -------------------------------- ### HexInt - Integer Stored as Hex Source: https://context7.com/apeworx/eth-pydantic-types/llms.txt Use HexInt for integer fields that should serialize to minimal 0x-prefixed hex strings without zero-padding. It accepts hex strings, integers, and bytes as input. ```python from pydantic import BaseModel, ValidationError from eth_pydantic_types.hex import HexInt class TransactionRequest(BaseModel): nonce: HexInt gas: HexInt gas_price: HexInt tx = TransactionRequest(nonce="0x123", gas=21000, gas_price=b"\x04\xa8\x17\xc8\x00") print(tx.nonce) # 291 (int) print(tx.gas) # 21000 print(isinstance(tx.nonce, int)) # True # Serialises to minimal hex (no leading zeros) print(tx.model_dump()) # {'nonce': '0x123', 'gas': '0x5208', 'gas_price': '0x4a817c800'} print(tx.model_dump_json()) # '{"nonce":"0x123","gas":"0x5208","gas_price":"0x4a817c800"}' # Invalid try: TransactionRequest(nonce="not-a-number", gas=0, gas_price=0) except ValidationError as e: print(e) # JSON schema import json schema = TransactionRequest.model_json_schema() print(schema["properties"]["nonce"]["type"]) # "integer" ``` -------------------------------- ### Validate and Pad Bytes Source: https://context7.com/apeworx/eth-pydantic-types/llms.txt Use validate_bytes_size to pad or validate bytes to an exact byte count. Specify the padding direction using PadDirection. ```python print(validate_bytes_size(b"\xff", 4, pad_direction=PadDirection.LEFT)) # b'\x00\x00\x00\xff' print(validate_bytes_size(b"\xff", 4, pad_direction=PadDirection.RIGHT)) # b'\xff\x00\x00\x00' ``` -------------------------------- ### HexInt32/UInt256 - Size-Bounded Integer Fields Source: https://context7.com/apeworx/eth-pydantic-types/llms.txt Employ HexInt32 or its alias UInt256 for 32-byte bounded integers that serialize to zero-padded 64-hex-character strings. Subclass BoundHexInt for custom integer widths. ```python from typing import ClassVar from pydantic import BaseModel, ValidationError from eth_pydantic_types.hex import BoundHexInt, HexInt32, UInt256 class ERC20Transfer(BaseModel): amount: UInt256 block_number: HexInt32 t = ERC20Transfer(amount="0xa", block_number=10) print(t.amount) # 10 print(t.block_number) # 10 dump = t.model_dump() print(dump["amount"]) # "0x000000000000000000000000000000000000000000000000000000000000000a" print(len(dump["amount"])) # 66 (0x + 64 hex digits = 32 bytes) ``` -------------------------------- ### Validate and Pad Hex String Source: https://context7.com/apeworx/eth-pydantic-types/llms.txt Use validate_str_size to pad or validate a hex string to an exact character count. Specify the padding direction using PadDirection. ```python print(validate_str_size("ff", 8, pad_direction=PadDirection.LEFT)) # "000000ff" print(validate_str_size("ff", 8, pad_direction=PadDirection.RIGHT)) # "ff000000" ``` -------------------------------- ### Create Custom Bounded Hex Bytes Type Source: https://context7.com/apeworx/eth-pydantic-types/llms.txt Define custom types like PublicKey by subclassing BoundHexBytes and setting the `size` class variable to enforce a specific byte length for hex string representations. ```python from typing import ClassVar from pydantic import BaseModel from eth_pydantic_types.hex import BoundHexBytes, BoundHexInt # --- 64-byte public key --- class PublicKey(BoundHexBytes): size: ClassVar[int] = 64 class Wallet(BaseModel): pub_key: PublicKey wallet = Wallet(pub_key="0x" + "05" * 64) print(len(wallet.pub_key)) # 64 ``` -------------------------------- ### Create Custom Bounded Hex String Type Source: https://context7.com/apeworx/eth-pydantic-types/llms.txt Define custom types like MerkleLeaf by subclassing HexStr32 and overriding __get_pydantic_core_schema__ and __eth_pydantic_validate__ to enforce specific string lengths and prefixing rules. ```python from typing import ClassVar from pydantic import BaseModel from pydantic_core.core_schema import str_schema, with_info_before_validator_function from eth_pydantic_types import HexStr32 from eth_pydantic_types.hex import BoundHexBytes, BoundHexInt from eth_pydantic_types.utils import PadDirection # --- Unprefixed 32-byte hex string (e.g. Merkle leaf without 0x) --- class MerkleLeaf(HexStr32): @classmethod def __get_pydantic_core_schema__(cls, value, handler=None): str_size = cls.size * 2 # 64 chars, no 0x return with_info_before_validator_function( cls.__eth_pydantic_validate__, str_schema(max_length=str_size, min_length=str_size), ) @classmethod def __eth_pydantic_validate__(cls, value, info=None, **kwargs): return super().__eth_pydantic_validate__(value, info=info, prefixed=False, **kwargs) class MerkleProof(BaseModel): leaf: MerkleLeaf proof = MerkleProof(leaf="0x" + "ab" * 32) print(proof.leaf) # "abababab..." (no 0x, 64 chars) print(len(proof.leaf)) # 64 ``` -------------------------------- ### HexStr20/HexStr32: Size-Bounded Hex String Fields Source: https://context7.com/apeworx/eth-pydantic-types/llms.txt Use HexStr20 and HexStr32 for fixed-size hex strings (20 and 32 bytes). They auto-pad short inputs (right-pad for str/bytes, left-pad for integers). The `__eth_pydantic_validate__` method allows custom padding and prefix handling. ```python from pydantic import BaseModel, field_validator from eth_pydantic_types import HexStr20, HexStr32 from eth_pydantic_types.utils import PadDirection class HashModel(BaseModel): small_hash: HexStr20 # 20-byte (40 hex chars) + 0x big_hash: HexStr32 # 32-byte (64 hex chars) + 0x # Auto-pads short values (right-pad for str/bytes inputs) m = HashModel( small_hash="0xcafe", big_hash="0xdeadbeef", ) print(m.small_hash) # "0xcafe000000000000000000000000000000000000" print(m.big_hash) # "0xdeadbeef0000000000000000000000000000000000000000000000000000" # Integer inputs are left-padded m2 = HashModel(small_hash=1, big_hash=255) print(m2.small_hash) # "0x0000000000000000000000000000000000000001" print(m2.big_hash) # "0x00000000000000000000000000000000000000000000000000000000000000ff" # Force right-pad via field_validator class RightPadModel(BaseModel): slot: HexStr20 @field_validator("slot", mode="before") @classmethod def right_pad(cls, value, info): field_type = cls.model_fields[info.field_name].annotation return field_type.__eth_pydantic_validate__(value, pad=PadDirection.RIGHT) m3 = RightPadModel(slot=1) print(m3.slot) # "0x0100000000000000000000000000000000000000" # Remove the 0x prefix with prefixed=False (custom type pattern) result = HexStr32.__eth_pydantic_validate__("0x" + "ab" * 32, prefixed=False) print(result[:4]) # "abab" (no 0x) ``` -------------------------------- ### Validate and Checksum Ethereum Addresses with Address Type Source: https://github.com/apeworx/eth-pydantic-types/blob/main/README.md Use the Address type for handling Ethereum addresses. It automatically validates and checksums addresses during model construction. ```python from pydantic import BaseModel from eth_pydantic_types import Address class Account(BaseModel): address: Address # NOTE: The address ends up checksummed # ("0x0837207e343277CBd6c114a45EC0e9Ec56a1AD84") account = Account(address="0x837207e343277cbd6c114a45ec0e9ec56a1ad84") ``` -------------------------------- ### HexBytes20/HexBytes32 - Size-Bounded Bytes Fields Source: https://context7.com/apeworx/eth-pydantic-types/llms.txt Utilize HexBytes20 and HexBytes32 for fixed-size byte fields (20 and 32 bytes respectively). Short values are padded. Subclass BoundHexBytes for custom arbitrary sizes. ```python from typing import ClassVar from pydantic import BaseModel, field_validator from eth_pydantic_types import HexBytes, HexBytes32 from eth_pydantic_types.hex import BoundHexBytes from eth_pydantic_types.hex.bytes import HexBytes20 from eth_pydantic_types.utils import PadDirection # Standard 32-byte hash class TxReceipt(BaseModel): tx_hash: HexBytes32 r = TxReceipt(tx_hash="0x" + "ab" * 32) print(len(r.tx_hash)) # 32 print(r.model_dump()) # {'tx_hash': '0xabababababababababababababababababababababababababababababababababab'} # Custom size via BoundHexBytes class Account(BaseModel): pub_key: type # replaced below class PublicKey(BoundHexBytes): size: ClassVar[int] = 64 class Account(BaseModel): pub_key: PublicKey key = "0x" + "05" * 64 account = Account(pub_key=key) print(len(account.pub_key)) # 64 print(account.pub_key == HexBytes(key)) # True # Right-pad via field_validator (mirrors Solidity bytes20) class SignatureModel(BaseModel): selector: HexBytes20 @field_validator("selector", mode="before") @classmethod def right_pad_selector(cls, value, info): return HexBytes20.__eth_pydantic_validate__(value, pad=PadDirection.RIGHT) m = SignatureModel(selector=1) print(m.selector.startswith(HexBytes(1))) # True (b'\x01' at the front) ``` -------------------------------- ### Create Custom Bounded Integer Type Source: https://context7.com/apeworx/eth-pydantic-types/llms.txt Define custom integer types like ChainID by subclassing BoundHexInt and setting the `size` and `signed` class variables to enforce specific byte lengths and signedness for integer values. ```python from typing import ClassVar from pydantic import BaseModel, ValidationError from eth_pydantic_types.hex import BoundHexInt # --- 8-byte unsigned chain ID --- class ChainID(BoundHexInt): size: ClassVar[int] = 8 signed: ClassVar[bool] = False class ChainConfig(BaseModel): chain_id: ChainID cfg = ChainConfig(chain_id=11155111) # Sepolia print(cfg.model_dump_json()) # '{"chain_id":"0x0000000000aa36a7"}' # Out-of-range rejection try: ChainConfig(chain_id=-1) except ValidationError as e: print("Rejected negative chain ID") ``` -------------------------------- ### BIP-122 Blockchain URI Parsing and Validation Source: https://context7.com/apeworx/eth-pydantic-types/llms.txt Provides Bip122Uri for validating and parsing BIP-122 blockchain URIs. It ensures the genesis hash and block hash are valid hex strings and exposes parsed components like chain, URI type, and hash. Use this for representing and validating blockchain pointers. ```python from pydantic import BaseModel, ValidationError from eth_pydantic_types.bip122 import Bip122Uri, Bip122UriType GENESIS = "d4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3" BLOCK = "752820c0ad7abc1200f9ad42c4adc6fbb4bd44b5bed4667990e64565102c1ba6" class ChainPointer(BaseModel): path: Bip122Uri ptr = ChainPointer( path=f"blockchain://{GENESIS}/block/{BLOCK}" ) print(ptr.path) # "blockchain://d4e5.../block/7528..." print(type(ptr.path)) # (Bip122Uri is a str subclass) # Access parsed components via Bip122Uri directly (not the model field) uri = Bip122Uri(f"blockchain://{GENESIS}/block/{BLOCK}") print(uri.uri_type) # Bip122UriType.BLOCK print(uri.chain) # "0xd4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3" print(uri.hash) # "0x752820c0ad7abc1200f9ad42c4adc6fbb4bd44b5bed4667990e64565102c1ba6" # Supported URI types print([t.value for t in Bip122UriType]) # ['tx', 'block', 'address'] # Invalid URIs raise ValidationError for bad in [ "not-a-blockchain-uri", f"blockchain://badhash/block/{BLOCK}", ]: try: ChainPointer(path=bad) except ValidationError: print(f"Rejected: {bad!r}") # JSON schema schema = ChainPointer.model_json_schema() prop = schema["properties"]["path"] print(prop["pattern"]) # "^blockchain://[0-9a-f]{64}/block/[0-9a-f]{64}$" ``` -------------------------------- ### HexInt Source: https://github.com/apeworx/eth-pydantic-types/blob/main/docs/methoddocs/hex.md The HexInt type is used for representing hexadecimal integers. ```APIDOC ## HexInt ### Description Represents an integer value in hexadecimal format. ### Usage This type is part of the `eth_pydantic_types.hex.int` module. ``` -------------------------------- ### Checksummed Ethereum Address Validation and Checksumming Source: https://context7.com/apeworx/eth-pydantic-types/llms.txt Utilizes Address and AddressType for EIP-55 checksum validation of Ethereum addresses. Accepts various input formats including hex strings (with/without '0x' prefix), integers, and HexBytes. Leading zeros are preserved for specific use cases like Uniswap v4 pool managers. ```python from pydantic import BaseModel, ValidationError from eth_pydantic_types import Address, AddressType class Account(BaseModel): address: Address address_type: AddressType # interchangeable with Address for validation # Input variations — all produce the same checksummed output inputs = [ "0x0837207e343277CBd6c114a45EC0e9Ec56a1AD84", # already checksummed "0x0837207e343277cbd6c114a45ec0e9ec56a1ad84", # lowercase "837207e343277cbd6c114a45ec0e9ec56a1ad84", # no 0x, no leading zero int("837207e343277cbd6c114a45ec0e9ec56a1ad84", 16), ] for addr in inputs: m = Account(address=addr, address_type=addr) print(m.address) # "0x0837207e343277CBd6c114a45EC0e9Ec56a1AD84" # Leading zeroes are preserved (Uniswap v4 pool manager) pool = Account( address="04444c5dc75cb358380d2e3de08a90", address_type="04444c5dc75cb358380d2e3de08a90", ) print(pool.address) # "0x000000000004444c5dc75cB358380D2e3dE08A90" # Invalid inputs raise ValidationError for bad in ("foo", -35, "0x" + "F" * 100): try: Account(address=bad, address_type=bad) except ValidationError: print(f"Rejected: {bad!r}") # JSON schema schema = Account.model_json_schema() addr_prop = schema["properties"]["address"] print(addr_prop["pattern"]) # "^0x[a-fA-F0-9]{40}$" print(addr_prop["minLength"]) # 42 print(addr_prop["maxLength"]) # 42 # Serialization print(Account( address="837207e343277cbd6c114a45ec0e9ec56a1ad84", address_type="837207e343277cbd6c114a45ec0e9ec56a1ad84", ).model_dump()) # {'address': '0x0837207e343277CBd6c114a45EC0e9Ec56a1AD84', # 'address_type': '0x0837207e343277CBd6c114a45EC0e9Ec56a1AD84'} ``` -------------------------------- ### Define Contract Call with ABI Types Source: https://context7.com/apeworx/eth-pydantic-types/llms.txt Use ABI type aliases from eth_pydantic_types.abi to model contract call data. This includes types like address, uint256, int128, bytes4, bytes, string, and bool. Pydantic handles validation and serialization. ```python from pydantic import BaseModel, ValidationError from eth_pydantic_types import abi class ContractCallDecoded(BaseModel): recipient: abi.address amount: abi.uint256 fee: abi.int128 selector: abi.bytes4 payload: abi.bytes flag: abi.bool label: abi.string call = ContractCallDecoded( recipient="0x1e59ce931B4CFea3fe4B875411e280e173cB7A9C", amount=1_000_000 * 10**18, fee=-500, selector=b"\x12\x34\x56\x78", payload="0xdeadbeef", flag=True, label="transfer", ) print(call.recipient) # "0x1e59ce931B4CFea3fe4B875411e280e173cB7A9C" (checksummed) print(call.amount) # 1000000000000000000000000 print(call.fee) # -500 print(len(call.selector)) # 4 (bytes4 → 4 bytes) print(call.model_dump()["selector"]) # "0x12345678" # Range enforcement for uintN / intN try: ContractCallDecoded( recipient="0x1e59ce931B4CFea3fe4B875411e280e173cB7A9C", amount=-1, # uint256 must be >= 0 fee=0, selector=b"\x00"*4, payload="0x", flag=False, label="", ) except ValidationError as e: print(e) ``` ```python from eth_pydantic_types.abi import bytes32, bytes4 import json from pydantic import BaseModel class StorageSlot(BaseModel): key: bytes32 tag: bytes4 slot = StorageSlot(key="0x" + "ff" * 32, tag="0xaabbccdd") print(slot.key.hex()) # "ff" * 32 print(slot.model_dump()) ``` -------------------------------- ### Validate Integer Size Source: https://context7.com/apeworx/eth-pydantic-types/llms.txt Use validate_int_size to range-check an integer for a specified number of bytes, supporting signed or unsigned values. Raises SizeError for out-of-range values. ```python print(validate_int_size(255, 1, signed=False)) # 255 try: validate_int_size(256, 1, signed=False) # raises SizeError except Exception as e: print(e) ``` -------------------------------- ### Use HexStr and HexStr32 in Pydantic Models Source: https://github.com/apeworx/eth-pydantic-types/blob/main/README.md Use HexStr for any size hex strings and HexStr32 for fixed 32-byte hex strings in your Pydantic models. These types ensure that string inputs are valid hex representations. ```python from pydantic import BaseModel from eth_pydantic_types import HexStr, HexStr32 class TransactionData(BaseModel): hash_any_size: HexStr sized_hash: HexStr32 data = TransactionData(hash_any_size="0x123", sized_hash="0x000123") assert isinstance(data.nonce, str) assert isinstance(data.gas, str) ``` -------------------------------- ### Use Bip122Uri for BIP-122 URIs in Pydantic Models Source: https://github.com/apeworx/eth-pydantic-types/blob/main/README.md Annotate model fields with Bip122Uri to use BIP-122 URIs. This type serializes to a string and validates individual hashes within the URI. ```python from eth_pydantic_types import Bip122Uri from pydantic import BaseModel class Message(BaseModel): path: Bip122Uri message = Message( path=( "blockchain://d4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3" "/block/752820c0ad7abc1200f9ad42c4adc6fbb4bd44b5bed4667990e64565102c1ba6" ) ) ``` -------------------------------- ### HexStr Source: https://github.com/apeworx/eth-pydantic-types/blob/main/docs/methoddocs/hex.md The HexStr type is used for representing hexadecimal strings. ```APIDOC ## HexStr ### Description Represents a hexadecimal string. ### Usage This type is part of the `eth_pydantic_types.hex.str` module. ``` -------------------------------- ### Use HexBytes and HexBytes32 in Pydantic Models Source: https://github.com/apeworx/eth-pydantic-types/blob/main/README.md Use HexBytes for any size byte strings that serialize to hex and HexBytes32 for fixed 32-byte hex representations. These types validate and handle byte data correctly. ```python from pydantic import BaseModel from eth_pydantic_types import HexBytes, HexBytes32 class TransactionData(BaseModel): hash_any_size: HexBytes sized_hash: HexBytes32 data = TransactionData(hash_any_size="0x123", sized_hash="0x000123") assert isinstance(data.nonce, str) assert isinstance(data.gas, str) ``` -------------------------------- ### Custom 8-byte Unsigned Integer for Network ID Source: https://context7.com/apeworx/eth-pydantic-types/llms.txt Defines a custom NetworkID type inheriting from BoundHexInt for 8-byte unsigned integers. Use this for chain or network identifiers. It enforces size and signedness constraints. ```python class NetworkID(BoundHexInt): size: ClassVar[int] = 8 signed: ClassVar[bool] = False class Network(BaseModel): network_id: NetworkID # Sepolia testnet chain ID net = Network(network_id=11155111) print(net.network_id) # 11155111 print(net.model_dump_json()) # '{"network_id":"0x0000000000aa36a7"}' # Out-of-range raises ValidationError try: Network(network_id=-1) except ValidationError as e: print(e) ``` -------------------------------- ### HexBytes - Unsized Bytes Field with Hex Serialization Source: https://context7.com/apeworx/eth-pydantic-types/llms.txt Use HexBytes for unsized byte fields that require 0x-prefixed hex string serialization. It accepts string, integer, and bytes as input and maintains its bytes subclass nature. ```python from pydantic import BaseModel, ValidationError from eth_pydantic_types import HexBytes from hexbytes import HexBytes as BaseHexBytes class Block(BaseModel): extra_data: HexBytes b = Block(extra_data="0xdeadbeef") print(b.extra_data) # HexBytes(b'\xde\xad\xbe\xef') print(isinstance(b.extra_data, bytes)) # True print(isinstance(b.extra_data, BaseHexBytes)) # True # Integer input b2 = Block(extra_data=10) print(b2.extra_data.hex()) # "0a" # Bytes input b3 = Block(extra_data=b"\x10\x31\xf0") print(b3.extra_data) # HexBytes(b'\x101\xf0') # Serialises to hex string print(b.model_dump()) # {'extra_data': '0xdeadbeef'} print(b.model_dump_json()) # '{"extra_data":"0xdeadbeef"}' # fromhex accepts with or without 0x prefix h1 = HexBytes.fromhex("0xdeadbeef") h2 = HexBytes.fromhex("deadbeef") print(h1 == h2) # True # Invalid input try: Block(extra_data="not-hex") except ValidationError as e: print(e) ``` -------------------------------- ### HexBytes Source: https://github.com/apeworx/eth-pydantic-types/blob/main/docs/methoddocs/hex.md The HexBytes type is used for representing hexadecimal byte sequences. ```APIDOC ## HexBytes ### Description Represents a sequence of bytes in hexadecimal format. ### Usage This type is part of the `eth_pydantic_types.hex.bytes` module. ``` -------------------------------- ### HexStr: Unsized Hex String Field Source: https://context7.com/apeworx/eth-pydantic-types/llms.txt Use HexStr for unsized hex string fields like transaction data. It validates and normalizes inputs to a 0x-prefixed, lowercase, even-length hex string. Supports conversion to int and bytes. ```python from pydantic import BaseModel, ValidationError from eth_pydantic_types import HexStr class Transaction(BaseModel): data: HexStr # Accepts str, int, or bytes tx = Transaction(data="0x0123") print(tx.data) # "0x0123" print(type(tx.data)) # tx2 = Transaction(data=10) print(tx2.data) # "0x0a" tx3 = Transaction(data=b"\xde\xad\xbe\xef") print(tx3.data) # "0xdeadbeef" # int conversion val = tx.data print(int(val, 16)) # 291 # bytes conversion print(bytes.fromhex(val[2:])) # b'\x01#' # from_bytes classmethod raw = b"\xb7\xfc\xef\x7f" print(HexStr.from_bytes(raw)) # "0xb7fcef7f" # Invalid input raises ValidationError try: Transaction(data="not-hex") except ValidationError as e: print(e) # JSON schema import json print(json.dumps(Transaction.model_json_schema(), indent=2)) # { # "properties": { # "data": {"type": "string", "format": "binary", # "pattern": "^0x([0-9a-f][0-9a-f])*$", ...} # }, ... # } ``` -------------------------------- ### Use HexInt in Pydantic Models for Hex Integers Source: https://github.com/apeworx/eth-pydantic-types/blob/main/README.md Use HexInt for integer values that are represented as hex strings. This type ensures that hex string inputs are correctly parsed into Python integers. ```python from pydantic import BaseModel from eth_pydantic_types import HexInt class TransactionData(BaseModel): nonce: HexInt gas: HexInt data = TransactionData(nonce="0x123", gas="0x000123") assert isinstance(data.nonce, int) assert isinstance(data.gas, int) ``` -------------------------------- ### Use HexStr for Un-Sized Hex Strings in Pydantic Source: https://github.com/apeworx/eth-pydantic-types/blob/main/README.md The HexStr type is suitable for models where you only need un-sized hex strings. It serializes to a string in Pydantic core schema and JSON schema. ```python from eth_pydantic_types import HexStr from pydantic import BaseModel class Tx(BaseModel): data: HexStr tx = Tx(data="0x0123") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.