From 845d08808d0e5fe171a58d07a9928c9ec90fff70 Mon Sep 17 00:00:00 2001 From: antazoey Date: Thu, 3 Oct 2024 10:15:35 -0500 Subject: [PATCH] fix: serialized `HexBytes` for `Any` types in `ContractLog` (#2308) --- src/ape/types/__init__.py | 29 +++++++++++++++-- tests/functional/test_contract_event.py | 41 +++++++++++++++++++++++++ 2 files changed, 68 insertions(+), 2 deletions(-) diff --git a/src/ape/types/__init__.py b/src/ape/types/__init__.py index 94ddf2033a..ea6581c50a 100644 --- a/src/ape/types/__init__.py +++ b/src/ape/types/__init__.py @@ -1,4 +1,4 @@ -from collections.abc import Callable, Iterator, Sequence +from collections.abc import Callable, Iterable, Iterator, Sequence from dataclasses import dataclass from typing import TYPE_CHECKING, Annotated, Any, Literal, Optional, TypeVar, Union, cast, overload @@ -265,7 +265,28 @@ def _serialize_event_arguments(self, event_arguments, info): (https://github.com/pydantic/pydantic/issues/10152) we have to ensure these are regular ints. """ - return {k: int(v) if isinstance(v, int) else v for k, v in event_arguments.items()} + return self._serialize_value(event_arguments, info) + + def _serialize_value(self, value: Any, info) -> Any: + if isinstance(value, int): + # Handle custom ints. + return int(value) + + elif isinstance(value, HexBytes): + return to_hex(value) if info.mode == "json" else value + + elif isinstance(value, str): + # Avoiding str triggering iterable condition. + return value + + elif isinstance(value, dict): + # Also, avoid handling dict in the iterable case. + return {k: self._serialize_value(v, info) for k, v in value.items()} + + elif isinstance(value, Iterable): + return [self._serialize_value(v, info) for v in value] + + return value class ContractLog(ExtraAttributesMixin, BaseContractLog): @@ -291,6 +312,10 @@ class ContractLog(ExtraAttributesMixin, BaseContractLog): Is `None` when from the pending block. """ + @field_serializer("transaction_hash", "block_hash") + def _serialize_hashes(self, value, info): + return self._serialize_value(value, info) + # NOTE: This class has an overridden `__getattr__` method, but `block` is a reserved keyword # in most smart contract languages, so it is safe to use. Purposely avoid adding # `.datetime` and `.timestamp` in case they are used as event arg names. diff --git a/tests/functional/test_contract_event.py b/tests/functional/test_contract_event.py index 509828184b..c4c607ef37 100644 --- a/tests/functional/test_contract_event.py +++ b/tests/functional/test_contract_event.py @@ -4,6 +4,8 @@ import pytest from eth_pydantic_types import HexBytes +from eth_pydantic_types.hash import HashBytes20 +from eth_utils import to_hex from ethpm_types import ContractType from ape.api import ReceiptAPI @@ -382,3 +384,42 @@ def test_model_dump(solidity_contract_container, owner): # This next assertion is important because of this Pydantic bug: # https://github.com/pydantic/pydantic/issues/10152 assert not isinstance(actual["newNum"], CurrencyValueComparable) + + +@pytest.mark.parametrize("mode", ("python", "json")) +def test_model_dump_hexbytes(mode): + # NOTE: There was an issue when using HexBytes for Any. + event_arguments = {"key": 123, "validators": [HexBytes(123)]} + txn_hash = HashBytes20.__eth_pydantic_validate__(347374237412374174) + event = ContractLog( + block_number=123, + block_hash="block-hash", + event_arguments=event_arguments, + event_name="MyEvent", + log_index=0, + transaction_hash=txn_hash, + ) + actual = event.model_dump(mode=mode) + expected_hash = txn_hash if mode == "python" else to_hex(txn_hash) + assert actual["transaction_hash"] == expected_hash + + +def test_model_dump_json(): + # NOTE: There was an issue when using HexBytes for Any. + event_arguments = {"key": 123, "validators": [HexBytes(123)]} + event = ContractLog( + block_number=123, + block_hash="block-hash", + event_arguments=event_arguments, + event_name="MyEvent", + log_index=0, + transaction_hash=HashBytes20.__eth_pydantic_validate__(347374237412374174), + ) + actual = event.model_dump_json() + assert actual == ( + '{"block_hash":"block-hash","block_number":123,' + '"contract_address":"0x0000000000000000000000000000000000000000",' + '"event_arguments":{"key":123,"validators":["0x7b"]},"event_name":' + '"MyEvent","log_index":0,' + '"transaction_hash":"0x00000000000000000000000004d21f074916369e"}' + )