Skip to content

Commit

Permalink
Only calculate the topic when it is asked for, while caching the result.
Browse files Browse the repository at this point in the history
- Calculating the topic at ``__init__`` is not necessary. Instead,
  calculate it when the topic is asked for and set the internal
  ``_topic`` attribute only on the first call.
  • Loading branch information
fselmo committed Jan 15, 2025
1 parent 695e883 commit 6fdb036
Showing 1 changed file with 7 additions and 2 deletions.
9 changes: 7 additions & 2 deletions web3/contract/base_contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,7 @@ class BaseContractEvent:
argument_types: Tuple[str, ...] = tuple()
args: Any = None
kwargs: Any = None
_topic: HexStr = None

def __init__(self, *argument_names: str, abi: Optional[ABIEvent] = None) -> None:
self.abi_element_identifier = type(self).__name__
Expand All @@ -175,7 +176,6 @@ def __init__(self, *argument_names: str, abi: Optional[ABIEvent] = None) -> None
self.abi = abi

self.signature = abi_to_signature(self.abi)
self.topic = encode_hex(keccak(text=self.signature))

if argument_names:
self.argument_names = argument_names
Expand All @@ -189,6 +189,12 @@ def __repr__(self) -> str:
return f"<Event {abi_to_signature(self.abi)}>"
return f"<Event {get_abi_element_signature(self.abi_element_identifier)}>"

@property
def topic(self) -> HexStr:
if self._topic is None:
self._topic = encode_hex(keccak(text=self.signature))
return self._topic

@combomethod
def _get_event_abi(cls) -> ABIEvent:
if cls.abi:
Expand All @@ -205,7 +211,6 @@ def _get_event_abi(cls) -> ABIEvent:

def _set_event_info(self) -> None:
self.abi = self._get_event_abi()
self.topic = encode_hex(keccak(text=self.signature))

@combomethod
def process_receipt(
Expand Down

0 comments on commit 6fdb036

Please sign in to comment.