degenbot.utils.bytes ==================== .. py:module:: degenbot.utils.bytes .. autoapi-nested-parse:: Plain-bytes hex utilities. Carries the conversion matrix that the old 1.3-era hex-bytes wrapper provided, as plain ``bytes`` utilities. Golden-vector parity with the upstream behavior is pinned in ``tests/utils/test_bytes_utils.py``. Module Contents --------------- .. py:function:: to_0x_hex(data: bytes | bytearray | str) -> str Return ``0x``-prefixed lowercase hex of *data* (degenbot semantics). ``bytes``/``bytearray`` are RAW data: re-encoded via ``.hex()`` (this is how degenbot has historically derived address, pool-id and tx-hash hex from raw ``bytes``). ``str`` is first decoded as hex via :func:`to_bytes` (upstream ``str.__str__`` rule). :returns: The hex string with a ``0x`` prefix (``"0x"`` for empty input). .. py:function:: to_bytes(data: BytesLikeSource) -> bytes Decode a value to ``bytes`` following the old wrapper's matrix. Conversion matrix (old wrapper ``to_bytes``, preserved byte-for-byte): - ``bytes`` -- returned as-is (no copy); - ``bytearray`` -- converted to ``bytes`` (copied); - ``memoryview`` -- converted (``.tobytes()``); - ``bool`` -- checked before ``int``: ``False`` -> ``b"\x00"``, ``True`` -> ``b"\x01"``; - ``int`` -- ``to_bytes((data.bit_length() + 7) // 8, "big")`` (the ``0`` edge -- one zero byte -- comes from ``bit_length``, and 256 uses 2 bytes); - ``str`` -- ``bytes.fromhex(s)`` after skipping an optional ``0x`` prefix, with odd-length hex left-padded (upstream rule); ASCII non-hex chars raise ``binascii.Error`` (a ``ValueError`` subclass) and non-ASCII characters propagate the ``UnicodeEncodeError`` (upstream's ``except`` clause catches ``UnicodeDecodeError``, which ``.encode()`` never raises); - any other input -- :class:`TypeError` (kept for values reaching this function through untyped / dynamic callers). :returns: The decoded ``bytes``. :raises TypeError: If *data* is not one of the accepted container types. :raises ValueError: If *data* is a negative ``int`` or a string containing non-hex characters (``binascii.Error``).