-
Notifications
You must be signed in to change notification settings - Fork 74
Expand file tree
/
Copy pathsubtensor_interface.py
More file actions
1686 lines (1454 loc) · 62.3 KB
/
subtensor_interface.py
File metadata and controls
1686 lines (1454 loc) · 62.3 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 os
import time
from typing import Optional, Any, Union, TypedDict, Iterable
import aiohttp
from async_substrate_interface.async_substrate import (
DiskCachedAsyncSubstrateInterface,
AsyncSubstrateInterface,
)
from async_substrate_interface.errors import SubstrateRequestException
from async_substrate_interface.utils.storage import StorageKey
from bittensor_wallet import Wallet
from bittensor_wallet.bittensor_wallet import Keypair
from bittensor_wallet.utils import SS58_FORMAT
from scalecodec import GenericCall
import typer
import websockets
from bittensor_cli.src.bittensor.chain_data import (
DelegateInfo,
StakeInfo,
NeuronInfoLite,
NeuronInfo,
SubnetHyperparameters,
decode_account_id,
decode_hex_identity,
DynamicInfo,
SubnetState,
MetagraphInfo,
)
from bittensor_cli.src import DelegatesDetails
from bittensor_cli.src.bittensor.balances import Balance, fixed_to_float
from bittensor_cli.src import Constants, defaults, TYPE_REGISTRY
from bittensor_cli.src.bittensor.utils import (
format_error_message,
console,
err_console,
decode_hex_identity_dict,
validate_chain_endpoint,
u16_normalized_float,
U16_MAX,
get_hotkey_pub_ss58,
)
class ParamWithTypes(TypedDict):
name: str # Name of the parameter.
type: str # ScaleType string of the parameter.
class ProposalVoteData:
index: int
threshold: int
ayes: list[str]
nays: list[str]
end: int
def __init__(self, proposal_dict: dict) -> None:
self.index = proposal_dict["index"]
self.threshold = proposal_dict["threshold"]
self.ayes = self.decode_ss58_tuples(proposal_dict["ayes"])
self.nays = self.decode_ss58_tuples(proposal_dict["nays"])
self.end = proposal_dict["end"]
@staticmethod
def decode_ss58_tuples(data: tuple):
"""
Decodes a tuple of ss58 addresses formatted as bytes tuples
"""
return [decode_account_id(data[x][0]) for x in range(len(data))]
class SubtensorInterface:
"""
Thin layer for interacting with Substrate Interface. Mostly a collection of frequently-used calls.
"""
def __init__(self, network, use_disk_cache: bool = False):
if network in Constants.network_map:
self.chain_endpoint = Constants.network_map[network]
self.network = network
if network == "local":
console.log(
"[yellow]Warning[/yellow]: Verify your local subtensor is running on port 9944."
)
else:
is_valid, _ = validate_chain_endpoint(network)
if is_valid:
self.chain_endpoint = network
if network in Constants.network_map.values():
self.network = next(
key
for key, value in Constants.network_map.items()
if value == network
)
else:
self.network = "custom"
else:
console.log(
f"Network not specified or not valid. Using default chain endpoint: "
f"{Constants.network_map[defaults.subtensor.network]}.\n"
f"You can set this for commands with the `--network` flag, or by setting this"
f" in the config. If you're sure you're using the correct URL, ensure it begins"
f" with 'ws://' or 'wss://'"
)
self.chain_endpoint = Constants.network_map[defaults.subtensor.network]
self.network = defaults.subtensor.network
substrate_class = (
DiskCachedAsyncSubstrateInterface
if (use_disk_cache or os.getenv("DISK_CACHE", "0") == "1")
else AsyncSubstrateInterface
)
self.substrate = substrate_class(
url=self.chain_endpoint,
ss58_format=SS58_FORMAT,
type_registry=TYPE_REGISTRY,
chain_name="Bittensor",
)
def __str__(self):
return f"Network: {self.network}, Chain: {self.chain_endpoint}"
async def __aenter__(self):
with console.status(
f"[yellow]Connecting to Substrate:[/yellow][bold white] {self}..."
):
try:
await self.substrate.initialize()
return self
except TimeoutError: # TODO verify
err_console.print(
"\n[red]Error[/red]: Timeout occurred connecting to substrate. "
f"Verify your chain and network settings: {self}"
)
raise typer.Exit(code=1)
async def __aexit__(self, exc_type, exc_val, exc_tb):
await self.substrate.close()
async def query(
self,
module: str,
storage_function: str,
params: Optional[list] = None,
block_hash: Optional[str] = None,
raw_storage_key: Optional[bytes] = None,
subscription_handler=None,
reuse_block_hash: bool = False,
) -> Any:
"""
Pass-through to substrate.query which automatically returns the .value if it's a ScaleObj
"""
result = await self.substrate.query(
module,
storage_function,
params,
block_hash,
raw_storage_key,
subscription_handler,
reuse_block_hash,
)
if hasattr(result, "value"):
return result.value
else:
return result
async def get_all_subnet_netuids(
self, block_hash: Optional[str] = None
) -> list[int]:
"""
Retrieves the list of all subnet unique identifiers (netuids) currently present in the Bittensor network.
:param block_hash: The hash of the block to retrieve the subnet unique identifiers from.
:return: A list of subnet netuids.
This function provides a comprehensive view of the subnets within the Bittensor network,
offering insights into its diversity and scale.
"""
result = await self.substrate.query_map(
module="SubtensorModule",
storage_function="NetworksAdded",
block_hash=block_hash,
reuse_block_hash=True,
)
res = []
async for netuid, exists in result:
if exists.value:
res.append(netuid)
return res
async def get_stake_for_coldkey(
self,
coldkey_ss58: str,
block_hash: Optional[str] = None,
reuse_block: bool = False,
) -> list[StakeInfo]:
"""
Retrieves stake information associated with a specific coldkey. This function provides details
about the stakes held by an account, including the staked amounts and associated delegates.
:param coldkey_ss58: The ``SS58`` address of the account's coldkey.
:param block_hash: The hash of the blockchain block number for the query.
:param reuse_block: Whether to reuse the last-used block hash.
:return: A list of StakeInfo objects detailing the stake allocations for the account.
Stake information is vital for account holders to assess their investment and participation
in the network's delegation and consensus processes.
"""
result = await self.query_runtime_api(
runtime_api="StakeInfoRuntimeApi",
method="get_stake_info_for_coldkey",
params=[coldkey_ss58],
block_hash=block_hash,
reuse_block=reuse_block,
)
if result is None:
return []
stakes: list[StakeInfo] = StakeInfo.list_from_any(result)
return [stake for stake in stakes if stake.stake > 0]
async def get_stake_for_coldkey_and_hotkey(
self,
hotkey_ss58: str,
coldkey_ss58: str,
netuid: Optional[int] = None,
block_hash: Optional[str] = None,
) -> Balance:
"""
Returns the stake under a coldkey - hotkey pairing.
:param hotkey_ss58: The SS58 address of the hotkey.
:param coldkey_ss58: The SS58 address of the coldkey.
:param netuid: The subnet ID to filter by. If provided, only returns stake for this specific
subnet.
:param block_hash: The block hash at which to query the stake information.
:return: Balance: The stake under the coldkey - hotkey pairing.
"""
alpha_shares, hotkey_alpha, hotkey_shares = await asyncio.gather(
self.query(
module="SubtensorModule",
storage_function="Alpha",
params=[hotkey_ss58, coldkey_ss58, netuid],
block_hash=block_hash,
),
self.query(
module="SubtensorModule",
storage_function="TotalHotkeyAlpha",
params=[hotkey_ss58, netuid],
block_hash=block_hash,
),
self.query(
module="SubtensorModule",
storage_function="TotalHotkeyShares",
params=[hotkey_ss58, netuid],
block_hash=block_hash,
),
)
alpha_shares_as_float = fixed_to_float(alpha_shares or 0)
hotkey_shares_as_float = fixed_to_float(hotkey_shares or 0)
if hotkey_shares_as_float == 0:
return Balance.from_rao(0).set_unit(netuid=netuid)
stake = alpha_shares_as_float / hotkey_shares_as_float * (hotkey_alpha or 0)
return Balance.from_rao(int(stake)).set_unit(netuid=netuid)
# Alias
get_stake = get_stake_for_coldkey_and_hotkey
async def query_runtime_api(
self,
runtime_api: str,
method: str,
params: Optional[Union[list, dict]] = None,
block_hash: Optional[str] = None,
reuse_block: Optional[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. This function is essential for advanced users
who need to interact with specific runtime methods and decode complex data types.
:param runtime_api: The name of the runtime API to query.
:param method: The specific method within the runtime API to call.
:param params: The parameters to pass to the method call.
:param block_hash: The hash of the blockchain block number at which to perform the query.
:param reuse_block: Whether to reuse the last-used block hash.
:return: The decoded result from the runtime API call, or ``None`` if the call fails.
This function enables access to the deeper layers of the Bittensor blockchain, allowing for detailed
and specific interactions with the network's runtime environment.
"""
if reuse_block:
block_hash = self.substrate.last_block_hash
result = (
await self.substrate.runtime_call(runtime_api, method, params, block_hash)
).value
return result
async def get_balance(
self,
address: str,
block_hash: Optional[str] = None,
reuse_block: bool = False,
) -> Balance:
"""
Retrieves the balance for a single coldkey address
:param address: coldkey address
:param block_hash: the block hash, optional
:param reuse_block: Whether to reuse the last-used block hash when retrieving info.
:return: Balance object representing the address's balance
"""
result = await self.query(
module="System",
storage_function="Account",
params=[address],
block_hash=block_hash,
reuse_block_hash=reuse_block,
)
value = result or {"data": {"free": 0}}
return Balance(value["data"]["free"])
async def get_balances(
self,
*addresses: str,
block_hash: Optional[str] = None,
reuse_block: bool = False,
) -> dict[str, Balance]:
"""
Retrieves the balance for given coldkey(s)
:param addresses: coldkey addresses(s)
:param block_hash: the block hash, optional
:param reuse_block: Whether to reuse the last-used block hash when retrieving info.
:return: dict of {address: Balance objects}
"""
if reuse_block:
block_hash = self.substrate.last_block_hash
calls = [
(
await self.substrate.create_storage_key(
"System", "Account", [address], block_hash=block_hash
)
)
for address in addresses
]
batch_call = await self.substrate.query_multi(calls, block_hash=block_hash)
results = {}
for item in batch_call:
value = item[1] or {"data": {"free": 0}}
results.update({item[0].params[0]: Balance(value["data"]["free"])})
return results
async def get_total_stake_for_coldkey(
self,
*ss58_addresses,
block_hash: Optional[str] = None,
) -> dict[str, tuple[Balance, Balance]]:
"""
Returns the total stake held on a coldkey.
:param ss58_addresses: The SS58 address(es) of the coldkey(s)
:param block_hash: The hash of the block number to retrieve the stake from.
:return: {address: Balance objects}
"""
sub_stakes = await self.get_stake_for_coldkeys(
list(ss58_addresses), block_hash=block_hash
)
# Token pricing info
dynamic_info = await self.all_subnets()
results = {}
for ss58, stake_info_list in sub_stakes.items():
total_tao_value = Balance(0)
total_swapped_tao_value = Balance(0)
for sub_stake in stake_info_list:
if sub_stake.stake.rao == 0:
continue
netuid = sub_stake.netuid
pool = dynamic_info[netuid]
alpha_value = Balance.from_rao(int(sub_stake.stake.rao)).set_unit(
netuid
)
# Without slippage
tao_value = pool.alpha_to_tao(alpha_value)
total_tao_value += tao_value
# With slippage
if netuid == 0:
swapped_tao_value = tao_value
else:
swapped_tao_value, _, _ = pool.alpha_to_tao_with_slippage(
sub_stake.stake
)
total_swapped_tao_value += swapped_tao_value
results[ss58] = (total_tao_value, total_swapped_tao_value)
return results
async def get_total_stake_for_hotkey(
self,
*ss58_addresses,
netuids: Optional[list[int]] = None,
block_hash: Optional[str] = None,
reuse_block: bool = False,
) -> dict[str, dict[int, Balance]]:
"""
Returns the total stake held on a hotkey.
:param ss58_addresses: The SS58 address(es) of the hotkey(s)
:param netuids: The netuids to retrieve the stake from. If not specified, will use all subnets.
:param block_hash: The hash of the block number to retrieve the stake from.
:param reuse_block: Whether to reuse the last-used block hash when retrieving info.
:return:
{
hotkey_ss58_1: {
netuid_1: netuid1_stake,
netuid_2: netuid2_stake,
...
},
hotkey_ss58_2: {
netuid_1: netuid1_stake,
netuid_2: netuid2_stake,
...
},
...
}
"""
if not block_hash:
if reuse_block:
block_hash = self.substrate.last_block_hash
else:
block_hash = await self.substrate.get_chain_head()
netuids = netuids or await self.get_all_subnet_netuids(block_hash=block_hash)
calls = [
(
await self.substrate.create_storage_key(
"SubtensorModule",
"TotalHotkeyAlpha",
params=[ss58, netuid],
block_hash=block_hash,
)
)
for ss58 in ss58_addresses
for netuid in netuids
]
query = await self.substrate.query_multi(calls, block_hash=block_hash)
results: dict[str, dict[int, "Balance"]] = {
hk_ss58: {} for hk_ss58 in ss58_addresses
}
for idx, (_, val) in enumerate(query):
hotkey_ss58 = ss58_addresses[idx // len(netuids)]
netuid = netuids[idx % len(netuids)]
value = (Balance.from_rao(val) if val is not None else Balance(0)).set_unit(
netuid
)
results[hotkey_ss58][netuid] = value
return results
async def current_take(
self,
hotkey_ss58: int,
block_hash: Optional[str] = None,
reuse_block: bool = False,
) -> Optional[float]:
"""
Retrieves the delegate 'take' percentage for a neuron identified by its hotkey. The 'take'
represents the percentage of rewards that the delegate claims from its nominators' stakes.
:param hotkey_ss58: The `SS58` address of the neuron's hotkey.
:param block_hash: The hash of the block number to retrieve the stake from.
:param reuse_block: Whether to reuse the last-used block hash when retrieving info.
:return: The delegate take percentage, None if not available.
The delegate take is a critical parameter in the network's incentive structure, influencing
the distribution of rewards among neurons and their nominators.
"""
result = await self.query(
module="SubtensorModule",
storage_function="Delegates",
params=[hotkey_ss58],
block_hash=block_hash,
reuse_block_hash=reuse_block,
)
if result is None:
return None
else:
return u16_normalized_float(result)
async def get_netuids_for_hotkey(
self,
hotkey_ss58: str,
block_hash: Optional[str] = None,
reuse_block: bool = False,
) -> list[int]:
"""
Retrieves a list of subnet UIDs (netuids) for which a given hotkey is a member. This function
identifies the specific subnets within the Bittensor network where the neuron associated with
the hotkey is active.
:param hotkey_ss58: The ``SS58`` address of the neuron's hotkey.
:param block_hash: The hash of the blockchain block number at which to perform the query.
:param reuse_block: Whether to reuse the last-used block hash when retrieving info.
:return: A list of netuids where the neuron is a member.
"""
result = await self.substrate.query_map(
module="SubtensorModule",
storage_function="IsNetworkMember",
params=[hotkey_ss58],
block_hash=block_hash,
reuse_block_hash=reuse_block,
)
res = []
async for record in result:
if record[1].value:
res.append(record[0])
return res
async def is_subnet_active(
self,
netuid: int,
block_hash: Optional[str] = None,
reuse_block: bool = False,
) -> bool:
"""Verify if subnet with provided netuid is active.
Args:
netuid (int): The unique identifier of the subnet.
block_hash (Optional[str]): The blockchain block_hash representation of block id.
reuse_block (bool): Whether to reuse the last-used block hash.
Returns:
True if subnet is active, False otherwise.
This means whether the `start_call` was initiated or not.
"""
query = await self.substrate.query(
module="SubtensorModule",
storage_function="FirstEmissionBlockNumber",
block_hash=block_hash,
reuse_block_hash=reuse_block,
params=[netuid],
)
return True if query and query.value > 0 else False
async def subnet_exists(
self, netuid: int, block_hash: Optional[str] = None, reuse_block: bool = False
) -> bool:
"""
Checks if a subnet with the specified unique identifier (netuid) exists within the Bittensor network.
:param netuid: The unique identifier of the subnet.
:param block_hash: The hash of the blockchain block number at which to check the subnet existence.
:param reuse_block: Whether to reuse the last-used block hash.
:return: `True` if the subnet exists, `False` otherwise.
This function is critical for verifying the presence of specific subnets in the network,
enabling a deeper understanding of the network's structure and composition.
"""
result = await self.query(
module="SubtensorModule",
storage_function="NetworksAdded",
params=[netuid],
block_hash=block_hash,
reuse_block_hash=reuse_block,
)
return result
async def get_subnet_state(
self, netuid: int, block_hash: Optional[str] = None
) -> Optional["SubnetState"]:
"""
Retrieves the state of a specific subnet within the Bittensor network.
:param netuid: The network UID of the subnet to query.
:param block_hash: The hash of the blockchain block number for the query.
:return: SubnetState object containing the subnet's state information, or None if the subnet doesn't exist.
"""
result = await self.query_runtime_api(
runtime_api="SubnetInfoRuntimeApi",
method="get_subnet_state",
params=[netuid],
block_hash=block_hash,
)
if result is None:
return None
return SubnetState.from_any(result)
async def get_hyperparameter(
self,
param_name: str,
netuid: int,
block_hash: Optional[str] = None,
reuse_block: bool = False,
) -> Optional[Any]:
"""
Retrieves a specified hyperparameter for a specific subnet.
:param param_name: The name of the hyperparameter to retrieve.
:param netuid: The unique identifier of the subnet.
:param block_hash: The hash of blockchain block number for the query.
:param reuse_block: Whether to reuse the last-used block hash.
:return: The value of the specified hyperparameter if the subnet exists, or None
"""
if not await self.subnet_exists(netuid, block_hash):
print("subnet does not exist")
return None
result = await self.query(
module="SubtensorModule",
storage_function=param_name,
params=[netuid],
block_hash=block_hash,
reuse_block_hash=reuse_block,
)
if result is None:
return None
return result
async def filter_netuids_by_registered_hotkeys(
self,
all_netuids: Iterable[int],
filter_for_netuids: Iterable[int],
all_hotkeys: Iterable[Wallet],
block_hash: Optional[str] = None,
reuse_block: bool = False,
) -> list[int]:
"""
Filters a given list of all netuids for certain specified netuids and hotkeys
:param all_netuids: A list of netuids to filter.
:param filter_for_netuids: A subset of all_netuids to filter from the main list
:param all_hotkeys: Hotkeys to filter from the main list
:param block_hash: hash of the blockchain block number at which to perform the query.
:param reuse_block: whether to reuse the last-used blockchain hash when retrieving info.
:return: the filtered list of netuids.
"""
netuids_with_registered_hotkeys = [
item
for sublist in await asyncio.gather(
*[
self.get_netuids_for_hotkey(
get_hotkey_pub_ss58(wallet),
reuse_block=reuse_block,
block_hash=block_hash,
)
for wallet in all_hotkeys
]
)
for item in sublist
]
if not filter_for_netuids:
all_netuids = netuids_with_registered_hotkeys
else:
filtered_netuids = [
netuid for netuid in all_netuids if netuid in filter_for_netuids
]
registered_hotkeys_filtered = [
netuid
for netuid in netuids_with_registered_hotkeys
if netuid in filter_for_netuids
]
# Combine both filtered lists
all_netuids = filtered_netuids + registered_hotkeys_filtered
return list(set(all_netuids))
async def get_existential_deposit(
self, block_hash: Optional[str] = None, reuse_block: bool = False
) -> Balance:
"""
Retrieves the existential deposit amount for the Bittensor blockchain. The existential deposit
is the minimum amount of TAO required for an account to exist on the blockchain. Accounts with
balances below this threshold can be reaped to conserve network resources.
:param block_hash: Block hash at which to query the deposit amount. If `None`, the current block is used.
:param reuse_block: Whether to reuse the last-used blockchain block hash.
:return: The existential deposit amount
The existential deposit is a fundamental economic parameter in the Bittensor network, ensuring
efficient use of storage and preventing the proliferation of dust accounts.
"""
result = getattr(
await self.substrate.get_constant(
module_name="Balances",
constant_name="ExistentialDeposit",
block_hash=block_hash,
reuse_block_hash=reuse_block,
),
"value",
None,
)
if result is None:
raise Exception("Unable to retrieve existential deposit amount.")
return Balance.from_rao(result)
async def neurons(
self, netuid: int, block_hash: Optional[str] = None
) -> list[NeuronInfo]:
"""
Retrieves a list of all neurons within a specified subnet of the Bittensor network. This function
provides a snapshot of the subnet's neuron population, including each neuron's attributes and network
interactions.
:param netuid: The unique identifier of the subnet.
:param block_hash: The hash of the blockchain block number for the query.
:return: A list of NeuronInfo objects detailing each neuron's characteristics in the subnet.
Understanding the distribution and status of neurons within a subnet is key to comprehending the
network's decentralized structure and the dynamics of its consensus and governance processes.
"""
neurons_lite, weights, bonds = await asyncio.gather(
self.neurons_lite(netuid=netuid, block_hash=block_hash),
self.weights(netuid=netuid, block_hash=block_hash),
self.bonds(netuid=netuid, block_hash=block_hash),
)
weights_as_dict = {uid: w for uid, w in weights}
bonds_as_dict = {uid: b for uid, b in bonds}
neurons = [
NeuronInfo.from_weights_bonds_and_neuron_lite(
neuron_lite, weights_as_dict, bonds_as_dict
)
for neuron_lite in neurons_lite
]
return neurons
async def neurons_lite(
self, netuid: int, block_hash: Optional[str] = None, reuse_block: bool = False
) -> list[NeuronInfoLite]:
"""
Retrieves a list of neurons in a 'lite' format from a specific subnet of the Bittensor network.
This function provides a streamlined view of the neurons, focusing on key attributes such as stake
and network participation.
:param netuid: The unique identifier of the subnet.
:param block_hash: The hash of the blockchain block number for the query.
:param reuse_block: Whether to reuse the last-used blockchain block hash.
:return: A list of simplified neuron information for the subnet.
This function offers a quick overview of the neuron population within a subnet, facilitating
efficient analysis of the network's decentralized structure and neuron dynamics.
"""
result = await self.query_runtime_api(
runtime_api="NeuronInfoRuntimeApi",
method="get_neurons_lite",
params=[netuid],
block_hash=block_hash,
reuse_block=reuse_block,
)
if result is None:
return []
return NeuronInfoLite.list_from_any(result)
async def neuron_for_uid(
self, uid: Optional[int], netuid: int, block_hash: Optional[str] = None
) -> NeuronInfo:
"""
Retrieves detailed information about a specific neuron identified by its unique identifier (UID)
within a specified subnet (netuid) of the Bittensor network. This function provides a comprehensive
view of a neuron's attributes, including its stake, rank, and operational status.
:param uid: The unique identifier of the neuron.
:param netuid: The unique identifier of the subnet.
:param block_hash: The hash of the blockchain block number for the query.
:return: Detailed information about the neuron if found, a null neuron otherwise
This function is crucial for analyzing individual neurons' contributions and status within a specific
subnet, offering insights into their roles in the network's consensus and validation mechanisms.
"""
if uid is None:
return NeuronInfo.get_null_neuron()
result = await self.query_runtime_api(
runtime_api="NeuronInfoRuntimeApi",
method="get_neuron",
params=[
netuid,
uid,
], # TODO check to see if this can accept more than one at a time
block_hash=block_hash,
)
if not result:
return NeuronInfo.get_null_neuron()
return NeuronInfo.from_any(result)
async def get_delegated(
self,
coldkey_ss58: str,
block_hash: Optional[str] = None,
reuse_block: bool = False,
) -> list[tuple[DelegateInfo, Balance]]:
"""
Retrieves a list of delegates and their associated stakes for a given coldkey. This function
identifies the delegates that a specific account has staked tokens on.
:param coldkey_ss58: The `SS58` address of the account's coldkey.
:param block_hash: The hash of the blockchain block number for the query.
:param reuse_block: Whether to reuse the last-used blockchain block hash.
:return: A list of tuples, each containing a delegate's information and staked amount.
This function is important for account holders to understand their stake allocations and their
involvement in the network's delegation and consensus mechanisms.
"""
block_hash = (
block_hash
if block_hash
else (self.substrate.last_block_hash if reuse_block else None)
)
result = await self.query_runtime_api(
runtime_api="DelegateInfoRuntimeApi",
method="get_delegated",
params=[coldkey_ss58],
block_hash=block_hash,
)
if not result:
return []
return DelegateInfo.list_from_any(result)
async def query_all_identities(
self,
block_hash: Optional[str] = None,
reuse_block: bool = False,
) -> dict[str, dict]:
"""
Queries all identities on the Bittensor blockchain.
:param block_hash: The hash of the blockchain block number at which to perform the query.
:param reuse_block: Whether to reuse the last-used blockchain block hash.
:return: A dictionary mapping addresses to their decoded identity data.
"""
identities = await self.substrate.query_map(
module="SubtensorModule",
storage_function="IdentitiesV2",
block_hash=block_hash,
reuse_block_hash=reuse_block,
fully_exhaust=True,
)
all_identities = {}
for ss58_address, identity in identities.records:
all_identities[decode_account_id(ss58_address[0])] = decode_hex_identity(
identity.value
)
return all_identities
async def query_identity(
self,
key: str,
block_hash: Optional[str] = None,
reuse_block: bool = False,
) -> dict:
"""
Queries the identity of a neuron on the Bittensor blockchain using the given key. This function retrieves
detailed identity information about a specific neuron, which is a crucial aspect of the network's decentralized
identity and governance system.
Note:
See the `Bittensor CLI documentation <https://docs.bittensor.com/reference/btcli>`_ for supported identity
parameters.
:param key: The key used to query the neuron's identity, typically the neuron's SS58 address.
:param block_hash: The hash of the blockchain block number at which to perform the query.
:param reuse_block: Whether to reuse the last-used blockchain block hash.
:return: An object containing the identity information of the neuron if found, ``None`` otherwise.
The identity information can include various attributes such as the neuron's stake, rank, and other
network-specific details, providing insights into the neuron's role and status within the Bittensor network.
"""
identity_info = await self.query(
module="SubtensorModule",
storage_function="IdentitiesV2",
params=[key],
block_hash=block_hash,
reuse_block_hash=reuse_block,
)
if not identity_info:
return {}
try:
return decode_hex_identity(identity_info)
except TypeError:
return {}
async def fetch_coldkey_hotkey_identities(
self,
block_hash: Optional[str] = None,
reuse_block: bool = False,
) -> dict[str, dict]:
"""
Builds a dictionary containing coldkeys and hotkeys with their associated identities and relationships.
:param block_hash: The hash of the blockchain block number for the query.
:param reuse_block: Whether to reuse the last-used blockchain block hash.
:return: Dict with 'coldkeys' and 'hotkeys' as keys.
"""
if block_hash is None:
block_hash = await self.substrate.get_chain_head()
coldkey_identities = await self.query_all_identities(block_hash=block_hash)
identities = {"coldkeys": {}, "hotkeys": {}}
sks = [
await self.substrate.create_storage_key(
"SubtensorModule", "OwnedHotkeys", [ck], block_hash=block_hash
)
for ck in coldkey_identities.keys()
]
query = await self.substrate.query_multi(sks, block_hash=block_hash)
storage_key: StorageKey
for storage_key, hotkeys in query:
coldkey_ss58 = storage_key.params[0]
coldkey_identity = coldkey_identities.get(coldkey_ss58)
identities["coldkeys"][coldkey_ss58] = {
"identity": coldkey_identity,
"hotkeys": hotkeys,
}
for hotkey_ss58 in hotkeys:
identities["hotkeys"][hotkey_ss58] = {
"coldkey": coldkey_ss58,
"identity": coldkey_identity,
}
return identities
async def weights(
self, netuid: int, block_hash: Optional[str] = None
) -> list[tuple[int, list[tuple[int, int]]]]:
"""
Retrieves the weight distribution set by neurons within a specific subnet of the Bittensor network.
This function maps each neuron's UID to the weights it assigns to other neurons, reflecting the
network's trust and value assignment mechanisms.
:param netuid: The network UID of the subnet to query.
:param block_hash: The hash of the blockchain block for the query.
:return: A list of tuples mapping each neuron's UID to its assigned weights.
The weight distribution is a key factor in the network's consensus algorithm and the ranking of neurons,
influencing their influence and reward allocation within the subnet.
"""
w_map_encoded = await self.substrate.query_map(
module="SubtensorModule",
storage_function="Weights",
params=[netuid],
block_hash=block_hash,
)
w_map = []
async for uid, w in w_map_encoded:
w_map.append((uid, w.value))