From 1922aeba38965d427195617626dfc9a7da62555b Mon Sep 17 00:00:00 2001 From: sslivkoff Date: Tue, 17 Sep 2024 21:23:20 +0000 Subject: [PATCH] add get_network_name() to python client --- python/mesc/__init__.py | 5 +++++ python/mesc/network_utils.py | 30 ++++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/python/mesc/__init__.py b/python/mesc/__init__.py index 5d6e603..cb70ca1 100644 --- a/python/mesc/__init__.py +++ b/python/mesc/__init__.py @@ -9,6 +9,9 @@ find_endpoints, get_global_metadata, ) +from .network_utils import ( + get_network_name, +) import typing @@ -26,6 +29,7 @@ 'get_endpoint_by_query', 'find_endpoints', 'get_global_metadata', + 'get_network_name', ) else: @@ -37,6 +41,7 @@ 'get_endpoint_by_query', 'find_endpoints', 'get_global_metadata', + 'get_network_name', ) __version__ = '0.2.0' diff --git a/python/mesc/network_utils.py b/python/mesc/network_utils.py index cf7e13e..2531556 100644 --- a/python/mesc/network_utils.py +++ b/python/mesc/network_utils.py @@ -62,3 +62,33 @@ def get_by_chain_id(mapping: typing.Mapping[str, T], chain_id: str) -> T | None: def chain_ids_equal(lhs: str, rhs: str) -> bool: return chain_id_to_standard_hex(lhs) == chain_id_to_standard_hex(rhs) + + +def get_network_name(network: int | str) -> str | None: + if isinstance(network, str): + # 1. check if a known name + if network in network_names.network_names.values(): + for k, v in network_names.network_names.items(): + if v == network: + return v + + # 2. check if a hex number + try: + if network.startswith('0x'): + as_int = int(network, 16) + else: + as_int = int(network) + as_int_str = str(as_int) + if as_int_str in network_names.network_names: + return network_names.network_names[as_int_str] + except ValueError: + pass + + # 3. return as a name + return network + + elif isinstance(network, int): + return network_names.network_names.get(str(network)) + + else: + raise Exception('invalid format for network')