Skip to content

Commit

Permalink
feat: support 41 prefix TRON address
Browse files Browse the repository at this point in the history
  • Loading branch information
c0mm4nd committed Aug 26, 2024
1 parent 277f768 commit 04edbfa
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 11 deletions.
21 changes: 21 additions & 0 deletions tests/test_common.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import unittest
from web3research.common.types import Address, ChainStyle


class TestCommon(unittest.TestCase):
def __init__(self, methodName: str = "runTest") -> None:
super().__init__(methodName)

def test_address(self):
USDT_TAddr = Address("TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t")
USDT_41Addr = "41"+USDT_TAddr.addr_hex
print(USDT_41Addr)
print(USDT_TAddr.string(ChainStyle.TRON))
print(Address(USDT_TAddr.string(ChainStyle.TRON)).string(ChainStyle.TRON))
print(Address(USDT_41Addr).string(ChainStyle.TRON))

USDT_ETHAddr = Address("0xdac17f958d2ee523a2206206994597c13d831ec7")
print(USDT_ETHAddr.addr_hex)
print(USDT_ETHAddr.string(ChainStyle.ETH))
if __name__ == "__main__":
unittest.main()
27 changes: 16 additions & 11 deletions web3research/common/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,18 +27,19 @@ def __init__(self, addr: Optional[str] = None, addr_hex: Optional[str] = None):
"""
if addr:
self.addr = addr
if addr.startswith("0x"):
if addr.startswith("0x") and len(addr) == 42:
self.addr_hex = addr.removeprefix("0x")
elif addr.startswith("T"):
assert len(self.addr_hex) == 40, "Invalid ETH address"
elif addr.startswith("T") and len(addr) == 34:
self.addr_hex = base58.b58decode_check(addr)[1:].hex()
assert len(self.addr_hex) == 40, "Invalid TRON address"
else:
# check is addr unhexifiable
try:
int(addr, 16)
except ValueError:
raise ValueError("Invalid address")
elif addr.startswith("41") and len(addr) == 42:
self.addr_hex = addr.removeprefix("41")
assert len(self.addr_hex) == 40, "Invalid TRON address"
elif len(addr) == 40:
self.addr_hex = addr
else:
raise ValueError("Invalid address")
else:
assert addr_hex is not None, "Either addr or addr_hex must be provided"
self.addr = addr_hex
Expand Down Expand Up @@ -91,10 +92,13 @@ def __init__(self, hash: Optional[str], hash_hex: Optional[str] = None):
"""
if hash:
self.hash = hash
if hash.startswith("0x"):
if hash.startswith("0x") and len(hash) == 66:
self.hash_hex = hash.removeprefix("0x")
else:
assert len(self.hash_hex) == 64, "Invalid ETH hash"
elif len(hash) == 64:
self.hash_hex = hash
else:
raise ValueError("Invalid hash")
else:
assert hash_hex is not None, "Either hash or hash_hex must be provided"
self.hash = hash_hex
Expand Down Expand Up @@ -124,4 +128,5 @@ def string(self, chain_style: ChainStyle):
elif chain_style == ChainStyle.ETH:
return "0x" + self.hash_hex
else:
raise ValueError("Invalid chain style")
raise ValueError("Invalid chain style")

0 comments on commit 04edbfa

Please sign in to comment.