forked from latent-to/bittensor
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathasync_subtensor.py
More file actions
9894 lines (8686 loc) · 445 KB
/
async_subtensor.py
File metadata and controls
9894 lines (8686 loc) · 445 KB
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 asyncio
import copy
import ssl
from datetime import datetime, timezone
from typing import TYPE_CHECKING, Any, Iterable, Literal, Optional, Union, cast
import asyncstdlib as a
import scalecodec
from async_substrate_interface import AsyncSubstrateInterface
from async_substrate_interface.substrate_addons import RetryAsyncSubstrate
from async_substrate_interface.types import ScaleObj
from async_substrate_interface.utils.storage import StorageKey
from bittensor_drand import get_encrypted_commitment
from bittensor_wallet.utils import SS58_FORMAT
from scalecodec import GenericCall
from bittensor.core.chain_data import (
ColdkeySwapAnnouncementInfo,
ColdkeySwapConstants,
ColdkeySwapDisputeInfo,
CrowdloanConstants,
CrowdloanInfo,
DelegateInfo,
DynamicInfo,
MetagraphInfo,
NeuronInfo,
NeuronInfoLite,
ProxyAnnouncementInfo,
ProxyConstants,
ProxyInfo,
ProxyType,
RootClaimType,
SelectiveMetagraphIndex,
SimSwapResult,
StakeInfo,
SubnetHyperparameters,
SubnetIdentity,
SubnetInfo,
WeightCommitInfo,
decode_account_id,
)
from bittensor.core.chain_data.chain_identity import ChainIdentity
from bittensor.core.chain_data.delegate_info import DelegatedInfo
from bittensor.core.chain_data.utils import (
decode_block,
decode_metadata,
decode_revealed_commitment,
decode_revealed_commitment_with_hotkey,
)
from bittensor.core.config import Config
from bittensor.core.errors import ChainError, SubstrateRequestException
from bittensor.core.extrinsics.asyncex.children import (
root_set_pending_childkey_cooldown_extrinsic,
set_children_extrinsic,
)
from bittensor.core.extrinsics.asyncex.coldkey_swap import (
announce_coldkey_swap_extrinsic,
clear_coldkey_swap_announcement_extrinsic,
dispute_coldkey_swap_extrinsic,
swap_coldkey_announced_extrinsic,
)
from bittensor.core.extrinsics.asyncex.crowdloan import (
contribute_crowdloan_extrinsic,
create_crowdloan_extrinsic,
dissolve_crowdloan_extrinsic,
finalize_crowdloan_extrinsic,
refund_crowdloan_extrinsic,
update_cap_crowdloan_extrinsic,
update_end_crowdloan_extrinsic,
update_min_contribution_crowdloan_extrinsic,
withdraw_crowdloan_extrinsic,
)
from bittensor.core.extrinsics.asyncex.liquidity import (
add_liquidity_extrinsic,
modify_liquidity_extrinsic,
remove_liquidity_extrinsic,
toggle_user_liquidity_extrinsic,
)
from bittensor.core.extrinsics.asyncex.mev_shield import submit_encrypted_extrinsic
from bittensor.core.extrinsics.asyncex.move_stake import (
move_stake_extrinsic,
swap_stake_extrinsic,
transfer_stake_extrinsic,
)
from bittensor.core.extrinsics.asyncex.proxy import (
add_proxy_extrinsic,
announce_extrinsic,
create_pure_proxy_extrinsic,
kill_pure_proxy_extrinsic,
poke_deposit_extrinsic,
proxy_announced_extrinsic,
proxy_extrinsic,
reject_announcement_extrinsic,
remove_announcement_extrinsic,
remove_proxies_extrinsic,
remove_proxy_extrinsic,
)
from bittensor.core.extrinsics.asyncex.registration import (
burned_register_extrinsic,
register_extrinsic,
register_subnet_extrinsic,
set_subnet_identity_extrinsic,
)
from bittensor.core.extrinsics.asyncex.root import (
claim_root_extrinsic,
root_register_extrinsic,
set_root_claim_type_extrinsic,
)
from bittensor.core.extrinsics.asyncex.serving import (
publish_metadata_extrinsic,
serve_axon_extrinsic,
)
from bittensor.core.extrinsics.asyncex.staking import (
add_stake_burn_extrinsic,
add_stake_extrinsic,
add_stake_multiple_extrinsic,
set_auto_stake_extrinsic,
)
from bittensor.core.extrinsics.asyncex.start_call import start_call_extrinsic
from bittensor.core.extrinsics.asyncex.take import set_take_extrinsic
from bittensor.core.extrinsics.asyncex.transfer import transfer_extrinsic
from bittensor.core.extrinsics.asyncex.unstaking import (
unstake_all_extrinsic,
unstake_extrinsic,
unstake_multiple_extrinsic,
)
from bittensor.core.extrinsics.asyncex.weights import (
commit_timelocked_weights_extrinsic,
commit_weights_extrinsic,
reveal_weights_extrinsic,
set_weights_extrinsic,
)
from bittensor.core.extrinsics.utils import get_transfer_fn_params
from bittensor.core.metagraph import AsyncMetagraph
from bittensor.core.settings import (
DEFAULT_MEV_PROTECTION,
DEFAULT_PERIOD,
MLKEM768_PUBLIC_KEY_SIZE,
TAO_APP_BLOCK_EXPLORER,
TYPE_REGISTRY,
version_as_int,
)
from bittensor.core.types import (
BlockInfo,
ExtrinsicResponse,
Salt,
SubtensorMixin,
UIDs,
Weights,
)
from bittensor.utils import (
Certificate,
decode_hex_identity_dict,
format_error_message,
get_caller_name,
get_mechid_storage_index,
is_valid_ss58_address,
u16_normalized_float,
u64_normalized_float,
validate_max_attempts,
)
from bittensor.utils.balance import (
Balance,
FixedPoint,
check_balance_amount,
fixed_to_float,
)
from bittensor.utils.btlogging import logging
from bittensor.utils.liquidity import (
LiquidityPosition,
calculate_fees,
get_fees,
price_to_tick,
tick_to_price,
)
if TYPE_CHECKING:
from async_substrate_interface import AsyncQueryMapResult
from bittensor_wallet import Keypair, Wallet
from bittensor.core.axon import Axon
class AsyncSubtensor(SubtensorMixin):
"""Asynchronous interface for interacting with the Bittensor blockchain.
This class provides a thin layer over the Substrate Interface offering async functionality for Bittensor. This
includes frequently-used calls for querying blockchain data, managing stakes and liquidity positions, registering
neurons, submitting weights, and many other functions for participating in Bittensor.
Notes:
Key Bittensor concepts used throughout this class:
- **Coldkey**: The key pair corresponding to a user's overall wallet. Used to transfer, stake, manage subnets.
- **Hotkey**: A key pair (each wallet may have zero, one, or more) used for neuron operations (mining and
validation).
- **Netuid**: Unique identifier for a subnet (0 is the Root Subnet)
- **UID**: Unique identifier for a neuron registered to a hotkey on a specific subnet.
- **Metagraph**: Data structure containing the complete state of a subnet at a block.
- **TAO**: The base network token; subnet 0 stake is in TAO
- **Alpha**: Subnet-specific token representing some quantity of TAO staked into a subnet.
- **Rao**: Smallest unit of TAO (1 TAO = 1e9 Rao)
- Bittensor Glossary <https://docs.learnbittensor.org/glossary>
- Wallets, Coldkeys and Hotkeys in Bittensor <https://docs.learnbittensor.org/keys/wallets>
"""
def __init__(
self,
network: Optional[str] = None,
config: Optional["Config"] = None,
log_verbose: bool = False,
fallback_endpoints: Optional[list[str]] = None,
retry_forever: bool = False,
archive_endpoints: Optional[list[str]] = None,
websocket_shutdown_timer: Optional[float] = 5.0,
mock: bool = False,
):
"""Initializes an AsyncSubtensor instance for blockchain interaction.
Parameters:
network: The network name to connect to (e.g., `finney` for Bittensor mainnet, `test`, for
Bittensor test network, `local` for a locally deployed blockchain). If `None`, uses the
default network from config.
config: Configuration object for the AsyncSubtensor instance. If `None`, uses the default configuration.
log_verbose: Enables or disables verbose logging.
fallback_endpoints: List of fallback WebSocket endpoints to use if the primary network endpoint is
unavailable. These are tried in order when the default endpoint fails.
retry_forever: Whether to retry connection attempts indefinitely on connection errors.
mock: Whether this is a mock instance. FOR TESTING ONLY.
archive_endpoints: List of archive node endpoints for queries requiring historical block data beyond the
retention period of lite nodes. These are only used when requesting blocks that the current node is
unable to serve.
websocket_shutdown_timer: Amount of time (in seconds) to wait after the last response from the chain before
automatically closing the WebSocket connection. Pass `None` to disable automatic shutdown entirely.
Returns:
None
"""
if config is None:
config = AsyncSubtensor.config()
self._config = copy.deepcopy(config)
self.chain_endpoint, self.network = AsyncSubtensor.setup_config(
network, self._config
)
self.log_verbose = log_verbose
self._check_and_log_network_settings()
logging.debug(
f"Connecting to network: [blue]{self.network}[/blue], "
f"chain_endpoint: [blue]{self.chain_endpoint}[/blue]..."
)
self.substrate = self._get_substrate(
fallback_endpoints=fallback_endpoints,
retry_forever=retry_forever,
_mock=mock,
archive_endpoints=archive_endpoints,
ws_shutdown_timer=websocket_shutdown_timer,
)
if self.log_verbose:
logging.set_trace()
logging.info(
f"Connected to {self.network} network and {self.chain_endpoint}."
)
async def close(self):
"""Closes the connection to the blockchain.
Use this to explicitly clean up resources and close the network connection instead of waiting for garbage
collection.
Returns:
None
Example:
sub = bt.AsyncSubtensor(network="finney")
# Initialize the connection
await subtensor.initialize()
# calls to subtensor
await subtensor.close()
"""
if self.substrate:
await self.substrate.close()
async def initialize(self):
"""Establishes connection to the blockchain.
This method establishes the connection to the Bittensor blockchain and should be called after creating an
AsyncSubtensor instance before making any queries.
When using the `async with` context manager, this method is called automatically and does not need to be
invoked explicitly.
Returns:
AsyncSubtensor: The initialized instance (self) for method chaining.
Example:
subtensor = AsyncSubtensor(network="finney")
# Initialize the connection
await subtensor.initialize()
# calls to subtensor
await subtensor.close()
"""
logging.info(
f"[magenta]Connecting to Substrate:[/magenta] [blue]{self}[/blue][magenta]...[/magenta]"
)
try:
await self.substrate.initialize()
return self
except TimeoutError:
logging.error(
f"[red]Error[/red]: Timeout occurred connecting to substrate."
f" Verify your chain and network settings: {self}"
)
raise ConnectionError
except (ConnectionRefusedError, ssl.SSLError) as error:
logging.error(
f"[red]Error[/red]: Connection refused when connecting to substrate. "
f"Verify your chain and network settings: {self}. Error: {error}"
)
raise ConnectionError
async def __aenter__(self):
return await self.initialize()
async def __aexit__(self, exc_type, exc_val, exc_tb):
await self.substrate.close()
# Helpers ==========================================================================================================
async def _decode_crowdloan_entry(
self,
crowdloan_id: int,
data: dict,
block_hash: Optional[str] = None,
) -> "CrowdloanInfo":
"""
Internal helper to parse and decode a single Crowdloan record.
Automatically decodes the embedded `call` field if present (Inline SCALE format).
"""
call_data = data.get("call")
if call_data and "Inline" in call_data:
try:
inline_bytes = bytes(call_data["Inline"][0][0])
scale_object = await self.substrate.create_scale_object(
type_string="Call",
data=scalecodec.ScaleBytes(inline_bytes),
block_hash=block_hash,
)
decoded_call = scale_object.decode()
data["call"] = decoded_call
except Exception as e:
data["call"] = {"decode_error": str(e), "raw": call_data}
return CrowdloanInfo.from_dict(crowdloan_id, data)
@a.lru_cache(maxsize=128)
async def _get_block_hash(self, block_id: int):
return await self.substrate.get_block_hash(block_id)
def _get_substrate(
self,
fallback_endpoints: Optional[list[str]] = None,
retry_forever: bool = False,
_mock: bool = False,
archive_endpoints: Optional[list[str]] = None,
ws_shutdown_timer: float = 5.0,
) -> Union[AsyncSubstrateInterface, RetryAsyncSubstrate]:
"""Creates the Substrate instance based on provided arguments.
This internal method creates either a standard AsyncSubstrateInterface or a RetryAsyncSubstrate depending on
whether fallback/archive endpoints or infinite retry is requested.
When `fallback_endpoints`, `archive_endpoints`, or `retry_forever` are provided, a RetryAsyncSubstrate
is created with automatic failover and exponential backoff retry logic. Otherwise, a standard
AsyncSubstrateInterface is used.
Parameters:
fallback_endpoints: List of fallback WebSocket endpoints to use if the primary endpoint is unavailable.
retry_forever: Whether to retry connection attempts indefinitely on connection errors.
_mock: Whether this is a mock instance. Used primarily for testing purposes.
archive_endpoints: List of archive node endpoints for historical block queries. Archive nodes maintain full
block history, while lite nodes only keep recent blocks. Use these when querying blocks older than the
lite node's retention period (typically a few thousand blocks).
ws_shutdown_timer: Amount of time (in seconds) to wait after the last response from the chain before
automatically closing the WebSocket connection.
Returns:
Either AsyncSubstrateInterface (simple connection) or RetryAsyncSubstrate (with failover and retry logic).
"""
if fallback_endpoints or retry_forever or archive_endpoints:
return RetryAsyncSubstrate(
url=self.chain_endpoint,
fallback_chains=fallback_endpoints,
ss58_format=SS58_FORMAT,
type_registry=TYPE_REGISTRY,
retry_forever=retry_forever,
use_remote_preset=True,
chain_name="Bittensor",
_mock=_mock,
archive_nodes=archive_endpoints,
ws_shutdown_timer=ws_shutdown_timer,
)
return AsyncSubstrateInterface(
url=self.chain_endpoint,
ss58_format=SS58_FORMAT,
type_registry=TYPE_REGISTRY,
use_remote_preset=True,
chain_name="Bittensor",
_mock=_mock,
ws_shutdown_timer=ws_shutdown_timer,
)
@property
async def block(self):
"""Provides an asynchronous getter to retrieve the current block number.
Returns:
The current blockchain block number.
"""
return await self.get_current_block()
async def determine_block_hash(
self,
block: Optional[int] = None,
block_hash: Optional[str] = None,
reuse_block: bool = False,
) -> Optional[str]:
"""Determine the block hash for the block specified with the provided parameters.
Ensures that only one of the block specification parameters is used and returns the appropriate block hash
for blockchain queries.
Parameter precedence (in order):
1. If `reuse_block=True` and `block` or `block_hash` is set → raises ValueError
2. If both `block` and `block_hash` are set → validates they match, raises ValueError if not
3. If only `block_hash` is set → returns it directly
4. If only `block` is set → fetches and returns its hash
5. If none are set → returns `None`
Parameters:
block: The block number to get the hash for. If specifying along with `block_hash`, the hash of `block`
will be checked and compared with the supplied block hash, raising a ValueError if the two do not match.
block_hash: The hash of the blockchain block (hex string prefixed with `0x`). If specifying along with
`block`, the hash of `block` will be checked and compared with the supplied block hash, raising a
ValueError if the two do not match.
reuse_block: Whether to reuse the last-used block hash. Do not set if using `block` or `block_hash`.
Returns:
The block hash (hex string with `0x` prefix) if one can be determined, `None` otherwise.
Notes:
- <https://docs.learnbittensor.org/glossary#block>
"""
if reuse_block and any([block, block_hash]):
raise ValueError("Cannot specify both reuse_block and block_hash/block")
if block and block_hash:
retrieved_block_hash = await self.get_block_hash(block)
if retrieved_block_hash != block_hash:
raise ValueError(
"You have supplied a `block_hash` and a `block`, but the block does not map to the same hash as "
f"the one you supplied. You supplied `block_hash={block_hash}` for `block={block}`, but this block"
f"maps to the block hash {retrieved_block_hash}."
)
else:
return retrieved_block_hash
# Return the appropriate value.
if block_hash:
return block_hash
if block is not None:
return await self.get_block_hash(block)
return None
async def _runtime_method_exists(
self, api: str, method: str, block_hash: str
) -> bool:
"""
Check if a runtime call method exists at the given block.
The complicated logic here comes from the fact that there are two ways in which runtime calls
are stored: the new and primary method is through the Metadata V15, but the V14 is a good backup (implemented
around mid 2024)
Returns:
True if the runtime call method exists, False otherwise.
"""
runtime = await self.substrate.init_runtime(block_hash=block_hash)
if runtime.metadata_v15 is not None:
metadata_v15_value = runtime.metadata_v15.value()
apis = {entry["name"]: entry for entry in metadata_v15_value["apis"]}
try:
api_entry = apis[api]
methods = {entry["name"]: entry for entry in api_entry["methods"]}
_ = methods[method]
return True
except KeyError:
return False
else:
try:
await self.substrate.get_metadata_runtime_call_function(
api=api,
method=method,
block_hash=block_hash,
)
return True
except ValueError:
return False
async def _query_with_fallback(
self,
*args: tuple[str, str, Optional[list[Any]]],
block_hash: Optional[str] = None,
default_value: Any = ValueError,
):
"""
Queries the subtensor node with a given set of args, falling back to the next group if the method
does not exist at the given block. This method exists to support backwards compatibility for blocks.
Parameters:
*args: Tuples containing (module, storage_function, params) in the order they should be attempted.
block_hash: The hash of the block being queried. If not provided, the chain tip will be used.
default_value: The default value to return if none of the methods exist at the given block.
Returns:
The value returned by the subtensor node, or the default value if none of the methods exist at the given
block.
Raises:
ValueError: If no default value is provided, and none of the methods exist at the given block, a
ValueError will be raised.
"""
if block_hash is None:
block_hash = await self.substrate.get_chain_head()
for module, storage_function, params in args:
if await self.substrate.get_metadata_storage_function(
module_name=module,
storage_name=storage_function,
block_hash=block_hash,
):
return await self.substrate.query(
module=module,
storage_function=storage_function,
block_hash=block_hash,
params=params,
)
if not isinstance(default_value, ValueError):
return default_value
else:
raise default_value
async def _runtime_call_with_fallback(
self,
*args: tuple[str, str, Optional[list[Any]] | dict[str, Any]],
block_hash: Optional[str] = None,
default_value: Any = ValueError,
):
"""
Makes a runtime call to the subtensor node with a given set of args, falling back to the next group if the
api.method does not exist at the given block. This method exists to support backwards compatibility for blocks.
Parameters:
*args: Tuples containing (api, method, params) in the order they should be attempted.
block_hash: The hash of the block being queried. If not provided, the chain tip will be used.
default_value: The default value to return if none of the methods exist at the given block.
Raises:
ValueError: If no default value is provided, and none of the methods exist at the given block, a
ValueError will be raised.
"""
if block_hash is None:
block_hash = await self.substrate.get_chain_head()
for api, method, params in args:
if await self._runtime_method_exists(
api=api, method=method, block_hash=block_hash
):
return await self.substrate.runtime_call(
api=api,
method=method,
block_hash=block_hash,
params=params,
)
if not isinstance(default_value, ValueError):
return default_value
else:
raise default_value
async def get_hyperparameter(
self,
param_name: str,
netuid: int,
block: Optional[int] = None,
block_hash: Optional[str] = None,
reuse_block: bool = False,
) -> Optional[Any]:
"""Retrieves a specified hyperparameter for a specific subnet.
This method queries the blockchain for subnet-specific hyperparameters such as difficulty, tempo, immunity
period, and other network configuration values. Return types and units vary by parameter.
Parameters:
param_name: The name of the hyperparameter storage function to retrieve.
netuid: The unique identifier of the subnet.
block: The block number to query. Do not specify if using `block_hash` or `reuse_block`.
block_hash: The block hash at which to check the parameter. Do not set if using `block` or
`reuse_block`.
reuse_block: Whether to reuse the last-used block hash. Do not set if using `block_hash` or `block`.
Returns:
The value of the specified hyperparameter if the subnet exists, `None` otherwise. Return type varies
by parameter (int, float, bool, or Balance).
Notes:
- <https://docs.learnbittensor.org/subnets/subnet-hyperparameters>
"""
block_hash = await self.determine_block_hash(block, block_hash, reuse_block)
if not await self.subnet_exists(
netuid, block_hash=block_hash, reuse_block=reuse_block
):
logging.error(f"subnet {netuid} does not exist")
return None
result = await self.substrate.query(
module="SubtensorModule",
storage_function=param_name,
params=[netuid],
block_hash=block_hash,
reuse_block_hash=reuse_block,
)
return getattr(result, "value", result)
async def sim_swap(
self,
origin_netuid: int,
destination_netuid: int,
amount: "Balance",
block_hash: Optional[str] = None,
) -> SimSwapResult:
"""Simulates a swap/stake operation and calculates the fees and resulting amounts.
This method queries the SimSwap Runtime API to calculate the swap fees (in Alpha or TAO) and the quantities
of Alpha or TAO tokens expected as output from the transaction. This simulation does NOT include the
blockchain extrinsic transaction fee (the fee to submit the transaction itself).
When moving stake between subnets, the operation may involve swapping Alpha (subnet-specific stake token) to
TAO (the base network token), then TAO to Alpha on the destination subnet. For subnet 0 (root network), all
stake is in TAO.
Parameters:
origin_netuid: Netuid of the source subnet (0 if add stake).
destination_netuid: Netuid of the destination subnet.
amount: Amount to swap/stake as a Balance object. Use `Balance.from_tao(...)` or
`Balance.from_rao(...)` to create the amount.
block_hash: The hash of the blockchain block for the query. If `None`, uses the current chain head.
Returns:
SimSwapResult: Object containing `alpha_fee`, `tao_fee`, `alpha_amount`, and `tao_amount` fields
representing the swap fees and output amounts.
Example:
# Simulate staking 100 TAO stake to subnet 1
result = await subtensor.sim_swap(
origin_netuid=0,
destination_netuid=1,
amount=Balance.from_tao(100)
)
print(f"Fee: {result.tao_fee.tao} TAO, Output: {result.alpha_amount} Alpha")
Notes:
- **Alpha**: Subnet-specific stake token (dynamic TAO)
- **TAO**: Base network token; subnet 0 uses TAO directly
- The returned fees do NOT include the extrinsic transaction fee
- Transaction Fees: <https://docs.learnbittensor.org/learn/fees>
- Glossary: <https://docs.learnbittensor.org/glossary>
"""
check_balance_amount(amount)
block_hash = block_hash or await self.substrate.get_chain_head()
if origin_netuid > 0 and destination_netuid > 0:
# for cross-subnet moves where neither origin nor destination is root
intermediate_result_, sn_price = await asyncio.gather(
self.query_runtime_api(
runtime_api="SwapRuntimeApi",
method="sim_swap_alpha_for_tao",
params={"netuid": origin_netuid, "alpha": amount.rao},
block_hash=block_hash,
),
self.get_subnet_price(origin_netuid, block_hash=block_hash),
)
intermediate_result = SimSwapResult.from_dict(
intermediate_result_, origin_netuid
)
result = SimSwapResult.from_dict(
await self.query_runtime_api(
runtime_api="SwapRuntimeApi",
method="sim_swap_tao_for_alpha",
params={
"netuid": destination_netuid,
"tao": intermediate_result.tao_amount.rao,
},
block_hash=block_hash,
),
origin_netuid,
)
secondary_fee = (result.tao_fee / sn_price.tao).set_unit(origin_netuid)
result.alpha_fee = result.alpha_fee + secondary_fee
return result
elif origin_netuid > 0:
# dynamic to tao
return SimSwapResult.from_dict(
await self.query_runtime_api(
runtime_api="SwapRuntimeApi",
method="sim_swap_alpha_for_tao",
params={"netuid": origin_netuid, "alpha": amount.rao},
block_hash=block_hash,
),
origin_netuid,
)
else:
# tao to dynamic or unstaked to staked tao (SN0)
return SimSwapResult.from_dict(
await self.query_runtime_api(
runtime_api="SwapRuntimeApi",
method="sim_swap_tao_for_alpha",
params={"netuid": destination_netuid, "tao": amount.rao},
block_hash=block_hash,
),
destination_netuid,
)
# Subtensor queries ===========================================================================================
async def query_constant(
self,
module_name: str,
constant_name: str,
block: Optional[int] = None,
block_hash: Optional[str] = None,
reuse_block: bool = False,
) -> Optional["ScaleObj"]:
"""Retrieves a constant from the specified module on the Bittensor blockchain.
Use this function for nonstandard queries to constants defined within the Bittensor blockchain, if these cannot
be accessed through other, standard getter methods.
Parameters:
module_name: The name of the module containing the constant (e.g., `Balances`, `SubtensorModule`).
constant_name: The name of the constant to retrieve (e.g., `ExistentialDeposit`).
block: The block number to query. Do not specify if using `block_hash` or `reuse_block`.
block_hash: The block hash at which to check the parameter. Do not set if using `block` or
`reuse_block`.
reuse_block: Whether to reuse the last-used block hash. Do not set if using `block_hash` or `block`.
Returns:
A SCALE-decoded object if found, `None` otherwise. Access the actual value using `.value` attribute.
Common types include int (for counts/blocks), Balance objects (for amounts in Rao), and booleans.
"""
block_hash = await self.determine_block_hash(block, block_hash, reuse_block)
return await self.substrate.get_constant(
module_name=module_name,
constant_name=constant_name,
block_hash=block_hash,
reuse_block_hash=reuse_block,
)
async def query_map(
self,
module: str,
name: str,
params: Optional[list] = None,
block: Optional[int] = None,
block_hash: Optional[str] = None,
reuse_block: bool = False,
) -> "AsyncQueryMapResult":
"""Queries map storage from any module on the Bittensor blockchain.
Use this function for nonstandard queries to map storage defined within the Bittensor blockchain, if these cannot
be accessed through other, standard getter methods.
Parameters:
module: The name of the module from which to query the map storage (e.g., "SubtensorModule", "System").
name: The specific storage function within the module to query (e.g., "Bonds", "Weights").
params: Parameters to be passed to the query.
block: The block number to query. Do not specify if using `block_hash` or `reuse_block`.
block_hash: The block hash at which to check the parameter. Do not set if using `block` or
`reuse_block`.
reuse_block: Whether to reuse the last-used block hash. Do not set if using `block_hash` or `block`.
Returns:
AsyncQueryMapResult: A data structure representing the map storage if found, None otherwise.
"""
block_hash = await self.determine_block_hash(block, block_hash, reuse_block)
result = await self.substrate.query_map(
module=module,
storage_function=name,
params=params,
block_hash=block_hash,
reuse_block_hash=reuse_block,
)
return result
async def query_map_subtensor(
self,
name: str,
params: Optional[list] = None,
block: Optional[int] = None,
block_hash: Optional[str] = None,
reuse_block: bool = False,
) -> "AsyncQueryMapResult":
"""Queries map storage from the Subtensor module on the Bittensor blockchain.
Use this function for nonstandard queries to map storage defined within the Bittensor blockchain, if these cannot
be accessed through other, standard getter methods.
Parameters:
name: The name of the map storage function to query.
params: A list of parameters to pass to the query function.
block: The block number to query. Do not specify if using `block_hash` or `reuse_block`.
block_hash: The block hash at which to check the parameter. Do not set if using `block` or
`reuse_block`.
reuse_block: Whether to reuse the last-used block hash. Do not set if using `block_hash` or `block`.
Returns:
An object containing the map-like data structure, or `None` if not found.
"""
block_hash = await self.determine_block_hash(block, block_hash, reuse_block)
return await self.substrate.query_map(
module="SubtensorModule",
storage_function=name,
params=params,
block_hash=block_hash,
reuse_block_hash=reuse_block,
)
async def query_module(
self,
module: str,
name: str,
params: Optional[list] = None,
block: Optional[int] = None,
block_hash: Optional[str] = None,
reuse_block: bool = False,
) -> Optional[Union["ScaleObj", Any]]:
"""Queries any module storage on the Bittensor blockchain with the specified parameters and block number.
This function is a generic query interface that allows for flexible and diverse data retrieval from various
blockchain modules. Use this function for nonstandard queries to storage defined within the Bittensor
blockchain, if these cannot be accessed through other, standard getter methods.
Parameters:
module: The name of the module from which to query data.
name: The name of the storage function within the module.
params: A list of parameters to pass to the query function.
block: The block number to query. Do not specify if using `block_hash` or `reuse_block`.
block_hash: The block hash at which to check the parameter. Do not set if using `block` or
`reuse_block`.
reuse_block: Whether to reuse the last-used block hash. Do not set if using `block_hash` or `block`.
Returns:
An object containing the requested data if found, `None` otherwise.
"""
block_hash = await self.determine_block_hash(block, block_hash, reuse_block)
return await self.substrate.query(
module=module,
storage_function=name,
params=params,
block_hash=block_hash,
reuse_block_hash=reuse_block,
)
async def query_runtime_api(
self,
runtime_api: str,
method: str,
params: Optional[Union[list[Any], dict[str, Any]]],
block: Optional[int] = None,
block_hash: Optional[str] = None,
reuse_block: bool = False,
) -> Optional[Any]:
"""Queries the runtime API of the Bittensor blockchain, providing a way to interact with the underlying runtime
and retrieve data encoded in Scale Bytes format. Use this function for nonstandard queries to the runtime
environment, if these cannot be accessed through other, standard getter methods.
Parameters:
runtime_api: The name of the runtime API to query.
method: The specific method within the runtime API to call.
params: The parameters to pass to the method call.
block: The block number to query. Do not specify if using `block_hash` or `reuse_block`.
block_hash: The block hash at which to check the parameter. Do not set if using `block` or
`reuse_block`.
reuse_block: Whether to reuse the last-used block hash. Do not set if using `block_hash` or `block`.
Returns:
The decoded result from the runtime API call, or `None` if the call fails.
"""
block_hash = await self.determine_block_hash(block, block_hash, reuse_block)
if not block_hash and reuse_block:
block_hash = self.substrate.last_block_hash
result = await self.substrate.runtime_call(
runtime_api, method, params, block_hash
)
return result.value
async def query_subtensor(
self,
name: str,
params: Optional[list] = None,
block: Optional[int] = None,
block_hash: Optional[str] = None,
reuse_block: bool = False,
) -> Optional[Union["ScaleObj", Any]]:
"""Queries named storage from the Subtensor module on the Bittensor blockchain.
Use this function for nonstandard queries to storage defined within the Bittensor blockchain, if these cannot
be accessed through other, standard getter methods.
Parameters:
name: The name of the storage function to query.
params: A list of parameters to pass to the query function.
block: The block number to query. Do not specify if using `block_hash` or `reuse_block`.
block_hash: The block hash at which to check the parameter. Do not set if using `block` or
`reuse_block`.
reuse_block: Whether to reuse the last-used block hash. Do not set if using `block_hash` or `block`.
Returns:
query_response: An object containing the requested data.
"""
block_hash = await self.determine_block_hash(block, block_hash, reuse_block)
return await self.substrate.query(
module="SubtensorModule",
storage_function=name,
params=params,
block_hash=block_hash,
reuse_block_hash=reuse_block,
)
async def state_call(
self,
method: str,
data: str,
block: Optional[int] = None,
block_hash: Optional[str] = None,
reuse_block: bool = False,
) -> dict[Any, Any]:
"""Makes a state call to the Bittensor blockchain, allowing for direct queries of the blockchain's state.
This function is typically used for advanced, nonstandard queries not provided by other getter methods.
Use this method when you need to query runtime APIs or storage functions that don't have dedicated
wrapper methods in the SDK. For standard queries, prefer the specific getter methods (e.g., `get_balance`,
`get_stake`) which provide better type safety and error handling.
Parameters:
method: The runtime API method name (e.g., "SubnetInfoRuntimeApi", "get_metagraph").
data: Hex-encoded string of the SCALE-encoded parameters to pass to the method.
block: The block number to query. Do not specify if using `block_hash` or `reuse_block`.
block_hash: The block hash at which to check the parameter. Do not set if using `block` or
`reuse_block`.
reuse_block: Whether to reuse the last-used block hash. Do not set if using `block_hash` or `block`.
Returns:
The result of the rpc call.
"""
block_hash = await self.determine_block_hash(block, block_hash, reuse_block)
return await self.substrate.rpc_request(
method="state_call",
params=[method, data],
block_hash=block_hash,
reuse_block_hash=reuse_block,
)
# Common subtensor methods =========================================================================================
async def all_subnets(
self,
block: Optional[int] = None,
block_hash: Optional[str] = None,
reuse_block: bool = False,
) -> Optional[list[DynamicInfo]]:
"""Queries the blockchain for comprehensive information about all subnets, including their dynamic parameters
and operational status.