Skip to content

Commit

Permalink
fix: use to_hex() instead of bytes.hex() (#67)
Browse files Browse the repository at this point in the history
  • Loading branch information
antazoey authored Dec 17, 2024
1 parent 6c904f0 commit 0456b72
Show file tree
Hide file tree
Showing 9 changed files with 41 additions and 35 deletions.
3 changes: 2 additions & 1 deletion .github/workflows/test.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -96,4 +96,5 @@ jobs:
run: npm install "@gnosis.pm/safe-contracts@${{ matrix.safe-version }}"

- name: Run Tests
run: pytest -n 0 -s --cov
#TODO: Put back: run: pytest -n 0 -s --cov
run: pytest tests/functional/test_account.py::test_swap_owner --maxfail 1 -vvv
6 changes: 3 additions & 3 deletions ape_safe/_cli/pending.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from ape.cli import ConnectedProviderCommand
from ape.exceptions import SignatureError
from eth_typing import ChecksumAddress, Hash32
from eth_utils import humanize_hash
from eth_utils import humanize_hash, to_hex
from hexbytes import HexBytes

from ape_safe._cli.click_ext import (
Expand Down Expand Up @@ -89,12 +89,12 @@ def _list(cli_ctx, safe, verbose) -> None:
value = "0"

if isinstance(value, bytes):
value_str = HexBytes(value).hex()
value_str = str(to_hex(HexBytes(value)))
else:
value_str = f"{value}"

if len(value_str) > 42:
value_str = humanize_hash(cast(Hash32, HexBytes(value_str)))
value_str = f"{humanize_hash(cast(Hash32, HexBytes(value_str)))}"

data[field_name] = value_str

Expand Down
14 changes: 7 additions & 7 deletions ape_safe/accounts.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import os
from collections.abc import Iterable, Iterator, Mapping
from pathlib import Path
from typing import TYPE_CHECKING, Any, Dict, Optional, Union, cast
from typing import TYPE_CHECKING, Any, Optional, Union, cast

from ape.api import AccountAPI, AccountContainerAPI, ReceiptAPI, TransactionAPI
from ape.api.networks import ForkedNetworkAPI
Expand Down Expand Up @@ -41,7 +41,7 @@


class SafeContainer(AccountContainerAPI):
_accounts: Dict[str, "SafeAccount"] = {}
_accounts: dict[str, "SafeAccount"] = {}

@property
def _account_files(self) -> Iterator[Path]:
Expand Down Expand Up @@ -182,8 +182,8 @@ def _get_path(self, alias: str) -> Path:
def get_signatures(
safe_tx: SafeTx,
signers: Iterable[AccountAPI],
) -> Dict[AddressType, MessageSignature]:
signatures: Dict[AddressType, MessageSignature] = {}
) -> dict[AddressType, MessageSignature]:
signatures: dict[AddressType, MessageSignature] = {}
for signer in signers:
signature = signer.sign_message(safe_tx)
if signature:
Expand Down Expand Up @@ -535,7 +535,7 @@ def call( # type: ignore[override]

return super().call(txn, **call_kwargs)

def get_api_confirmations(self, safe_tx: SafeTx) -> Dict[AddressType, MessageSignature]:
def get_api_confirmations(self, safe_tx: SafeTx) -> dict[AddressType, MessageSignature]:
safe_tx_id = get_safe_tx_hash(safe_tx)
try:
client_confirmations = self.client.get_confirmations(safe_tx_id)
Expand All @@ -560,7 +560,7 @@ def _contract_approvals(self, safe_tx: SafeTx) -> Mapping[AddressType, MessageSi
if self.contract.approvedHashes(signer, safe_tx_hash) > 0
}

def _all_approvals(self, safe_tx: SafeTx) -> Dict[AddressType, MessageSignature]:
def _all_approvals(self, safe_tx: SafeTx) -> dict[AddressType, MessageSignature]:
approvals = self.get_api_confirmations(safe_tx)

# NOTE: Do this last because it should take precedence
Expand Down Expand Up @@ -724,7 +724,7 @@ def skip_signer(signer: AccountAPI):

def add_signatures(
self, safe_tx: SafeTx, confirmations: Optional[list[SafeTxConfirmation]] = None
) -> Dict[AddressType, MessageSignature]:
) -> dict[AddressType, MessageSignature]:
confirmations = confirmations or []
if not self.local_signers:
raise ApeSafeError("Cannot sign without local signers.")
Expand Down
24 changes: 14 additions & 10 deletions ape_safe/client/__init__.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import json
from collections.abc import Iterator
from datetime import datetime
from functools import reduce
from typing import Dict, Iterator, Optional, Union, cast
from typing import Optional, Union, cast

from ape.types import AddressType, HexBytes, MessageSignature
from ape.utils import USER_AGENT, get_package_version
from eip712.common import SafeTxV1, SafeTxV2
from eth_utils import to_hex

from ape_safe.client.base import BaseSafeClient
from ape_safe.client.mock import MockSafeClient
Expand Down Expand Up @@ -116,7 +118,7 @@ def get_confirmations(self, safe_tx_hash: SafeTxID) -> Iterator[SafeTxConfirmati
url = data.get("next")

def post_transaction(
self, safe_tx: SafeTx, signatures: Dict[AddressType, MessageSignature], **kwargs
self, safe_tx: SafeTx, signatures: dict[AddressType, MessageSignature], **kwargs
):
tx_data = UnexecutedTxData.from_safe_tx(safe_tx, self.safe_details.threshold)
signature = HexBytes(
Expand All @@ -127,11 +129,11 @@ def post_transaction(
b"",
)
)
post_dict: Dict = {"signature": signature.hex(), "origin": ORIGIN}
post_dict: dict = {"signature": to_hex(signature), "origin": ORIGIN}

for key, value in tx_data.model_dump(by_alias=True, mode="json").items():
if isinstance(value, HexBytes):
post_dict[key] = value.hex()
post_dict[key] = to_hex(value)
elif isinstance(value, OperationType):
post_dict[key] = int(value)
elif isinstance(value, datetime):
Expand All @@ -153,17 +155,19 @@ def post_transaction(
def post_signatures(
self,
safe_tx_or_hash: Union[SafeTx, SafeTxID],
signatures: Dict[AddressType, MessageSignature],
signatures: dict[AddressType, MessageSignature],
):
if isinstance(safe_tx_or_hash, (SafeTxV1, SafeTxV2)):
safe_tx = safe_tx_or_hash
safe_tx_hash = get_safe_tx_hash(safe_tx)
else:
safe_tx_hash = safe_tx_or_hash

safe_tx_hash = cast(SafeTxID, HexBytes(safe_tx_hash).hex())
safe_tx_hash = cast(SafeTxID, to_hex(HexBytes(safe_tx_hash)))
url = f"multisig-transactions/{safe_tx_hash}/confirmations"
signature = HexBytes(b"".join([x.encode_rsv() for x in order_by_signer(signatures)])).hex()
signature = to_hex(
HexBytes(b"".join([x.encode_rsv() for x in order_by_signer(signatures)]))
)
try:
self._post(url, json={"signature": signature})
except ClientResponseError as err:
Expand All @@ -176,15 +180,15 @@ def estimate_gas_cost(
self, receiver: AddressType, value: int, data: bytes, operation: int = 0
) -> Optional[int]:
url = f"safes/{self.address}/multisig-transactions/estimations"
request: Dict = {
request: dict = {
"to": receiver,
"value": value,
"data": HexBytes(data).hex(),
"data": to_hex(HexBytes(data)),
"operation": operation,
}
result = self._post(url, json=request).json()
gas = result.get("safeTxGas")
return int(HexBytes(gas).hex(), 16)
return int(to_hex(HexBytes(gas)), 16)


__all__ = [
Expand Down
8 changes: 4 additions & 4 deletions ape_safe/client/mock.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from typing import TYPE_CHECKING, Optional, Union, cast

from ape.utils import ZERO_ADDRESS, ManagerAccessMixin
from eth_utils import keccak
from eth_utils import keccak, to_hex
from hexbytes import HexBytes

from ape_safe.client.base import BaseSafeClient
Expand Down Expand Up @@ -70,7 +70,7 @@ def _all_transactions(
yield tx

def get_confirmations(self, safe_tx_hash: SafeTxID) -> Iterator[SafeTxConfirmation]:
tx_hash = cast(SafeTxID, HexBytes(safe_tx_hash).hex())
tx_hash = cast(SafeTxID, to_hex(HexBytes(safe_tx_hash)))
if safe_tx_data := self.transactions.get(tx_hash):
yield from safe_tx_data.confirmations

Expand All @@ -87,7 +87,7 @@ def post_transaction(
)
for signer, sig in signatures.items()
)
tx_id = cast(SafeTxID, HexBytes(safe_tx_data.safe_tx_hash).hex())
tx_id = cast(SafeTxID, to_hex(HexBytes(safe_tx_data.safe_tx_hash)))
self.transactions[tx_id] = safe_tx_data
if safe_tx_data.nonce in self.transactions_by_nonce:
self.transactions_by_nonce[safe_tx_data.nonce].append(tx_id)
Expand All @@ -105,7 +105,7 @@ def post_signatures(
if isinstance(safe_tx_or_hash, (str, bytes, int))
else get_safe_tx_hash(safe_tx_or_hash)
)
tx_id = cast(SafeTxID, HexBytes(safe_tx_id).hex())
tx_id = cast(SafeTxID, to_hex(HexBytes(safe_tx_id)))
self.transactions[tx_id].confirmations.append(
SafeTxConfirmation(
owner=signer,
Expand Down
4 changes: 2 additions & 2 deletions ape_safe/client/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from ape.types import AddressType, HexBytes
from eip712.common import SafeTxV1, SafeTxV2
from eth_typing import HexStr
from eth_utils import add_0x_prefix
from eth_utils import add_0x_prefix, to_hex
from pydantic import BaseModel, Field

from ape_safe.utils import get_safe_tx_hash
Expand Down Expand Up @@ -93,7 +93,7 @@ def base_tx_dict(self) -> dict:

def __str__(self) -> str:
# TODO: Decode data
data_hex = self.data.hex() if self.data else ""
data_hex = to_hex(self.data) if self.data else ""
if len(data_hex) > 40:
data_hex = f"{data_hex[:18]}....{data_hex[-18:]}"

Expand Down
4 changes: 2 additions & 2 deletions ape_safe/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from typing import TYPE_CHECKING, cast

from eip712.messages import calculate_hash
from eth_utils import to_int
from eth_utils import to_hex, to_int

if TYPE_CHECKING:
from ape.types import AddressType, MessageSignature
Expand All @@ -19,4 +19,4 @@ def order_by_signer(

def get_safe_tx_hash(safe_tx) -> "SafeTxID":
message_hash = calculate_hash(safe_tx.signable_message)
return cast("SafeTxID", message_hash.hex())
return cast("SafeTxID", to_hex(message_hash))
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ addopts = """
--cov-report html
--cov-report xml
--cov=ape_safe
--show-internal
"""
python_files = "test_*.py"
testpaths = "tests"
Expand Down
12 changes: 6 additions & 6 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"pytest-xdist", # multi-process runner
"pytest-cov", # Coverage analyzer plugin
"hypothesis>=6.2.0,<7.0", # Strategy-based fuzzer
"ape-foundry>=0.8", # Used as the testing provider
"ape-foundry>=0.8.7", # Used as the testing provider
"ape-solidity>=0.8", # Needed for compiling the Safe contracts
],
"lint": [
Expand Down Expand Up @@ -64,12 +64,12 @@
url="https://github.com/ApeWorX/ape-safe",
include_package_data=True,
install_requires=[
"eth-ape>=0.8.14,<0.9",
"click>=8.1.7,<9",
"eip712>=0.2.10,<3",
"eth-ape>=0.8.21,<0.9",
"eth-utils>=2.1.0,<6",
"pydantic>=2.10.2,<3",
"requests>=2.31.0,<3",
"eip712", # Use same version as eth-ape
"click", # Use same version as eth-ape
"pydantic", # Use same version as eth-ape
"eth-utils", # Use same version as eth-ape
],
entry_points={
"ape_cli_subcommands": [
Expand Down

0 comments on commit 0456b72

Please sign in to comment.