Skip to content

Commit b2cf95b

Browse files
committed
Added better typing
1 parent 0cda999 commit b2cf95b

File tree

6 files changed

+64
-51
lines changed

6 files changed

+64
-51
lines changed

async_substrate_interface/async_substrate.py

Lines changed: 30 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -689,7 +689,7 @@ async def _start_receiving(self):
689689
except ConnectionClosed:
690690
await self.connect(force=True)
691691

692-
async def send(self, payload: dict) -> int:
692+
async def send(self, payload: dict) -> str:
693693
"""
694694
Sends a payload to the websocket connection.
695695
@@ -714,6 +714,7 @@ async def send(self, payload: dict) -> int:
714714
return original_id
715715
except (ConnectionClosed, ssl.SSLError, EOFError):
716716
await self.connect(force=True)
717+
return await self.send(payload)
717718

718719
async def retrieve(self, item_id: int) -> Optional[dict]:
719720
"""
@@ -911,7 +912,7 @@ async def name(self):
911912
return self._name
912913

913914
async def get_storage_item(
914-
self, module: str, storage_function: str, block_hash: str = None
915+
self, module: str, storage_function: str, block_hash: Optional[str] = None
915916
):
916917
runtime = await self.init_runtime(block_hash=block_hash)
917918
metadata_pallet = runtime.metadata.get_metadata_pallet(module)
@@ -1154,7 +1155,7 @@ async def create_storage_key(
11541155
pallet: str,
11551156
storage_function: str,
11561157
params: Optional[list] = None,
1157-
block_hash: str = None,
1158+
block_hash: Optional[str] = None,
11581159
) -> StorageKey:
11591160
"""
11601161
Create a `StorageKey` instance providing storage function details. See `subscribe_storage()`.
@@ -1169,7 +1170,7 @@ async def create_storage_key(
11691170
StorageKey
11701171
"""
11711172
runtime = await self.init_runtime(block_hash=block_hash)
1172-
1173+
params = params or []
11731174
return StorageKey.create_from_storage_function(
11741175
pallet,
11751176
storage_function,
@@ -1424,7 +1425,7 @@ async def get_metadata_error(
14241425
return error
14251426

14261427
async def get_metadata_runtime_call_functions(
1427-
self, block_hash: str = None, runtime: Optional[Runtime] = None
1428+
self, block_hash: Optional[str] = None, runtime: Optional[Runtime] = None
14281429
) -> list[GenericRuntimeCallDefinition]:
14291430
"""
14301431
Get a list of available runtime API calls
@@ -1763,7 +1764,7 @@ async def get_block_header(
17631764
ignore_decoding_errors: bool = False,
17641765
include_author: bool = False,
17651766
finalized_only: bool = False,
1766-
) -> dict:
1767+
) -> Optional[dict]:
17671768
"""
17681769
Retrieves a block header and decodes its containing log digest items. If `block_hash` and `block_number`
17691770
is omitted the chain tip will be retrieved, or the finalized head if `finalized_only` is set to true.
@@ -1790,7 +1791,7 @@ async def get_block_header(
17901791
block_hash = await self.get_block_hash(block_number)
17911792

17921793
if block_hash is None:
1793-
return
1794+
return None
17941795

17951796
if block_hash and finalized_only:
17961797
raise ValueError(
@@ -1820,7 +1821,7 @@ async def get_block_header(
18201821

18211822
async def subscribe_block_headers(
18221823
self,
1823-
subscription_handler: callable,
1824+
subscription_handler: Callable,
18241825
ignore_decoding_errors: bool = False,
18251826
include_author: bool = False,
18261827
finalized_only=False,
@@ -1902,7 +1903,7 @@ def retrieve_extrinsic_by_hash(
19021903
)
19031904

19041905
async def get_extrinsics(
1905-
self, block_hash: str = None, block_number: int = None
1906+
self, block_hash: Optional[str] = None, block_number: Optional[int] = None
19061907
) -> Optional[list["AsyncExtrinsicReceipt"]]:
19071908
"""
19081909
Return all extrinsics for given block_hash or block_number
@@ -2780,7 +2781,7 @@ async def create_signed_extrinsic(
27802781
self,
27812782
call: GenericCall,
27822783
keypair: Keypair,
2783-
era: Optional[dict] = None,
2784+
era: Optional[Union[dict, str]] = None,
27842785
nonce: Optional[int] = None,
27852786
tip: int = 0,
27862787
tip_asset_id: Optional[int] = None,
@@ -2932,12 +2933,12 @@ async def _do_runtime_call_old(
29322933
params: Optional[Union[list, dict]] = None,
29332934
block_hash: Optional[str] = None,
29342935
runtime: Optional[Runtime] = None,
2935-
) -> ScaleType:
2936+
) -> ScaleObj:
29362937
logger.debug(
29372938
f"Decoding old runtime call: {api}.{method} with params: {params} at block hash: {block_hash}"
29382939
)
29392940
runtime_call_def = _TYPE_REGISTRY["runtime_api"][api]["methods"][method]
2940-
2941+
params = params or []
29412942
# Encode params
29422943
param_data = b""
29432944

@@ -3245,7 +3246,7 @@ async def get_payment_info(
32453246
return result.value
32463247

32473248
async def get_type_registry(
3248-
self, block_hash: str = None, max_recursion: int = 4
3249+
self, block_hash: Optional[str] = None, max_recursion: int = 4
32493250
) -> dict:
32503251
"""
32513252
Generates an exhaustive list of which RUST types exist in the runtime specified at given block_hash (or
@@ -3284,7 +3285,7 @@ async def get_type_registry(
32843285
return type_registry
32853286

32863287
async def get_type_definition(
3287-
self, type_string: str, block_hash: str = None
3288+
self, type_string: str, block_hash: Optional[str] = None
32883289
) -> str:
32893290
"""
32903291
Retrieves SCALE encoding specifications of given type_string
@@ -3589,11 +3590,11 @@ async def create_multisig_extrinsic(
35893590
keypair: Keypair,
35903591
multisig_account: MultiAccountId,
35913592
max_weight: Optional[Union[dict, int]] = None,
3592-
era: dict = None,
3593-
nonce: int = None,
3593+
era: Optional[dict] = None,
3594+
nonce: Optional[int] = None,
35943595
tip: int = 0,
3595-
tip_asset_id: int = None,
3596-
signature: Union[bytes, str] = None,
3596+
tip_asset_id: Optional[int] = None,
3597+
signature: Optional[Union[bytes, str]] = None,
35973598
) -> GenericExtrinsic:
35983599
"""
35993600
Create a Multisig extrinsic that will be signed by one of the signatories. Checks on-chain if the threshold
@@ -3878,6 +3879,9 @@ async def get_block_number(self, block_hash: Optional[str] = None) -> int:
38783879
elif "result" in response:
38793880
if response["result"]:
38803881
return int(response["result"]["number"], 16)
3882+
raise SubstrateRequestException(
3883+
f"Unable to retrieve block number for {block_hash}"
3884+
)
38813885

38823886
async def close(self):
38833887
"""
@@ -3973,14 +3977,14 @@ async def get_async_substrate_interface(
39733977
"""
39743978
substrate = AsyncSubstrateInterface(
39753979
url,
3976-
use_remote_preset,
3977-
auto_discover,
3978-
ss58_format,
3979-
type_registry,
3980-
chain_name,
3981-
max_retries,
3982-
retry_timeout,
3983-
_mock,
3980+
use_remote_preset=use_remote_preset,
3981+
auto_discover=auto_discover,
3982+
ss58_format=ss58_format,
3983+
type_registry=type_registry,
3984+
chain_name=chain_name,
3985+
max_retries=max_retries,
3986+
retry_timeout=retry_timeout,
3987+
_mock=_mock,
39843988
)
39853989
await substrate.initialize()
39863990
return substrate

async_substrate_interface/sync_substrate.py

Lines changed: 27 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -641,7 +641,7 @@ def connect(self, init=False):
641641
raise ConnectionError(e)
642642

643643
def get_storage_item(
644-
self, module: str, storage_function: str, block_hash: str = None
644+
self, module: str, storage_function: str, block_hash: Optional[str] = None
645645
):
646646
self.init_runtime(block_hash=block_hash)
647647
metadata_pallet = self.runtime.metadata.get_metadata_pallet(module)
@@ -659,7 +659,9 @@ def _get_current_block_hash(
659659
return self.last_block_hash
660660
return block_hash
661661

662-
def _load_registry_at_block(self, block_hash: Optional[str]) -> MetadataV15:
662+
def _load_registry_at_block(
663+
self, block_hash: Optional[str]
664+
) -> tuple[Optional[MetadataV15], Optional[PortableRegistry]]:
663665
# Should be called for any block that fails decoding.
664666
# Possibly the metadata was different.
665667
try:
@@ -864,7 +866,7 @@ def create_storage_key(
864866
pallet: str,
865867
storage_function: str,
866868
params: Optional[list] = None,
867-
block_hash: str = None,
869+
block_hash: Optional[str] = None,
868870
) -> StorageKey:
869871
"""
870872
Create a `StorageKey` instance providing storage function details. See `subscribe_storage()`.
@@ -883,7 +885,7 @@ def create_storage_key(
883885
return StorageKey.create_from_storage_function(
884886
pallet,
885887
storage_function,
886-
params,
888+
params or [],
887889
runtime_config=self.runtime_config,
888890
metadata=self.runtime.metadata,
889891
)
@@ -1104,7 +1106,7 @@ def get_metadata_error(self, module_name, error_name, block_hash=None):
11041106
return error
11051107

11061108
def get_metadata_runtime_call_functions(
1107-
self, block_hash: str = None
1109+
self, block_hash: Optional[str] = None
11081110
) -> list[GenericRuntimeCallDefinition]:
11091111
"""
11101112
Get a list of available runtime API calls
@@ -1124,7 +1126,7 @@ def get_metadata_runtime_call_functions(
11241126
return call_functions
11251127

11261128
def get_metadata_runtime_call_function(
1127-
self, api: str, method: str, block_hash: str = None
1129+
self, api: str, method: str, block_hash: Optional[str] = None
11281130
) -> GenericRuntimeCallDefinition:
11291131
"""
11301132
Get details of a runtime API call
@@ -1416,7 +1418,7 @@ def get_block_header(
14161418
ignore_decoding_errors: bool = False,
14171419
include_author: bool = False,
14181420
finalized_only: bool = False,
1419-
) -> dict:
1421+
) -> Optional[dict]:
14201422
"""
14211423
Retrieves a block header and decodes its containing log digest items. If `block_hash` and `block_number`
14221424
is omitted the chain tip will be retrieved, or the finalized head if `finalized_only` is set to true.
@@ -1473,7 +1475,7 @@ def get_block_header(
14731475

14741476
def subscribe_block_headers(
14751477
self,
1476-
subscription_handler: callable,
1478+
subscription_handler: Callable,
14771479
ignore_decoding_errors: bool = False,
14781480
include_author: bool = False,
14791481
finalized_only=False,
@@ -1555,7 +1557,7 @@ def retrieve_extrinsic_by_hash(
15551557
)
15561558

15571559
def get_extrinsics(
1558-
self, block_hash: str = None, block_number: int = None
1560+
self, block_hash: str = None, block_number: Optional[int] = None
15591561
) -> Optional[list["ExtrinsicReceipt"]]:
15601562
"""
15611563
Return all extrinsics for given block_hash or block_number
@@ -2349,7 +2351,7 @@ def create_signed_extrinsic(
23492351
self,
23502352
call: GenericCall,
23512353
keypair: Keypair,
2352-
era: Optional[dict] = None,
2354+
era: Optional[Union[dict, str]] = None,
23532355
nonce: Optional[int] = None,
23542356
tip: int = 0,
23552357
tip_asset_id: Optional[int] = None,
@@ -2496,7 +2498,7 @@ def _do_runtime_call_old(
24962498
method: str,
24972499
params: Optional[Union[list, dict]] = None,
24982500
block_hash: Optional[str] = None,
2499-
) -> ScaleType:
2501+
) -> ScaleObj:
25002502
logger.debug(
25012503
f"Decoding old runtime call: {api}.{method} with params: {params} at block hash: {block_hash}"
25022504
)
@@ -2544,7 +2546,7 @@ def runtime_call(
25442546
method: str,
25452547
params: Optional[Union[list, dict]] = None,
25462548
block_hash: Optional[str] = None,
2547-
) -> ScaleType:
2549+
) -> ScaleObj:
25482550
"""
25492551
Calls a runtime API method
25502552
@@ -2770,7 +2772,9 @@ def get_payment_info(self, call: GenericCall, keypair: Keypair) -> dict[str, Any
27702772

27712773
return result.value
27722774

2773-
def get_type_registry(self, block_hash: str = None, max_recursion: int = 4) -> dict:
2775+
def get_type_registry(
2776+
self, block_hash: Optional[str] = None, max_recursion: int = 4
2777+
) -> dict:
27742778
"""
27752779
Generates an exhaustive list of which RUST types exist in the runtime specified at given block_hash (or
27762780
chaintip if block_hash is omitted)
@@ -2807,7 +2811,9 @@ def get_type_registry(self, block_hash: str = None, max_recursion: int = 4) -> d
28072811

28082812
return type_registry
28092813

2810-
def get_type_definition(self, type_string: str, block_hash: str = None) -> str:
2814+
def get_type_definition(
2815+
self, type_string: str, block_hash: Optional[str] = None
2816+
) -> str:
28112817
"""
28122818
Retrieves SCALE encoding specifications of given type_string
28132819
@@ -3052,11 +3058,11 @@ def create_multisig_extrinsic(
30523058
keypair: Keypair,
30533059
multisig_account: MultiAccountId,
30543060
max_weight: Optional[Union[dict, int]] = None,
3055-
era: dict = None,
3056-
nonce: int = None,
3061+
era: Optional[dict] = None,
3062+
nonce: Optional[int] = None,
30573063
tip: int = 0,
3058-
tip_asset_id: int = None,
3059-
signature: Union[bytes, str] = None,
3064+
tip_asset_id: Optional[int] = None,
3065+
signature: Optional[Union[bytes, str]] = None,
30603066
) -> GenericExtrinsic:
30613067
"""
30623068
Create a Multisig extrinsic that will be signed by one of the signatories. Checks on-chain if the threshold
@@ -3333,6 +3339,9 @@ def get_block_number(self, block_hash: Optional[str] = None) -> int:
33333339
elif "result" in response:
33343340
if response["result"]:
33353341
return int(response["result"]["number"], 16)
3342+
raise SubstrateRequestException(
3343+
f"Unable to determine block number for {block_hash}"
3344+
)
33363345

33373346
def close(self):
33383347
"""

async_substrate_interface/types.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -372,7 +372,7 @@ def __init__(self, payloads):
372372
self.responses = defaultdict(lambda: {"complete": False, "results": []})
373373
self.payloads_count = len(payloads)
374374

375-
def add_request(self, item_id: int, request_id: Any):
375+
def add_request(self, item_id: Union[int, str], request_id: Any):
376376
"""
377377
Adds an outgoing request to the responses map for later retrieval
378378
"""

async_substrate_interface/utils/cache.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,7 @@ def inner(self, *args, **kwargs):
127127
return decorator
128128

129129

130-
def async_sql_lru_cache(maxsize=None):
130+
def async_sql_lru_cache(maxsize: Optional[int] = None):
131131
def decorator(func):
132132
@cached_fetcher(max_size=maxsize)
133133
async def inner(self, *args, **kwargs):
@@ -283,7 +283,7 @@ def __get__(self, instance, owner):
283283
return self._instances[instance]
284284

285285

286-
def cached_fetcher(max_size: int, cache_key_index: int = 0):
286+
def cached_fetcher(max_size: Optional[int] = None, cache_key_index: int = 0):
287287
"""Wrapper for CachedFetcher. See example in CachedFetcher docstring."""
288288

289289
def wrapper(method):

async_substrate_interface/utils/decoding.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -160,7 +160,7 @@ def concat_hash_len(key_hasher: str) -> int:
160160

161161

162162
def legacy_scale_decode(
163-
type_string: str, scale_bytes: Union[str, ScaleBytes], runtime: "Runtime"
163+
type_string: str, scale_bytes: Union[str, bytes, ScaleBytes], runtime: "Runtime"
164164
):
165165
if isinstance(scale_bytes, (str, bytes)):
166166
scale_bytes = ScaleBytes(scale_bytes)

async_substrate_interface/utils/storage.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -48,9 +48,9 @@ def create_from_data(
4848
data: bytes,
4949
runtime_config: RuntimeConfigurationObject,
5050
metadata: GenericMetadataVersioned,
51-
value_scale_type: str = None,
52-
pallet: str = None,
53-
storage_function: str = None,
51+
value_scale_type: Optional[str] = None,
52+
pallet: Optional[str] = None,
53+
storage_function: Optional[str] = None,
5454
) -> "StorageKey":
5555
"""
5656
Create a StorageKey instance providing raw storage key bytes

0 commit comments

Comments
 (0)