From a3b9c909156a7f45803a91d7283ecb1afecdf44e Mon Sep 17 00:00:00 2001 From: Juliya Smith Date: Fri, 8 Dec 2023 09:33:02 -0600 Subject: [PATCH] fix: 0x prefix bug --- eth_pydantic_types/hex.py | 8 ++++++-- tests/test_hex.py | 6 ++++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/eth_pydantic_types/hex.py b/eth_pydantic_types/hex.py index b50fcda..ad6cbbf 100644 --- a/eth_pydantic_types/hex.py +++ b/eth_pydantic_types/hex.py @@ -1,5 +1,7 @@ -from typing import Any, ClassVar, Optional, Tuple, Union +from typing import Any, ClassVar, Optional, Tuple, Union, cast +from eth_typing import HexStr as EthTypingHexStr +from eth_utils import add_0x_prefix from hexbytes import HexBytes as BaseHexBytes from pydantic_core import CoreSchema from pydantic_core.core_schema import ( @@ -105,7 +107,9 @@ def __eth_pydantic_validate__(cls, value): @classmethod def from_bytes(cls, data: bytes) -> "HexStr": - return HexStr(super().from_bytes(data)) + value_str = super().from_bytes(data) + value = add_0x_prefix(cast(EthTypingHexStr, value_str)) + return HexStr(value) def validate_hex_str(value: str) -> str: diff --git a/tests/test_hex.py b/tests/test_hex.py index 9c47def..c263741 100644 --- a/tests/test_hex.py +++ b/tests/test_hex.py @@ -109,3 +109,9 @@ def test_hexstr_model_dump(bytes32str): actual = model.model_dump() expected = {"value": "0x03"} assert actual == expected + + +def test_from_bytes(): + value = b"\xb7\xfc\xef\x7f\xe7E\xf2\xa9U`\xff_U\x0e;\x8f" + actual = HexStr.from_bytes(value) + assert actual.startswith("0x")