Skip to content

Commit

Permalink
fix: encode/decode bytes/HexBytes recursively in messages (#51)
Browse files Browse the repository at this point in the history
  • Loading branch information
mikeshultz authored Jan 10, 2024
1 parent 1092046 commit 48df76b
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 7 deletions.
16 changes: 10 additions & 6 deletions silverback/middlewares.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
from typing import Optional, Tuple
from typing import Any, Optional, Tuple

from ape.logging import logger
from ape.types import ContractLog
from ape.utils import ManagerAccessMixin
from eth_utils.conversions import to_hex
from taskiq import TaskiqMessage, TaskiqMiddleware, TaskiqResult

from silverback.persistence import HandlerResult
Expand Down Expand Up @@ -45,13 +46,16 @@ def compute_block_time() -> int:
self.persistence = settings.get_persistent_store()

def pre_send(self, message: TaskiqMessage) -> TaskiqMessage:
# TODO: Necessary until https://github.com/ApeWorX/ape/issues/1465 is resolved

def fix_dict(data: dict) -> dict:
fixed_data = {}
# TODO: Necessary because bytes/HexBytes doesn't encode/deocde well for some reason
def fix_dict(data: dict, recurse_count: int = 0) -> dict:
fixed_data: dict[str, Any] = {}
for name, value in data.items():
if isinstance(value, bytes):
fixed_data[name] = value.hex()
fixed_data[name] = to_hex(value)
elif isinstance(value, dict):
if recurse_count > 3:
raise RecursionError("Event object is too deep")
fixed_data[name] = fix_dict(value, recurse_count + 1)
else:
fixed_data[name] = value

Expand Down
6 changes: 5 additions & 1 deletion silverback/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,17 @@ def iter_to_queue():
return yield_queue_items()


def hexbytes_dict(data: dict) -> dict:
def hexbytes_dict(data: dict, recurse_count: int = 0) -> dict:
"""Converts any hex string values in a flat dictionary to HexBytes."""
fixed_data = {}

for name, value in data.items():
if isinstance(value, str) and value.startswith("0x"):
fixed_data[name] = HexBytes(value)
elif isinstance(value, dict):
if recurse_count > 3:
raise RecursionError("Event object is too deep")
hexbytes_dict(value, recurse_count + 1)
else:
fixed_data[name] = value

Expand Down

0 comments on commit 48df76b

Please sign in to comment.