Skip to content

Commit

Permalink
fix: specify encoding when calling bytes [APE-1186] (#1539)
Browse files Browse the repository at this point in the history
  • Loading branch information
z80dev authored Jul 24, 2023
1 parent 3112e74 commit d477765
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 4 deletions.
20 changes: 16 additions & 4 deletions src/ape/api/transactions.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,11 +170,23 @@ def __repr__(self) -> str:
def __str__(self) -> str:
data = self.dict()
if len(data["data"]) > 9:
data["data"] = (
"0x" + bytes(data["data"][:3]).hex() + "..." + bytes(data["data"][-3:]).hex()
)
# only want to specify encoding if data["data"] is a string
if isinstance(data["data"], str):
data["data"] = (
"0x"
+ bytes(data["data"][:3], encoding="utf8").hex()
+ "..."
+ bytes(data["data"][-3:], encoding="utf8").hex()
)
else:
data["data"] = (
"0x" + bytes(data["data"][:3]).hex() + "..." + bytes(data["data"][-3:]).hex()
)
else:
data["data"] = "0x" + bytes(data["data"]).hex()
if isinstance(data["data"], str):
data["data"] = "0x" + bytes(data["data"], encoding="utf8").hex()
else:
data["data"] = "0x" + bytes(data["data"]).hex()
params = "\n ".join(f"{k}: {v}" for k, v in data.items())
return f"{self.__class__.__name__}:\n {params}"

Expand Down
10 changes: 10 additions & 0 deletions tests/functional/test_transaction.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,3 +72,13 @@ def test_transaction_dict_excludes_none_values():
txn.value = None # type: ignore
actual = txn.dict()
assert "value" not in actual


def test_txn_str_when_data_is_bytes(ethereum):
"""
Tests against a condition that would cause transactions to
fail with string-encoding errors.
"""
txn = ethereum.create_transaction(data=HexBytes("0x123"))
actual = str(txn)
assert isinstance(actual, str)

0 comments on commit d477765

Please sign in to comment.