From e8dd4917970a3a6edfaf304cf67a7f873ea98bbc Mon Sep 17 00:00:00 2001 From: Abel Armoa <30988000+aarmoa@users.noreply.github.com> Date: Tue, 15 Jul 2025 16:46:51 -0300 Subject: [PATCH] [cp-508] Added logic in Address class to create an instance from an Ethereum address --- pyinjective/wallet.py | 7 +++++++ tests/test_wallet.py | 16 ++++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/pyinjective/wallet.py b/pyinjective/wallet.py index b142e7df..0e321859 100644 --- a/pyinjective/wallet.py +++ b/pyinjective/wallet.py @@ -232,6 +232,13 @@ def from_cons_bech32(cls, bech: str) -> "Address": """Create an address instance from a bech32-encoded consensus address""" return cls._from_bech32(bech, BECH32_ADDR_CONS_PREFIX) + @classmethod + def from_eth_address(cls, eth_address: str) -> "Address": + """Create an address instance from a hex-encoded Ethereum address""" + eth_address_without_prefix = eth_address[2:] if eth_address.startswith("0x") else eth_address + bytes_representation = bytes.fromhex(eth_address_without_prefix) + return cls(bytes_representation) + def _to_bech32(self, prefix: str) -> str: five_bit_r = convertbits(self.addr, 8, 5) assert five_bit_r is not None, "Unsuccessful bech32.convertbits call" diff --git a/tests/test_wallet.py b/tests/test_wallet.py index a2740a97..5b62dd2a 100644 --- a/tests/test_wallet.py +++ b/tests/test_wallet.py @@ -28,3 +28,19 @@ def test_convert_public_key_to_address(self): expected_address = Address(hashed_value[12:]) assert expected_address == address + + +class TestAddress: + def test_from_acc_bech32(self): + address = Address.from_acc_bech32("inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r") + assert address.to_acc_bech32() == "inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r" + + eth_address = address.get_ethereum_address() + assert eth_address == "0xbdaedec95d563fb05240d6e01821008454c24c36" + + def test_from_eth(self): + address = Address.from_eth_address("0xbdaedec95d563fb05240d6e01821008454c24c36") + assert address.to_acc_bech32() == "inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r" + + eth_address = address.get_ethereum_address() + assert eth_address == "0xbdaedec95d563fb05240d6e01821008454c24c36"