Skip to content

Commit 46cf95f

Browse files
committed
Fixes + formatting.
1 parent 04e7050 commit 46cf95f

File tree

5 files changed

+129
-127
lines changed

5 files changed

+129
-127
lines changed

async_substrate_interface/async_substrate.py

Lines changed: 33 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -727,13 +727,7 @@ async def initialize(self):
727727
if not self._chain:
728728
chain = await self.rpc_request("system_chain", [])
729729
self._chain = chain.get("result")
730-
init_load = await asyncio.gather(
731-
self.init_runtime(),
732-
return_exceptions=True,
733-
)
734-
for potential_exception in init_load:
735-
if isinstance(potential_exception, Exception):
736-
raise potential_exception
730+
await self.init_runtime()
737731
self.initialized = True
738732
self._initializing = False
739733

@@ -775,7 +769,9 @@ async def name(self):
775769
self._name = (await self.rpc_request("system_name", [])).get("result")
776770
return self._name
777771

778-
async def get_storage_item(self, module: str, storage_function: str, block_hash: str = None):
772+
async def get_storage_item(
773+
self, module: str, storage_function: str, block_hash: str = None
774+
):
779775
await self.init_runtime(block_hash=block_hash)
780776
metadata_pallet = self.runtime.metadata.get_metadata_pallet(module)
781777
storage_item = metadata_pallet.get_storage_function(storage_function)
@@ -792,7 +788,9 @@ async def _get_current_block_hash(
792788
return self.last_block_hash
793789
return block_hash
794790

795-
async def _load_registry_at_block(self, block_hash: Optional[str]) -> MetadataV15:
791+
async def _load_registry_at_block(
792+
self, block_hash: Optional[str]
793+
) -> tuple[MetadataV15, PortableRegistry]:
796794
# Should be called for any block that fails decoding.
797795
# Possibly the metadata was different.
798796
try:
@@ -817,7 +815,7 @@ async def _load_registry_at_block(self, block_hash: Optional[str]) -> MetadataV1
817815
metadata = MetadataV15.decode_from_metadata_option(metadata_option_bytes)
818816
registry = PortableRegistry.from_metadata_v15(metadata)
819817
self._load_registry_type_map(registry)
820-
return metadata,registry
818+
return metadata, registry
821819

822820
async def _wait_for_registry(self, _attempt: int = 1, _retries: int = 3) -> None:
823821
async def _waiter():
@@ -899,7 +897,7 @@ async def decode_scale(
899897
else:
900898
return obj
901899

902-
async def load_runtime(self,runtime):
900+
async def load_runtime(self, runtime):
903901
self.runtime = runtime
904902

905903
# Update type registry
@@ -965,39 +963,31 @@ async def init_runtime(
965963

966964
runtime_info = await self.get_block_runtime_info(runtime_block_hash)
967965

968-
# TODO when someone gets time, someone'd like to add this and the metadata v15 as tasks with callbacks
969-
# TODO to update the caches, but someone doesn't have time now.
970-
metadata = await self.get_block_metadata(
971-
block_hash=runtime_block_hash, decode=True
966+
metadata, (metadata_v15, registry) = await asyncio.gather(
967+
self.get_block_metadata(block_hash=runtime_block_hash, decode=True),
968+
self._load_registry_at_block(block_hash=runtime_block_hash),
972969
)
973970
if metadata is None:
974971
# does this ever happen?
975972
raise SubstrateRequestException(
976973
f"No metadata for block '{runtime_block_hash}'"
977974
)
978975
logger.debug(
979-
"Retrieved metadata for {} from Substrate node".format(
980-
runtime_version
981-
)
982-
)
983-
984-
metadata_v15,registry = await self._load_registry_at_block(block_hash=runtime_block_hash)
985-
logger.debug(
986-
"Retrieved metadata v15 for {} from Substrate node".format(
987-
runtime_version
988-
)
976+
f"Retrieved metadata and metadata v15 for {runtime_version} from Substrate node"
989977
)
990978

991979
runtime = Runtime(
992-
chain=self.chain,
993-
runtime_config=self.runtime_config,
994-
metadata=metadata,
995-
type_registry=self.type_registry,
996-
metadata_v15=metadata_v15,
997-
runtime_info=runtime_info,
998-
registry=registry,
999-
)
1000-
self.runtime_cache.add_item(runtime_version=runtime_version, runtime=runtime)
980+
chain=self.chain,
981+
runtime_config=self.runtime_config,
982+
metadata=metadata,
983+
type_registry=self.type_registry,
984+
metadata_v15=metadata_v15,
985+
runtime_info=runtime_info,
986+
registry=registry,
987+
)
988+
self.runtime_cache.add_item(
989+
runtime_version=runtime_version, runtime=runtime
990+
)
1001991

1002992
await self.load_runtime(runtime)
1003993

@@ -1669,30 +1659,28 @@ def convert_event_data(data):
16691659
events.append(convert_event_data(item))
16701660
return events
16711661

1672-
@a.lru_cache(maxsize=16) # small cache with large items
1673-
async def get_parent_block_hash(self,block_hash):
1662+
@a.lru_cache(maxsize=512) # large cache with small items
1663+
async def get_parent_block_hash(self, block_hash):
16741664
block_header = await self.rpc_request("chain_getHeader", [block_hash])
16751665

16761666
if block_header["result"] is None:
1677-
raise SubstrateRequestException(
1678-
f'Block not found for "{block_hash}"'
1679-
)
1667+
raise SubstrateRequestException(f'Block not found for "{block_hash}"')
16801668
parent_block_hash: str = block_header["result"]["parentHash"]
16811669

1682-
if int(parent_block_hash,16) == 0:
1670+
if int(parent_block_hash, 16) == 0:
16831671
# "0x0000000000000000000000000000000000000000000000000000000000000000"
16841672
return block_hash
16851673
return parent_block_hash
16861674

1687-
@a.lru_cache(maxsize=16) # small cache with large items
1675+
@a.lru_cache(maxsize=16) # small cache with large items
16881676
async def get_block_runtime_info(self, block_hash: str) -> dict:
16891677
"""
16901678
Retrieve the runtime info of given block_hash
16911679
"""
16921680
response = await self.rpc_request("state_getRuntimeVersion", [block_hash])
16931681
return response.get("result")
16941682

1695-
@a.lru_cache(maxsize=512) # large cache with small items
1683+
@a.lru_cache(maxsize=512) # large cache with small items
16961684
async def get_block_runtime_version_for(self, block_hash: str):
16971685
"""
16981686
Retrieve the runtime version of the parent of a given block_hash
@@ -1997,7 +1985,7 @@ async def rpc_request(
19971985
else:
19981986
raise SubstrateRequestException(result[payload_id][0])
19991987

2000-
@a.lru_cache(maxsize=512) # block_id->block_hash does not change
1988+
@a.lru_cache(maxsize=512) # block_id->block_hash does not change
20011989
async def get_block_hash(self, block_id: int) -> str:
20021990
return (await self.rpc_request("chain_getBlockHash", [block_id]))["result"]
20031991

@@ -2177,7 +2165,7 @@ async def create_scale_object(
21772165
if "metadata" not in kwargs:
21782166
kwargs["metadata"] = self.runtime.metadata
21792167

2180-
return runtime.runtime_config.create_scale_object(
2168+
return self.runtime.runtime_config.create_scale_object(
21812169
type_string, data=data, **kwargs
21822170
)
21832171

@@ -2358,7 +2346,7 @@ async def create_signed_extrinsic(
23582346
The signed Extrinsic
23592347
"""
23602348
# only support creating extrinsics for current block
2361-
await self.init_runtime(block_id=self.get_block_number())
2349+
await self.init_runtime(block_id=await self.get_block_number())
23622350

23632351
# Check requirements
23642352
if not isinstance(call, GenericCall):

async_substrate_interface/sync_substrate.py

Lines changed: 26 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -583,7 +583,9 @@ def connect(self, init=False):
583583
else:
584584
return connect(self.chain_endpoint, max_size=self.ws_max_size)
585585

586-
def get_storage_item(self, module: str, storage_function: str, block_hash: str = None):
586+
def get_storage_item(
587+
self, module: str, storage_function: str, block_hash: str = None
588+
):
587589
self.init_runtime(block_hash=block_hash)
588590
metadata_pallet = self.runtime.metadata.get_metadata_pallet(module)
589591
storage_item = metadata_pallet.get_storage_function(storage_function)
@@ -613,7 +615,7 @@ def _load_registry_at_block(self, block_hash: Optional[str]) -> MetadataV15:
613615
metadata = MetadataV15.decode_from_metadata_option(metadata_option_bytes)
614616
registry = PortableRegistry.from_metadata_v15(metadata)
615617
self._load_registry_type_map(registry)
616-
return metadata,registry
618+
return metadata, registry
617619

618620
def decode_scale(
619621
self,
@@ -644,7 +646,7 @@ def decode_scale(
644646
else:
645647
return obj
646648

647-
def load_runtime(self,runtime):
649+
def load_runtime(self, runtime):
648650
self.runtime = runtime
649651

650652
# Update type registry
@@ -719,12 +721,10 @@ def init_runtime(
719721
f"No metadata for block '{runtime_block_hash}'"
720722
)
721723
logger.debug(
722-
"Retrieved metadata for {} from Substrate node".format(
723-
runtime_version
724-
)
724+
"Retrieved metadata for {} from Substrate node".format(runtime_version)
725725
)
726726

727-
metadata_v15,registry = self._load_registry_at_block(
727+
metadata_v15, registry = self._load_registry_at_block(
728728
block_hash=runtime_block_hash
729729
)
730730
logger.debug(
@@ -734,15 +734,17 @@ def init_runtime(
734734
)
735735

736736
runtime = Runtime(
737-
chain=self.chain,
738-
runtime_config=self.runtime_config,
739-
metadata=metadata,
740-
type_registry=self.type_registry,
741-
metadata_v15=metadata_v15,
742-
runtime_info=runtime_info,
743-
registry=registry,
744-
)
745-
self.runtime_cache.add_item(runtime_version=runtime_version, runtime=runtime)
737+
chain=self.chain,
738+
runtime_config=self.runtime_config,
739+
metadata=metadata,
740+
type_registry=self.type_registry,
741+
metadata_v15=metadata_v15,
742+
runtime_info=runtime_info,
743+
registry=registry,
744+
)
745+
self.runtime_cache.add_item(
746+
runtime_version=runtime_version, runtime=runtime
747+
)
746748

747749
self.load_runtime(runtime)
748750

@@ -1404,30 +1406,28 @@ def convert_event_data(data):
14041406
events.append(convert_event_data(item))
14051407
return events
14061408

1407-
@lru_cache(maxsize=16) # small cache with large items
1408-
def get_parent_block_hash(self,block_hash):
1409+
@lru_cache(maxsize=512) # large cache with small items
1410+
def get_parent_block_hash(self, block_hash):
14091411
block_header = self.rpc_request("chain_getHeader", [block_hash])
14101412

14111413
if block_header["result"] is None:
1412-
raise SubstrateRequestException(
1413-
f'Block not found for "{block_hash}"'
1414-
)
1414+
raise SubstrateRequestException(f'Block not found for "{block_hash}"')
14151415
parent_block_hash: str = block_header["result"]["parentHash"]
14161416

1417-
if int(parent_block_hash,16) == 0:
1417+
if int(parent_block_hash, 16) == 0:
14181418
# "0x0000000000000000000000000000000000000000000000000000000000000000"
14191419
return block_hash
14201420
return parent_block_hash
14211421

1422-
@lru_cache(maxsize=16) # small cache with large items
1422+
@lru_cache(maxsize=16) # small cache with large items
14231423
def get_block_runtime_info(self, block_hash: str) -> dict:
14241424
"""
14251425
Retrieve the runtime info of given block_hash
14261426
"""
14271427
response = self.rpc_request("state_getRuntimeVersion", [block_hash])
14281428
return response.get("result")
14291429

1430-
@lru_cache(maxsize=512) # large cache with small items
1430+
@lru_cache(maxsize=512) # large cache with small items
14311431
def get_block_runtime_version_for(self, block_hash: str):
14321432
"""
14331433
Retrieve the runtime version of the parent of a given block_hash
@@ -1727,7 +1727,7 @@ def rpc_request(
17271727
else:
17281728
raise SubstrateRequestException(result[payload_id][0])
17291729

1730-
@lru_cache(maxsize=512) # block_id->block_hash does not change
1730+
@lru_cache(maxsize=512) # block_id->block_hash does not change
17311731
def get_block_hash(self, block_id: int) -> str:
17321732
return self.rpc_request("chain_getBlockHash", [block_id])["result"]
17331733

@@ -1899,7 +1899,7 @@ def create_scale_object(
18991899
if "metadata" not in kwargs:
19001900
kwargs["metadata"] = self.runtime.metadata
19011901

1902-
return runtime.runtime_config.create_scale_object(
1902+
return self.runtime.runtime_config.create_scale_object(
19031903
type_string, data=data, **kwargs
19041904
)
19051905

async_substrate_interface/types.py

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ def retrieve(
4747
self,
4848
block: Optional[int] = None,
4949
block_hash: Optional[str] = None,
50-
runtime_version: Optional[int] = None
50+
runtime_version: Optional[int] = None,
5151
) -> Optional["Runtime"]:
5252
if block is not None:
5353
return self.blocks.get(block)
@@ -71,7 +71,14 @@ class Runtime:
7171
registry: Optional[PortableRegistry] = None
7272

7373
def __init__(
74-
self, chain, runtime_config: RuntimeConfigurationObject, metadata, type_registry, metadata_v15=None, runtime_info=None, registry=None
74+
self,
75+
chain,
76+
runtime_config: RuntimeConfigurationObject,
77+
metadata,
78+
type_registry,
79+
metadata_v15=None,
80+
runtime_info=None,
81+
registry=None,
7582
):
7683
self.config = {}
7784
self.chain = chain
@@ -81,12 +88,13 @@ def __init__(
8188
self.metadata_v15 = metadata_v15
8289
self.runtime_info = runtime_info
8390
self.registry = registry
84-
self.runtime_version = runtime_info.get('specVersion')
91+
self.runtime_version = runtime_info.get("specVersion")
8592
self.transaction_version = runtime_info.get("transactionVersion")
8693

8794
def __str__(self):
8895
return f"Runtime: {self.chain} | {self.config}"
8996

97+
9098
# @property
9199
# def implements_scaleinfo(self) -> bool:
92100
# """
@@ -174,6 +182,7 @@ def __str__(self):
174182
# # Load type registries in runtime configuration
175183
# self.runtime_config.update_type_registry(self.type_registry)
176184

185+
177186
class RequestManager:
178187
RequestResults = dict[Union[str, int], list[Union[ScaleType, dict]]]
179188

@@ -613,7 +622,7 @@ def serialize_module_error(module, error, spec_version) -> dict:
613622
"spec_version": spec_version,
614623
}
615624

616-
def _load_registry_type_map(self,registry):
625+
def _load_registry_type_map(self, registry):
617626
registry_type_map = {}
618627
type_id_to_name = {}
619628
types = json.loads(registry.registry)["types"]
@@ -839,5 +848,7 @@ def _encode_scale(self, type_string, value: Any) -> bytes:
839848
else:
840849
value = value.value # Unwrap the value of the type
841850

842-
result = bytes(encode_by_type_string(type_string, self.registry, value))
851+
result = bytes(
852+
encode_by_type_string(type_string, self.runtime.registry, value)
853+
)
843854
return result

0 commit comments

Comments
 (0)