-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsync_substrate.py
2894 lines (2435 loc) · 106 KB
/
sync_substrate.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import functools
import logging
import random
from hashlib import blake2b
from typing import Optional, Union, Callable, Any
from bittensor_wallet.keypair import Keypair
from bittensor_wallet.utils import SS58_FORMAT
from bt_decode import MetadataV15, PortableRegistry, decode as decode_by_type_string
from scalecodec import (
GenericCall,
GenericExtrinsic,
GenericRuntimeCallDefinition,
ss58_encode,
)
from scalecodec.base import RuntimeConfigurationObject, ScaleBytes, ScaleType
from websockets.sync.client import connect
from websockets.exceptions import ConnectionClosed
from async_substrate_interface.errors import (
ExtrinsicNotFound,
SubstrateRequestException,
BlockNotFound,
)
from async_substrate_interface.types import (
SubstrateMixin,
RuntimeCache,
Runtime,
RequestManager,
Preprocessed,
ScaleObj,
)
from async_substrate_interface.utils import hex_to_bytes, json, get_next_id
from async_substrate_interface.utils.decoding import (
_determine_if_old_runtime_call,
_bt_decode_to_dict_or_list,
)
from async_substrate_interface.utils.storage import StorageKey
from async_substrate_interface.type_registry import _TYPE_REGISTRY
ResultHandler = Callable[[dict, Any], tuple[dict, bool]]
logger = logging.getLogger("async_substrate_interface")
class ExtrinsicReceipt:
"""
Object containing information of submitted extrinsic. Block hash where extrinsic is included is required
when retrieving triggered events or determine if extrinsic was successful
"""
def __init__(
self,
substrate: "SubstrateInterface",
extrinsic_hash: Optional[str] = None,
block_hash: Optional[str] = None,
block_number: Optional[int] = None,
extrinsic_idx: Optional[int] = None,
finalized: bool = False,
):
"""
Object containing information of submitted extrinsic. Block hash where extrinsic is included is required
when retrieving triggered events or determine if extrinsic was successful
Args:
substrate: the AsyncSubstrateInterface instance
extrinsic_hash: the hash of the extrinsic
block_hash: the hash of the block on which this extrinsic exists
finalized: whether the extrinsic is finalized
"""
self.substrate = substrate
self.extrinsic_hash = extrinsic_hash
self.block_hash = block_hash
self.block_number = block_number
self.finalized = finalized
self.__extrinsic_idx = extrinsic_idx
self.__extrinsic = None
self.__triggered_events: Optional[list] = None
self.__is_success: Optional[bool] = None
self.__error_message = None
self.__weight = None
self.__total_fee_amount = None
def get_extrinsic_identifier(self) -> str:
"""
Returns the on-chain identifier for this extrinsic in format "[block_number]-[extrinsic_idx]" e.g. 134324-2
Returns
-------
str
"""
if self.block_number is None:
if self.block_hash is None:
raise ValueError(
"Cannot create extrinsic identifier: block_hash is not set"
)
self.block_number = self.substrate.get_block_number(self.block_hash)
if self.block_number is None:
raise ValueError(
"Cannot create extrinsic identifier: unknown block_hash"
)
return f"{self.block_number}-{self.extrinsic_idx}"
def retrieve_extrinsic(self):
if not self.block_hash:
raise ValueError(
"ExtrinsicReceipt can't retrieve events because it's unknown which block_hash it is "
"included, manually set block_hash or use `wait_for_inclusion` when sending extrinsic"
)
# Determine extrinsic idx
block = self.substrate.get_block(block_hash=self.block_hash)
extrinsics = block["extrinsics"]
if len(extrinsics) > 0:
if self.__extrinsic_idx is None:
self.__extrinsic_idx = self.__get_extrinsic_index(
block_extrinsics=extrinsics, extrinsic_hash=self.extrinsic_hash
)
if self.__extrinsic_idx >= len(extrinsics):
raise ExtrinsicNotFound()
self.__extrinsic = extrinsics[self.__extrinsic_idx]
@property
def extrinsic_idx(self) -> int:
"""
Retrieves the index of this extrinsic in containing block
Returns
-------
int
"""
if self.__extrinsic_idx is None:
self.retrieve_extrinsic()
return self.__extrinsic_idx
@property
def triggered_events(self) -> list:
"""
Gets triggered events for submitted extrinsic. block_hash where extrinsic is included is required, manually
set block_hash or use `wait_for_inclusion` when submitting extrinsic
Returns
-------
list
"""
if self.__triggered_events is None:
if not self.block_hash:
raise ValueError(
"ExtrinsicReceipt can't retrieve events because it's unknown which block_hash it is "
"included, manually set block_hash or use `wait_for_inclusion` when sending extrinsic"
)
if self.extrinsic_idx is None:
self.retrieve_extrinsic()
self.__triggered_events = []
for event in self.substrate.get_events(block_hash=self.block_hash):
if event["extrinsic_idx"] == self.extrinsic_idx:
self.__triggered_events.append(event)
return self.__triggered_events
@classmethod
def create_from_extrinsic_identifier(
cls, substrate: "SubstrateInterface", extrinsic_identifier: str
) -> "ExtrinsicReceipt":
"""
Create an `AsyncExtrinsicReceipt` with on-chain identifier for this extrinsic in format
"[block_number]-[extrinsic_idx]" e.g. 134324-2
Args:
substrate: SubstrateInterface
extrinsic_identifier: "[block_number]-[extrinsic_idx]" e.g. 134324-2
Returns:
AsyncExtrinsicReceipt of the extrinsic
"""
id_parts = extrinsic_identifier.split("-", maxsplit=1)
block_number: int = int(id_parts[0])
extrinsic_idx: int = int(id_parts[1])
# Retrieve block hash
block_hash = substrate.get_block_hash(block_number)
return cls(
substrate=substrate,
block_hash=block_hash,
block_number=block_number,
extrinsic_idx=extrinsic_idx,
)
def process_events(self):
if self.triggered_events:
self.__total_fee_amount = 0
# Process fees
has_transaction_fee_paid_event = False
for event in self.triggered_events:
if (
event["event"]["module_id"] == "TransactionPayment"
and event["event"]["event_id"] == "TransactionFeePaid"
):
self.__total_fee_amount = event["event"]["attributes"]["actual_fee"]
has_transaction_fee_paid_event = True
# Process other events
for event in self.triggered_events:
# Check events
if (
event["event"]["module_id"] == "System"
and event["event"]["event_id"] == "ExtrinsicSuccess"
):
self.__is_success = True
self.__error_message = None
if "dispatch_info" in event["event"]["attributes"]:
self.__weight = event["event"]["attributes"]["dispatch_info"][
"weight"
]
else:
# Backwards compatibility
self.__weight = event["event"]["attributes"]["weight"]
elif (
event["event"]["module_id"] == "System"
and event["event"]["event_id"] == "ExtrinsicFailed"
):
self.__is_success = False
dispatch_info = event["event"]["attributes"]["dispatch_info"]
dispatch_error = event["event"]["attributes"]["dispatch_error"]
self.__weight = dispatch_info["weight"]
if "Module" in dispatch_error:
module_index = dispatch_error["Module"][0]["index"]
error_index = int.from_bytes(
bytes(dispatch_error["Module"][0]["error"]),
byteorder="little",
signed=False,
)
if isinstance(error_index, str):
# Actual error index is first u8 in new [u8; 4] format
error_index = int(error_index[2:4], 16)
module_error = self.substrate.metadata.get_module_error(
module_index=module_index, error_index=error_index
)
self.__error_message = {
"type": "Module",
"name": module_error.name,
"docs": module_error.docs,
}
elif "BadOrigin" in dispatch_error:
self.__error_message = {
"type": "System",
"name": "BadOrigin",
"docs": "Bad origin",
}
elif "CannotLookup" in dispatch_error:
self.__error_message = {
"type": "System",
"name": "CannotLookup",
"docs": "Cannot lookup",
}
elif "Other" in dispatch_error:
self.__error_message = {
"type": "System",
"name": "Other",
"docs": "Unspecified error occurred",
}
elif not has_transaction_fee_paid_event:
if (
event["event"]["module_id"] == "Treasury"
and event["event"]["event_id"] == "Deposit"
):
self.__total_fee_amount += event["event"]["attributes"]["value"]
elif (
event["event"]["module_id"] == "Balances"
and event["event"]["event_id"] == "Deposit"
):
self.__total_fee_amount += event.value["attributes"]["amount"]
@property
def is_success(self) -> bool:
"""
Returns `True` if `ExtrinsicSuccess` event is triggered, `False` in case of `ExtrinsicFailed`
In case of False `error_message` will contain more details about the error
Returns
-------
bool
"""
if self.__is_success is None:
self.process_events()
return self.__is_success
@property
def error_message(self) -> Optional[dict]:
"""
Returns the error message if the extrinsic failed in format e.g.:
`{'type': 'System', 'name': 'BadOrigin', 'docs': 'Bad origin'}`
Returns
-------
dict
"""
if self.__error_message is None:
if self.is_success:
return None
self.process_events()
return self.__error_message
@property
def weight(self) -> Union[int, dict]:
"""
Contains the actual weight when executing this extrinsic
Returns
-------
int (WeightV1) or dict (WeightV2)
"""
if self.__weight is None:
self.process_events()
return self.__weight
@property
def total_fee_amount(self) -> int:
"""
Contains the total fee costs deducted when executing this extrinsic. This includes fee for the validator
(`Balances.Deposit` event) and the fee deposited for the treasury (`Treasury.Deposit` event)
Returns
-------
int
"""
if self.__total_fee_amount is None:
self.process_events()
return self.__total_fee_amount
# Helper functions
@staticmethod
def __get_extrinsic_index(block_extrinsics: list, extrinsic_hash: str) -> int:
"""
Returns the index of a provided extrinsic
"""
for idx, extrinsic in enumerate(block_extrinsics):
if (
extrinsic.extrinsic_hash
and f"0x{extrinsic.extrinsic_hash.hex()}" == extrinsic_hash
):
return idx
raise ExtrinsicNotFound()
# Backwards compatibility methods
def __getitem__(self, item):
return getattr(self, item)
def __iter__(self):
for item in self.__dict__.items():
yield item
def get(self, name):
return self[name]
class QueryMapResult:
def __init__(
self,
records: list,
page_size: int,
substrate: "SubstrateInterface",
module: Optional[str] = None,
storage_function: Optional[str] = None,
params: Optional[list] = None,
block_hash: Optional[str] = None,
last_key: Optional[str] = None,
max_results: Optional[int] = None,
ignore_decoding_errors: bool = False,
):
self.records = records
self.page_size = page_size
self.module = module
self.storage_function = storage_function
self.block_hash = block_hash
self.substrate = substrate
self.last_key = last_key
self.max_results = max_results
self.params = params
self.ignore_decoding_errors = ignore_decoding_errors
self.loading_complete = False
self._buffer = iter(self.records) # Initialize the buffer with initial records
def retrieve_next_page(self, start_key) -> list:
result = self.substrate.query_map(
module=self.module,
storage_function=self.storage_function,
params=self.params,
page_size=self.page_size,
block_hash=self.block_hash,
start_key=start_key,
max_results=self.max_results,
ignore_decoding_errors=self.ignore_decoding_errors,
)
if len(result.records) < self.page_size:
self.loading_complete = True
# Update last key from new result set to use as offset for next page
self.last_key = result.last_key
return result.records
def __iter__(self):
return self
def get_next_record(self):
try:
# Try to get the next record from the buffer
record = next(self._buffer)
except StopIteration:
# If no more records in the buffer
return False, None
else:
return True, record
def __next__(self):
successfully_retrieved, record = self.get_next_record()
if successfully_retrieved:
return record
# If loading is already completed
if self.loading_complete:
raise StopIteration
next_page = self.retrieve_next_page(self.last_key)
# If we cannot retrieve the next page
if not next_page:
self.loading_complete = True
raise StopIteration
# Update the buffer with the newly fetched records
self._buffer = iter(next_page)
return next(self._buffer)
def __getitem__(self, item):
return self.records[item]
class SubstrateInterface(SubstrateMixin):
def __init__(
self,
url: str,
use_remote_preset: bool = False,
auto_discover: bool = True,
ss58_format: Optional[int] = None,
type_registry: Optional[dict] = None,
type_registry_preset: Optional[str] = None,
chain_name: str = "",
max_retries: int = 5,
retry_timeout: float = 60.0,
_mock: bool = False,
):
"""
The sync compatible version of the subtensor interface commands we use in bittensor. Use this instance only
if you are not running within an event loop, otherwise use AsyncSubstrateInterface
Args:
url: the URI of the chain to connect to
use_remote_preset: whether to pull the preset from GitHub
auto_discover: whether to automatically pull the presets based on the chain name and type registry
ss58_format: the specific SS58 format to use
type_registry: a dict of custom types
type_registry_preset: preset
chain_name: the name of the chain (the result of the rpc request for "system_chain")
max_retries: number of times to retry RPC requests before giving up
retry_timeout: how to long wait since the last ping to retry the RPC request
_mock: whether to use mock version of the subtensor interface
"""
self.max_retries = max_retries
self.retry_timeout = retry_timeout
self.chain_endpoint = url
self.url = url
self._chain = chain_name
self.config = {
"use_remote_preset": use_remote_preset,
"auto_discover": auto_discover,
"rpc_methods": None,
"strict_scale_decode": True,
}
self.initialized = False
self._forgettable_task = None
self.ss58_format = ss58_format
self.type_registry = type_registry
self.type_registry_preset = type_registry_preset
self.runtime_cache = RuntimeCache()
self.runtime_config = RuntimeConfigurationObject(
ss58_format=self.ss58_format, implements_scale_info=True
)
self.metadata_version_hex = "0x0f000000" # v15
self.reload_type_registry()
self.ws = self.connect(init=True)
self.registry_type_map = {}
self.type_id_to_name = {}
if not _mock:
self.initialize()
def __enter__(self):
self.initialize()
return self
def __del__(self):
self.ws.close()
print("DELETING SUBSTATE")
# self.ws.protocol.fail(code=1006) # ABNORMAL_CLOSURE
def initialize(self):
"""
Initialize the connection to the chain.
"""
if not self.initialized:
if not self._chain:
chain = self.rpc_request("system_chain", [])
self._chain = chain.get("result")
self.init_runtime()
self.initialized = True
def __exit__(self, exc_type, exc_val, exc_tb):
self.ws.close()
@property
def properties(self):
if self._properties is None:
self._properties = self.rpc_request("system_properties", []).get("result")
return self._properties
@property
def version(self):
if self._version is None:
self._version = self.rpc_request("system_version", []).get("result")
return self._version
@property
def token_decimals(self):
if self._token_decimals is None:
self._token_decimals = self.properties.get("tokenDecimals")
return self._token_decimals
@property
def token_symbol(self):
if self._token_symbol is None:
if self.properties:
self._token_symbol = self.properties.get("tokenSymbol")
else:
self._token_symbol = "UNIT"
return self._token_symbol
@property
def name(self):
if self._name is None:
self._name = self.rpc_request("system_name", []).get("result")
return self._name
def connect(self, init=False):
if init is True:
return connect(self.chain_endpoint, max_size=self.ws_max_size)
else:
if not self.ws.close_code:
return self.ws
else:
self.ws = connect(self.chain_endpoint, max_size=self.ws_max_size)
return self.ws
def get_storage_item(
self, module: str, storage_function: str, block_hash: str = None
):
self.init_runtime(block_hash=block_hash)
metadata_pallet = self.runtime.metadata.get_metadata_pallet(module)
storage_item = metadata_pallet.get_storage_function(storage_function)
return storage_item
def _get_current_block_hash(
self, block_hash: Optional[str], reuse: bool
) -> Optional[str]:
if block_hash:
self.last_block_hash = block_hash
return block_hash
elif reuse:
if self.last_block_hash:
return self.last_block_hash
return block_hash
def _load_registry_at_block(self, block_hash: Optional[str]) -> MetadataV15:
# Should be called for any block that fails decoding.
# Possibly the metadata was different.
metadata_rpc_result = self.rpc_request(
"state_call",
["Metadata_metadata_at_version", self.metadata_version_hex],
block_hash=block_hash,
)
metadata_option_hex_str = metadata_rpc_result["result"]
metadata_option_bytes = bytes.fromhex(metadata_option_hex_str[2:])
metadata = MetadataV15.decode_from_metadata_option(metadata_option_bytes)
registry = PortableRegistry.from_metadata_v15(metadata)
self._load_registry_type_map(registry)
return metadata, registry
def decode_scale(
self,
type_string: str,
scale_bytes: bytes,
return_scale_obj=False,
) -> Union[ScaleObj, Any]:
"""
Helper function to decode arbitrary SCALE-bytes (e.g. 0x02000000) according to given RUST type_string
(e.g. BlockNumber). The relevant versioning information of the type (if defined) will be applied if block_hash
is set
Args:
type_string: the type string of the SCALE object for decoding
scale_bytes: the bytes representation of the SCALE object to decode
return_scale_obj: Whether to return the decoded value wrapped in a SCALE-object-like wrapper, or raw.
Returns:
Decoded object
"""
if type_string == "scale_info::0": # Is an AccountId
# Decode AccountId bytes to SS58 address
return ss58_encode(scale_bytes, SS58_FORMAT)
else:
obj = decode_by_type_string(type_string, self.runtime.registry, scale_bytes)
if return_scale_obj:
return ScaleObj(obj)
else:
return obj
def load_runtime(self, runtime):
self.runtime = runtime
# Update type registry
self.reload_type_registry(use_remote_preset=False, auto_discover=True)
self.runtime_config.set_active_spec_version_id(runtime.runtime_version)
if self.implements_scaleinfo:
logger.debug("Add PortableRegistry from metadata to type registry")
self.runtime_config.add_portable_registry(runtime.metadata)
# Set runtime compatibility flags
try:
_ = self.runtime_config.create_scale_object("sp_weights::weight_v2::Weight")
self.config["is_weight_v2"] = True
self.runtime_config.update_type_registry_types(
{"Weight": "sp_weights::weight_v2::Weight"}
)
except NotImplementedError:
self.config["is_weight_v2"] = False
self.runtime_config.update_type_registry_types({"Weight": "WeightV1"})
def init_runtime(
self, block_hash: Optional[str] = None, block_id: Optional[int] = None
) -> Runtime:
"""
This method is used by all other methods that deals with metadata and types defined in the type registry.
It optionally retrieves the block_hash when block_id is given and sets the applicable metadata for that
block_hash. Also, it applies all the versioned types at the time of the block_hash.
Because parsing of metadata and type registry is quite heavy, the result will be cached per runtime id.
In the future there could be support for caching backends like Redis to make this cache more persistent.
Args:
block_hash: optional block hash, should not be specified if block_id is
block_id: optional block id, should not be specified if block_hash is
Returns:
Runtime object
"""
if block_id and block_hash:
raise ValueError("Cannot provide block_hash and block_id at the same time")
if block_id:
block_hash = self.get_block_hash(block_id)
if not block_hash:
block_hash = self.get_chain_head()
runtime_version = self.get_block_runtime_version_for(block_hash)
if runtime_version is None:
raise SubstrateRequestException(
f"No runtime information for block '{block_hash}'"
)
if self.runtime and runtime_version == self.runtime.runtime_version:
return
runtime = self.runtime_cache.retrieve(runtime_version=runtime_version)
if not runtime:
self.last_block_hash = block_hash
runtime_block_hash = self.get_parent_block_hash(block_hash)
runtime_info = self.get_block_runtime_info(runtime_block_hash)
metadata = self.get_block_metadata(
block_hash=runtime_block_hash, decode=True
)
if metadata is None:
# does this ever happen?
raise SubstrateRequestException(
f"No metadata for block '{runtime_block_hash}'"
)
logger.debug(
"Retrieved metadata for {} from Substrate node".format(runtime_version)
)
metadata_v15, registry = self._load_registry_at_block(
block_hash=runtime_block_hash
)
logger.debug(
"Retrieved metadata v15 for {} from Substrate node".format(
runtime_version
)
)
runtime = Runtime(
chain=self.chain,
runtime_config=self.runtime_config,
metadata=metadata,
type_registry=self.type_registry,
metadata_v15=metadata_v15,
runtime_info=runtime_info,
registry=registry,
)
self.runtime_cache.add_item(
runtime_version=runtime_version, runtime=runtime
)
self.load_runtime(runtime)
if self.ss58_format is None:
# Check and apply runtime constants
ss58_prefix_constant = self.get_constant(
"System", "SS58Prefix", block_hash=block_hash
)
if ss58_prefix_constant:
self.ss58_format = ss58_prefix_constant
def create_storage_key(
self,
pallet: str,
storage_function: str,
params: Optional[list] = None,
block_hash: str = None,
) -> StorageKey:
"""
Create a `StorageKey` instance providing storage function details. See `subscribe_storage()`.
Args:
pallet: name of pallet
storage_function: name of storage function
params: list of parameters in case of a Mapped storage function
block_hash: the hash of the blockchain block whose runtime to use
Returns:
StorageKey
"""
self.init_runtime(block_hash=block_hash)
return StorageKey.create_from_storage_function(
pallet,
storage_function,
params,
runtime_config=self.runtime_config,
metadata=self.runtime.metadata,
)
def get_metadata_storage_functions(self, block_hash=None) -> list:
"""
Retrieves a list of all storage functions in metadata active at given block_hash (or chaintip if block_hash is
omitted)
Args:
block_hash: hash of the blockchain block whose runtime to use
Returns:
list of storage functions
"""
self.init_runtime(block_hash=block_hash)
storage_list = []
for module_idx, module in enumerate(self.metadata.pallets):
if module.storage:
for storage in module.storage:
storage_list.append(
self.serialize_storage_item(
storage_item=storage,
module=module,
spec_version_id=self.runtime.runtime_version,
)
)
return storage_list
def get_metadata_storage_function(self, module_name, storage_name, block_hash=None):
"""
Retrieves the details of a storage function for given module name, call function name and block_hash
Args:
module_name
storage_name
block_hash
Returns:
Metadata storage function
"""
self.init_runtime(block_hash=block_hash)
pallet = self.metadata.get_metadata_pallet(module_name)
if pallet:
return pallet.get_storage_function(storage_name)
def get_metadata_errors(self, block_hash=None) -> list[dict[str, Optional[str]]]:
"""
Retrieves a list of all errors in metadata active at given block_hash (or chaintip if block_hash is omitted)
Args:
block_hash: hash of the blockchain block whose metadata to use
Returns:
list of errors in the metadata
"""
self.init_runtime(block_hash=block_hash)
error_list = []
for module_idx, module in enumerate(self.runtime.metadata.pallets):
if module.errors:
for error in module.errors:
error_list.append(
self.serialize_module_error(
module=module,
error=error,
spec_version=self.runtime.runtime_version,
)
)
return error_list
def get_metadata_error(self, module_name, error_name, block_hash=None):
"""
Retrieves the details of an error for given module name, call function name and block_hash
Args:
module_name: module name for the error lookup
error_name: error name for the error lookup
block_hash: hash of the blockchain block whose metadata to use
Returns:
error
"""
self.init_runtime(block_hash=block_hash)
for module_idx, module in enumerate(self.runtime.metadata.pallets):
if module.name == module_name and module.errors:
for error in module.errors:
if error_name == error.name:
return error
def get_metadata_runtime_call_functions(
self, block_hash: str = None
) -> list[GenericRuntimeCallDefinition]:
"""
Get a list of available runtime API calls
Returns:
list of runtime call functions
"""
self.init_runtime(block_hash=block_hash)
call_functions = []
for api, methods in self.runtime_config.type_registry["runtime_api"].items():
for method in methods["methods"].keys():
call_functions.append(
self.get_metadata_runtime_call_function(api, method)
)
return call_functions
def get_metadata_runtime_call_function(
self, api: str, method: str, block_hash: str = None
) -> GenericRuntimeCallDefinition:
"""
Get details of a runtime API call
Args:
api: Name of the runtime API e.g. 'TransactionPaymentApi'
method: Name of the method e.g. 'query_fee_details'
Returns:
runtime call function
"""
self.init_runtime(block_hash=block_hash)
try:
runtime_call_def = self.runtime_config.type_registry["runtime_api"][api][
"methods"
][method]
runtime_call_def["api"] = api
runtime_call_def["method"] = method
runtime_api_types = self.runtime_config.type_registry["runtime_api"][
api
].get("types", {})
except KeyError:
raise ValueError(f"Runtime API Call '{api}.{method}' not found in registry")
# Add runtime API types to registry
self.runtime_config.update_type_registry_types(runtime_api_types)
runtime_call_def_obj = self.create_scale_object("RuntimeCallDefinition")
runtime_call_def_obj.encode(runtime_call_def)
return runtime_call_def_obj
def _get_block_handler(
self,
block_hash: str,
ignore_decoding_errors: bool = False,
include_author: bool = False,
header_only: bool = False,
finalized_only: bool = False,
subscription_handler: Optional[Callable] = None,
):
try:
self.init_runtime(block_hash=block_hash)
except BlockNotFound:
return None
def decode_block(block_data, block_data_hash=None) -> dict[str, Any]:
if block_data:
if block_data_hash:
block_data["header"]["hash"] = block_data_hash
if isinstance(block_data["header"]["number"], str):
# Convert block number from hex (backwards compatibility)
block_data["header"]["number"] = int(
block_data["header"]["number"], 16
)
extrinsic_cls = self.runtime_config.get_decoder_class("Extrinsic")
if "extrinsics" in block_data:
for idx, extrinsic_data in enumerate(block_data["extrinsics"]):
try:
extrinsic_decoder = extrinsic_cls(
data=ScaleBytes(extrinsic_data),
metadata=self.runtime.metadata,
runtime_config=self.runtime_config,
)
extrinsic_decoder.decode(check_remaining=True)
block_data["extrinsics"][idx] = extrinsic_decoder
except Exception:
if not ignore_decoding_errors:
raise
block_data["extrinsics"][idx] = None
for idx, log_data in enumerate(block_data["header"]["digest"]["logs"]):
if isinstance(log_data, str):
# Convert digest log from hex (backwards compatibility)
try:
log_digest_cls = self.runtime_config.get_decoder_class(
"sp_runtime::generic::digest::DigestItem"
)
if log_digest_cls is None:
raise NotImplementedError(
"No decoding class found for 'DigestItem'"
)
log_digest = log_digest_cls(data=ScaleBytes(log_data))
log_digest.decode(
check_remaining=self.config.get("strict_scale_decode")