Skip to content

Commit

Permalink
fix: serialized HexBytes for Any types in ContractLog (#2308)
Browse files Browse the repository at this point in the history
  • Loading branch information
antazoey authored Oct 3, 2024
1 parent 29fbcaa commit 845d088
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 2 deletions.
29 changes: 27 additions & 2 deletions src/ape/types/__init__.py
Original file line number Diff line number Diff line change
@@ -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

Expand Down Expand Up @@ -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):
Expand All @@ -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.
Expand Down
41 changes: 41 additions & 0 deletions tests/functional/test_contract_event.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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"}'
)

0 comments on commit 845d088

Please sign in to comment.