Skip to content

Commit

Permalink
Add to_0x_hex_str method
Browse files Browse the repository at this point in the history
  • Loading branch information
falvaradorodriguez committed Feb 3, 2025
1 parent 74ca922 commit 45ac943
Show file tree
Hide file tree
Showing 23 changed files with 120 additions and 76 deletions.
3 changes: 2 additions & 1 deletion safe_eth/eth/clients/cowswap/cow_swap_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from safe_eth.eth.constants import NULL_ADDRESS
from safe_eth.eth.eip712 import eip712_encode_hash
from safe_eth.util.http import prepare_http_session
from safe_eth.util.util import to_0x_hex_str

from .order import Order, OrderKind

Expand Down Expand Up @@ -163,7 +164,7 @@ def place_order(
"feeAmount": str(order.feeAmount),
"kind": order.kind,
"partiallyFillable": order.partiallyFillable,
"signature": signed_message.signature.to_0x_hex(),
"signature": to_0x_hex_str(signed_message.signature),
"signingScheme": "ethsign",
"from": from_address,
}
Expand Down
3 changes: 2 additions & 1 deletion safe_eth/eth/django/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from hexbytes import HexBytes

from safe_eth.eth.utils import fast_is_checksum_address
from safe_eth.util.util import to_0x_hex_str


class EthereumAddressFieldForm(forms.CharField):
Expand Down Expand Up @@ -79,6 +80,6 @@ def to_python(self, value: Optional[Any]) -> Optional[HexBytes]:
raise ValidationError(
self.error_messages["length"],
code="length",
params={"value": python_value.to_0x_hex()},
params={"value": to_0x_hex_str(python_value)},
)
return python_value
3 changes: 2 additions & 1 deletion safe_eth/eth/django/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from eth_utils import to_normalized_address
from hexbytes import HexBytes

from ...util.util import to_0x_hex_str
from ..utils import fast_bytes_to_checksum_address, fast_to_checksum_address
from .forms import EthereumAddressFieldForm, HexFieldForm, Keccak256FieldForm
from .validators import validate_address, validate_checksumed_address
Expand Down Expand Up @@ -225,7 +226,7 @@ def _to_bytes(self, value) -> Optional[bytes]:

def from_db_value(self, value: memoryview, expression, connection) -> Optional[str]:
if value:
return HexBytes(bytes(value)).to_0x_hex()
return to_0x_hex_str(bytes(value))
return None

def get_prep_value(self, value: Union[bytes, str]) -> Optional[bytes]:
Expand Down
3 changes: 2 additions & 1 deletion safe_eth/eth/django/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from rest_framework import serializers
from rest_framework.exceptions import ValidationError

from ...util.util import to_0x_hex_str
from ..constants import (
SIGNATURE_R_MAX_VALUE,
SIGNATURE_R_MIN_VALUE,
Expand Down Expand Up @@ -89,7 +90,7 @@ def to_representation(self, obj):
obj = HexBytes(obj.hex())
elif not isinstance(obj, HexBytes):
obj = HexBytes(obj)
return obj.to_0x_hex()
return to_0x_hex_str(obj)

def to_internal_value(self, data):
if isinstance(data, (bytes, memoryview)):
Expand Down
4 changes: 3 additions & 1 deletion safe_eth/eth/django/tests/test_forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@

from hexbytes import HexBytes

from safe_eth.util.util import to_0x_hex_str

from ...utils import fast_keccak_text
from ..forms import EthereumAddressFieldForm, HexFieldForm, Keccak256FieldForm

Expand Down Expand Up @@ -77,7 +79,7 @@ def test_keccak256_field_form(self):
form.errors["value"], ['"0x1234" keccak256 hash should be 32 bytes.']
)

form = Keccak256Form(data={"value": fast_keccak_text("testing").to_0x_hex()})
form = Keccak256Form(data={"value": to_0x_hex_str(fast_keccak_text("testing"))})
self.assertTrue(form.is_valid())

form = Keccak256Form(data={"value": ""})
Expand Down
4 changes: 3 additions & 1 deletion safe_eth/eth/django/tests/test_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
from faker import Faker
from hexbytes import HexBytes

from safe_eth.util.util import to_0x_hex_str

from ...constants import NULL_ADDRESS, SENTINEL_ADDRESS
from ...utils import fast_is_checksum_address, fast_keccak_text
from .models import (
Expand Down Expand Up @@ -147,7 +149,7 @@ def test_uint32_field(self):

def test_keccak256_field(self):
value_hexbytes = HexBytes(fast_keccak_text(faker.name()))
value_hex_with_0x: str = value_hexbytes.to_0x_hex()
value_hex_with_0x: str = to_0x_hex_str(value_hexbytes)
value_hex_without_0x: str = value_hex_with_0x[2:]
value: bytes = bytes(value_hexbytes)

Expand Down
6 changes: 5 additions & 1 deletion safe_eth/eth/django/tests/test_serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
from hexbytes import HexBytes
from rest_framework import serializers

from safe_eth.util.util import to_0x_hex_str

from ...constants import NULL_ADDRESS, SENTINEL_ADDRESS
from ...utils import fast_keccak_text, get_eth_address_with_invalid_checksum
from ..serializers import (
Expand Down Expand Up @@ -144,7 +146,9 @@ class A:
hex_value = value if isinstance(value, str) else value.hex()
a.value = value
serializer = HexadecimalSerializerTest(a)
self.assertEqual(serializer.data["value"], HexBytes(hex_value).to_0x_hex())
self.assertEqual(
serializer.data["value"], to_0x_hex_str(HexBytes(hex_value))
)

def test_hash_serializer_field(self):
value = fast_keccak_text("test").hex()
Expand Down
27 changes: 15 additions & 12 deletions safe_eth/eth/ethereum_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@
from safe_eth.util import chunks

from ..util.http import prepare_http_session
from ..util.util import to_0x_hex_str
from .constants import (
ERC20_721_TRANSFER_TOPIC,
GAS_CALL_DATA_BYTE,
Expand Down Expand Up @@ -307,7 +308,9 @@ def batch_call_custom(
payloads, sorted(all_results, key=lambda x: x["id"])
):
if "error" in result:
fn_name = payload.get("fn_name", HexBytes(payload["data"]).to_0x_hex())
fn_name = payload.get(
"fn_name", to_0x_hex_str(HexBytes(payload["data"]))
)
errors.append(f'`{fn_name}`: {result["error"]}')
return_values.append(None)
else:
Expand All @@ -325,7 +328,7 @@ def batch_call_custom(
return_values.append(normalized_data)
except (DecodingError, OverflowError):
fn_name = payload.get(
"fn_name", HexBytes(payload["data"]).to_0x_hex()
"fn_name", to_0x_hex_str(HexBytes(payload["data"]))
)
errors.append(f"`{fn_name}`: DecodingError, cannot decode")
return_values.append(None)
Expand Down Expand Up @@ -475,7 +478,7 @@ def _decode_transfer_log(
except DecodingError:
logger.warning(
"Cannot decode Transfer event `uint256 value` from data=%s",
value_data.to_0x_hex(),
to_0x_hex_str(value_data),
)
return None
from_to_data = b"".join(topics[1:])
Expand All @@ -490,7 +493,7 @@ def _decode_transfer_log(
except DecodingError:
logger.warning(
"Cannot decode Transfer event `address from, address to` from topics=%s",
HexBytes(from_to_data).to_0x_hex(),
to_0x_hex_str(from_to_data),
)
return None
elif topics_len == 4:
Expand All @@ -508,7 +511,7 @@ def _decode_transfer_log(
except DecodingError:
logger.warning(
"Cannot decode Transfer event `address from, address to` from topics=%s",
HexBytes(from_to_token_id_data).to_0x_hex(),
to_0x_hex_str(from_to_token_id_data),
)
return None
return None
Expand Down Expand Up @@ -713,10 +716,10 @@ def get_total_transfer_history(
:param token_address: Address of the token
:return: List of events sorted by blockNumber
"""
topic_0 = self.TRANSFER_TOPIC.to_0x_hex()
topic_0 = to_0x_hex_str(self.TRANSFER_TOPIC)
if addresses:
addresses_encoded = [
HexBytes(eth_abi.encode(["address"], [address])).to_0x_hex()
to_0x_hex_str(eth_abi.encode(["address"], [address]))
for address in addresses
]
# Topics for transfer `to` and `from` an address
Expand Down Expand Up @@ -1089,7 +1092,7 @@ def trace_transactions(
"id": i,
"jsonrpc": "2.0",
"method": "trace_transaction",
"params": [HexBytes(tx_hash).to_0x_hex()],
"params": [to_0x_hex_str(HexBytes(tx_hash))],
}
for i, tx_hash in enumerate(tx_hashes)
]
Expand Down Expand Up @@ -1542,7 +1545,7 @@ def deploy_and_initialize_contract(

tx["gas"] = self.w3.eth.estimate_gas(tx)
tx_hash = self.send_unsigned_transaction(
tx, private_key=HexBytes(deployer_account.key).to_0x_hex()
tx, private_key=to_0x_hex_str(deployer_account.key)
)
if check_receipt:
tx_receipt = self.get_transaction_receipt(
Expand Down Expand Up @@ -1709,7 +1712,7 @@ def get_transactions(
"id": i,
"jsonrpc": "2.0",
"method": "eth_getTransactionByHash",
"params": [HexBytes(tx_hash).to_0x_hex()],
"params": [to_0x_hex_str(HexBytes(tx_hash))],
}
for i, tx_hash in enumerate(tx_hashes)
]
Expand Down Expand Up @@ -1752,7 +1755,7 @@ def get_transaction_receipts(
"id": i,
"jsonrpc": "2.0",
"method": "eth_getTransactionReceipt",
"params": [HexBytes(tx_hash).to_0x_hex()],
"params": [to_0x_hex_str(HexBytes(tx_hash))],
}
for i, tx_hash in enumerate(tx_hashes)
]
Expand Down Expand Up @@ -1784,7 +1787,7 @@ def _parse_block_identifier(self, block_identifier: BlockIdentifier) -> str:
if isinstance(block_identifier, int):
return HexStr(hex(block_identifier))
elif isinstance(block_identifier, bytes):
return HexStr(HexBytes(block_identifier).to_0x_hex())
return HexStr(to_0x_hex_str(HexBytes(block_identifier)))
return str(block_identifier)

def get_blocks(
Expand Down
8 changes: 5 additions & 3 deletions safe_eth/eth/tests/account_abstraction/test_bundler_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
import requests
from eth_typing import HexStr

from safe_eth.util.util import to_0x_hex_str

from ...account_abstraction import (
BundlerClient,
BundlerClientConnectionException,
Expand All @@ -32,7 +34,7 @@ def test_get_user_operation_by_hash(self, mock_session: MagicMock):
mock_session.return_value.json = MagicMock(
return_value={"jsonrpc": "2.0", "id": 1, "result": None}
)
user_operation_hash = safe_4337_user_operation_hash_mock.to_0x_hex()
user_operation_hash = to_0x_hex_str(safe_4337_user_operation_hash_mock)

self.assertIsNone(self.bundler.get_user_operation_by_hash(user_operation_hash))
mock_session.return_value.json = MagicMock(return_value=user_operation_mock)
Expand Down Expand Up @@ -72,7 +74,7 @@ def test_get_user_operation_receipt(self, mock_session: MagicMock):
mock_session.return_value.json = MagicMock(
return_value={"jsonrpc": "2.0", "id": 1, "result": None}
)
user_operation_hash = safe_4337_user_operation_hash_mock.to_0x_hex()
user_operation_hash = to_0x_hex_str(safe_4337_user_operation_hash_mock)
self.assertIsNone(self.bundler.get_user_operation_receipt(user_operation_hash))
mock_session.return_value.json = MagicMock(
return_value=copy.deepcopy(user_operation_receipt_mock)
Expand Down Expand Up @@ -116,7 +118,7 @@ def test_get_user_operation_and_receipt(self, mock_session: MagicMock):
{"jsonrpc": "2.0", "id": 2, "result": None},
]
)
user_operation_hash = safe_4337_user_operation_hash_mock.to_0x_hex()
user_operation_hash = to_0x_hex_str(safe_4337_user_operation_hash_mock)
self.assertIsNone(
self.bundler.get_user_operation_and_receipt(user_operation_hash)
)
Expand Down
19 changes: 10 additions & 9 deletions safe_eth/eth/tests/account_abstraction/test_e2e_bundler_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
from django.test import TestCase

import pytest
from hexbytes import HexBytes

from safe_eth.util.util import to_0x_hex_str

from ...account_abstraction import BundlerClient, UserOperation, UserOperationReceipt
from ...account_abstraction.user_operation import UserOperationV07
Expand All @@ -30,7 +31,7 @@ def test_get_chain_id(self):
self.assertGreater(self.bundler.get_chain_id(), 0)

def test_get_user_operation_by_hash(self):
user_operation_hash = safe_4337_user_operation_hash_mock.to_0x_hex()
user_operation_hash = to_0x_hex_str(safe_4337_user_operation_hash_mock)

expected_user_operation = UserOperation.from_bundler_response(
user_operation_hash, user_operation_mock["result"]
Expand All @@ -41,30 +42,30 @@ def test_get_user_operation_by_hash(self):
expected_user_operation,
)
self.assertEqual(
HexBytes(
to_0x_hex_str(
user_operation.calculate_user_operation_hash(safe_4337_chain_id_mock)
).to_0x_hex(),
),
user_operation_hash,
)

def test_get_user_operation_V07_by_hash(self):
"""
Test UserOperation v0.7
"""
user_operation_hash = user_operation_v07_hash.to_0x_hex()
user_operation_hash = to_0x_hex_str(user_operation_v07_hash)
user_operation = self.bundler.get_user_operation_by_hash(user_operation_hash)
self.assertIsInstance(user_operation, UserOperationV07)
self.assertEqual(
HexBytes(
to_0x_hex_str(
user_operation.calculate_user_operation_hash(
user_operation_v07_chain_id
)
).to_0x_hex(),
),
user_operation_hash,
)

def test_get_user_operation_receipt(self):
user_operation_hash = safe_4337_user_operation_hash_mock.to_0x_hex()
user_operation_hash = to_0x_hex_str(safe_4337_user_operation_hash_mock)
expected_user_operation_receipt = UserOperationReceipt.from_bundler_response(
user_operation_receipt_mock["result"]
)
Expand All @@ -76,7 +77,7 @@ def test_get_user_operation_receipt(self):

@pytest.mark.xfail(reason="Some bundlers don't support batch requests")
def test_get_user_operation_and_receipt(self):
user_operation_hash = safe_4337_user_operation_hash_mock.to_0x_hex()
user_operation_hash = to_0x_hex_str(safe_4337_user_operation_hash_mock)

expected_user_operation = UserOperation.from_bundler_response(
user_operation_hash, user_operation_mock["result"]
Expand Down
6 changes: 4 additions & 2 deletions safe_eth/eth/tests/account_abstraction/test_user_operation.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from unittest import TestCase

from safe_eth.util.util import to_0x_hex_str

from ...account_abstraction import UserOperation
from ...account_abstraction.user_operation import UserOperationV07
from ..mocks.mock_bundler import (
Expand All @@ -15,7 +17,7 @@ class TestUserOperation(TestCase):
def test_calculate_user_operation_hash_V06(self):
user_operation_hash = safe_4337_user_operation_hash_mock
user_operation = UserOperation.from_bundler_response(
user_operation_hash.to_0x_hex(), user_operation_mock["result"]
to_0x_hex_str(user_operation_hash), user_operation_mock["result"]
)
self.assertIsInstance(user_operation, UserOperation)
self.assertEqual(
Expand All @@ -26,7 +28,7 @@ def test_calculate_user_operation_hash_V06(self):
def test_calculate_user_operation_hash_V07(self):
user_operation_hash = user_operation_v07_hash
user_operation = UserOperation.from_bundler_response(
user_operation_hash.to_0x_hex(), user_operation_v07_mock["result"]
to_0x_hex_str(user_operation_hash), user_operation_v07_mock["result"]
)
self.assertIsInstance(user_operation, UserOperationV07)
self.assertEqual(
Expand Down
Loading

0 comments on commit 45ac943

Please sign in to comment.