-
Notifications
You must be signed in to change notification settings - Fork 276
/
subtensor.py
5538 lines (4715 loc) · 233 KB
/
subtensor.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
# The MIT License (MIT)
# Copyright © 2021 Yuma Rao
# Copyright © 2023 Opentensor Foundation
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
# documentation files (the “Software”), to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of
# the Software.
# THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
# THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
"""
The ``bittensor.subtensor`` module in Bittensor serves as a crucial interface for interacting with the Bittensor
blockchain, facilitating a range of operations essential for the decentralized machine learning network.
"""
import argparse
import copy
import functools
import socket
import time
from typing import List, Dict, Union, Optional, Tuple, TypedDict, Any
import numpy as np
import scalecodec
from numpy.typing import NDArray
from retry import retry
from scalecodec.base import RuntimeConfiguration
from scalecodec.exceptions import RemainingScaleBytesNotEmptyException
from scalecodec.type_registry import load_type_registry_preset
from scalecodec.types import GenericCall, ScaleType
from substrateinterface.base import QueryMapResult, SubstrateInterface, ExtrinsicReceipt
from substrateinterface.exceptions import SubstrateRequestException
import bittensor
from bittensor.btlogging import logging as _logger
from bittensor.utils import torch, weight_utils, format_error_message
from .chain_data import (
DelegateInfoLite,
NeuronInfo,
DelegateInfo,
PrometheusInfo,
SubnetInfo,
SubnetHyperparameters,
StakeInfo,
NeuronInfoLite,
AxonInfo,
ProposalVoteData,
IPInfo,
custom_rpc_type_registry,
)
from .errors import IdentityError, NominationError, StakeError, TakeError
from .extrinsics.commit_weights import (
commit_weights_extrinsic,
reveal_weights_extrinsic,
)
from .extrinsics.delegation import (
delegate_extrinsic,
nominate_extrinsic,
undelegate_extrinsic,
increase_take_extrinsic,
decrease_take_extrinsic,
)
from .extrinsics.network import (
register_subnetwork_extrinsic,
set_hyperparameter_extrinsic,
)
from .extrinsics.prometheus import prometheus_extrinsic
from .extrinsics.registration import (
register_extrinsic,
burned_register_extrinsic,
run_faucet_extrinsic,
swap_hotkey_extrinsic,
)
from .extrinsics.root import root_register_extrinsic, set_root_weights_extrinsic
from .extrinsics.senate import (
register_senate_extrinsic,
leave_senate_extrinsic,
vote_senate_extrinsic,
)
from .extrinsics.serving import (
serve_extrinsic,
serve_axon_extrinsic,
publish_metadata,
get_metadata,
)
from .extrinsics.set_weights import set_weights_extrinsic
from .extrinsics.staking import add_stake_extrinsic, add_stake_multiple_extrinsic
from .extrinsics.transfer import transfer_extrinsic
from .extrinsics.unstaking import unstake_extrinsic, unstake_multiple_extrinsic
from .types import AxonServeCallParams, PrometheusServeCallParams
from .utils import (
U16_NORMALIZED_FLOAT,
ss58_to_vec_u8,
U64_NORMALIZED_FLOAT,
networking,
)
from .utils.balance import Balance
from .utils.registration import POWSolution
from .utils.registration import legacy_torch_api_compat
from .utils.subtensor import get_subtensor_errors
KEY_NONCE: Dict[str, int] = {}
#######
# Monkey patch in caching the convert_type_string method
#######
if hasattr(RuntimeConfiguration, "convert_type_string"):
original_convert_type_string = RuntimeConfiguration.convert_type_string
@functools.lru_cache(maxsize=None)
def convert_type_string(_, name):
return original_convert_type_string(name)
RuntimeConfiguration.convert_type_string = convert_type_string
#######
class ParamWithTypes(TypedDict):
name: str # Name of the parameter.
type: str # ScaleType string of the parameter.
class Subtensor:
"""
The Subtensor class in Bittensor serves as a crucial interface for interacting with the Bittensor blockchain,
facilitating a range of operations essential for the decentralized machine learning network.
This class enables neurons (network participants) to engage in activities such as registering on the network,
managing staked weights, setting inter-neuronal weights, and participating in consensus mechanisms.
The Bittensor network operates on a digital ledger where each neuron holds stakes (S) and learns a set
of inter-peer weights (W). These weights, set by the neurons themselves, play a critical role in determining
the ranking and incentive mechanisms within the network. Higher-ranked neurons, as determined by their
contributions and trust within the network, receive more incentives.
The Subtensor class connects to various Bittensor networks like the main ``finney`` network or local test
networks, providing a gateway to the blockchain layer of Bittensor. It leverages a staked weighted trust
system and consensus to ensure fair and distributed incentive mechanisms, where incentives (I) are
primarily allocated to neurons that are trusted by the majority of the network.
Additionally, Bittensor introduces a speculation-based reward mechanism in the form of bonds (B), allowing
neurons to accumulate bonds in other neurons, speculating on their future value. This mechanism aligns
with market-based speculation, incentivizing neurons to make judicious decisions in their inter-neuronal
investments.
Example Usage::
# Connect to the main Bittensor network (Finney).
finney_subtensor = subtensor(network='finney')
# Close websocket connection with the Bittensor network.
finney_subtensor.close()
# (Re)creates the websocket connection with the Bittensor network.
finney_subtensor.connect_websocket()
# Register a new neuron on the network.
wallet = bittensor.wallet(...) # Assuming a wallet instance is created.
success = finney_subtensor.register(wallet=wallet, netuid=netuid)
# Set inter-neuronal weights for collaborative learning.
success = finney_subtensor.set_weights(wallet=wallet, netuid=netuid, uids=[...], weights=[...])
# Speculate by accumulating bonds in other promising neurons.
success = finney_subtensor.delegate(wallet=wallet, delegate_ss58=other_neuron_ss58, amount=bond_amount)
# Get the metagraph for a specific subnet using given subtensor connection
metagraph = subtensor.metagraph(netuid=netuid)
By facilitating these operations, the Subtensor class is instrumental in maintaining the decentralized
intelligence and dynamic learning environment of the Bittensor network, as envisioned in its foundational
principles and mechanisms described in the `NeurIPS paper
<https://bittensor.com/pdfs/academia/NeurIPS_DAO_Workshop_2022_3_3.pdf>`_. paper.
"""
def __init__(
self,
network: Optional[str] = None,
config: Optional[bittensor.config] = None,
_mock: bool = False,
log_verbose: bool = True,
) -> None:
"""
Initializes a Subtensor interface for interacting with the Bittensor blockchain.
NOTE:
Currently subtensor defaults to the ``finney`` network. This will change in a future release.
We strongly encourage users to run their own local subtensor node whenever possible. This increases
decentralization and resilience of the network. In a future release, local subtensor will become the
default and the fallback to ``finney`` removed. Please plan ahead for this change. We will provide detailed
instructions on how to run a local subtensor node in the documentation in a subsequent release.
Args:
network (str, optional): The network name to connect to (e.g., ``finney``, ``local``). This can also be the
chain endpoint (e.g., ``wss://entrypoint-finney.opentensor.ai:443``) and will be correctly parsed into
the network and chain endpoint. If not specified, defaults to the main Bittensor network.
config (bittensor.config, optional): Configuration object for the subtensor. If not provided, a default
configuration is used.
_mock (bool, optional): If set to ``True``, uses a mocked connection for testing purposes.
This initialization sets up the connection to the specified Bittensor network, allowing for various
blockchain operations such as neuron registration, stake management, and setting weights.
"""
# Determine config.subtensor.chain_endpoint and config.subtensor.network config.
# If chain_endpoint is set, we override the network flag, otherwise, the chain_endpoint is assigned by the
# network.
# Argument importance: network > chain_endpoint > config.subtensor.chain_endpoint > config.subtensor.network
# Check if network is a config object. (Single argument passed as first positional)
if isinstance(network, bittensor.config):
if network.subtensor is None:
_logger.warning(
"If passing a bittensor config object, it must not be empty. Using default subtensor config."
)
config = None
else:
config = network
network = None
if config is None:
config = Subtensor.config()
self.config = copy.deepcopy(config) # type: ignore
# Setup config.subtensor.network and config.subtensor.chain_endpoint
self.chain_endpoint, self.network = Subtensor.setup_config(network, config) # type: ignore
if (
self.network == "finney"
or self.chain_endpoint == bittensor.__finney_entrypoint__
) and log_verbose:
_logger.info(
f"You are connecting to {self.network} network with endpoint {self.chain_endpoint}."
)
_logger.warning(
"We strongly encourage running a local subtensor node whenever possible. "
"This increases decentralization and resilience of the network."
)
_logger.warning(
"In a future release, local subtensor will become the default endpoint. "
"To get ahead of this change, please run a local subtensor node and point to it."
)
# Attempt to connect to chosen endpoint. Fallback to finney if local unavailable.
try:
# Set up params.
self.substrate = SubstrateInterface(
ss58_format=bittensor.__ss58_format__,
use_remote_preset=True,
url=self.chain_endpoint,
type_registry=bittensor.__type_registry__,
)
except ConnectionRefusedError:
_logger.error(
f"Could not connect to {self.network} network with {self.chain_endpoint} chain endpoint. Exiting...",
)
_logger.info(
"You can check if you have connectivity by running this command: nc -vz localhost "
f"{self.chain_endpoint.split(':')[2]}"
)
exit(1)
# TODO (edu/phil): Advise to run local subtensor and point to dev docs.
try:
self.substrate.websocket.settimeout(600)
# except:
# bittensor.logging.warning("Could not set websocket timeout.")
except AttributeError as e:
_logger.warning(f"AttributeError: {e}")
except TypeError as e:
_logger.warning(f"TypeError: {e}")
except (socket.error, OSError) as e:
_logger.warning(f"Socket error: {e}")
if log_verbose:
_logger.info(
f"Connected to {self.network} network and {self.chain_endpoint}."
)
self._subtensor_errors: Dict[str, Dict[str, str]] = {}
def __str__(self) -> str:
if self.network == self.chain_endpoint:
# Connecting to chain endpoint without network known.
return "subtensor({})".format(self.chain_endpoint)
else:
# Connecting to network with endpoint known.
return "subtensor({}, {})".format(self.network, self.chain_endpoint)
def __repr__(self) -> str:
return self.__str__()
@staticmethod
def config() -> "bittensor.config":
"""
Creates and returns a Bittensor configuration object.
Returns:
config (bittensor.config): A Bittensor configuration object configured with arguments added by the
`subtensor.add_args` method.
"""
parser = argparse.ArgumentParser()
Subtensor.add_args(parser)
return bittensor.config(parser, args=[])
@classmethod
def help(cls):
"""Print help to stdout."""
parser = argparse.ArgumentParser()
cls.add_args(parser)
print(cls.__new__.__doc__)
parser.print_help()
@classmethod
def add_args(cls, parser: "argparse.ArgumentParser", prefix: Optional[str] = None):
"""
Adds command-line arguments to the provided ArgumentParser for configuring the Subtensor settings.
Args:
parser (argparse.ArgumentParser): The ArgumentParser object to which the Subtensor arguments will be added.
prefix (Optional[str]): An optional prefix for the argument names. If provided, the prefix is prepended to
each argument name.
Arguments added:
--subtensor.network: The Subtensor network flag. Possible values are 'finney', 'test', 'archive', and
'local'. Overrides the chain endpoint if set.
--subtensor.chain_endpoint: The Subtensor chain endpoint flag. If set, it overrides the network flag.
--subtensor._mock: If true, uses a mocked connection to the chain.
Example:
parser = argparse.ArgumentParser()
Subtensor.add_args(parser)
"""
prefix_str = "" if prefix is None else f"{prefix}."
try:
default_network = bittensor.__networks__[1]
default_chain_endpoint = bittensor.__finney_entrypoint__
parser.add_argument(
f"--{prefix_str}subtensor.network",
default=default_network,
type=str,
help="""The subtensor network flag. The likely choices are:
-- finney (main network)
-- test (test network)
-- archive (archive network +300 blocks)
-- local (local running network)
If this option is set it overloads subtensor.chain_endpoint with
an entry point node from that network.
""",
)
parser.add_argument(
f"--{prefix_str}subtensor.chain_endpoint",
default=default_chain_endpoint,
type=str,
help="""The subtensor endpoint flag. If set, overrides the --network flag.""",
)
parser.add_argument(
f"--{prefix_str}subtensor._mock",
default=False,
type=bool,
help="""If true, uses a mocked connection to the chain.""",
)
except argparse.ArgumentError:
# re-parsing arguments.
pass
@staticmethod
def determine_chain_endpoint_and_network(network: str):
"""Determines the chain endpoint and network from the passed network or chain_endpoint.
Args:
network (str): The network flag. The choices are: ``-- finney`` (main network), ``-- archive``
(archive network +300 blocks), ``-- local`` (local running network), ``-- test`` (test network).
Returns:
network (str): The network flag.
chain_endpoint (str): The chain endpoint flag. If set, overrides the ``network`` argument.
"""
if network is None:
return None, None
if network in ["finney", "local", "test", "archive"]:
if network == "finney":
# Kiru Finney staging network.
return network, bittensor.__finney_entrypoint__
elif network == "local":
return network, bittensor.__local_entrypoint__
elif network == "test":
return network, bittensor.__finney_test_entrypoint__
elif network == "archive":
return network, bittensor.__archive_entrypoint__
else:
if (
network == bittensor.__finney_entrypoint__
or "entrypoint-finney.opentensor.ai" in network
):
return "finney", bittensor.__finney_entrypoint__
elif (
network == bittensor.__finney_test_entrypoint__
or "test.finney.opentensor.ai" in network
):
return "test", bittensor.__finney_test_entrypoint__
elif (
network == bittensor.__archive_entrypoint__
or "archive.chain.opentensor.ai" in network
):
return "archive", bittensor.__archive_entrypoint__
elif "127.0.0.1" in network or "localhost" in network:
return "local", network
else:
return "unknown", network
@staticmethod
def setup_config(network: str, config: "bittensor.config"):
"""
Sets up and returns the configuration for the Subtensor network and endpoint.
This method determines the appropriate network and chain endpoint based on the provided network string or
configuration object. It evaluates the network and endpoint in the following order of precedence:
1. Provided network string.
2. Configured chain endpoint in the `config` object.
3. Configured network in the `config` object.
4. Default chain endpoint.
5. Default network.
Args:
network (str): The name of the Subtensor network. If None, the network and endpoint will be determined from
the `config` object.
config (bittensor.config): The configuration object containing the network and chain endpoint settings.
Returns:
tuple: A tuple containing the formatted WebSocket endpoint URL and the evaluated network name.
"""
if network is not None:
(
evaluated_network,
evaluated_endpoint,
) = Subtensor.determine_chain_endpoint_and_network(network)
else:
if config.get("__is_set", {}).get("subtensor.chain_endpoint"):
(
evaluated_network,
evaluated_endpoint,
) = Subtensor.determine_chain_endpoint_and_network(
config.subtensor.chain_endpoint
)
elif config.get("__is_set", {}).get("subtensor.network"):
(
evaluated_network,
evaluated_endpoint,
) = Subtensor.determine_chain_endpoint_and_network(
config.subtensor.network
)
elif config.subtensor.get("chain_endpoint"):
(
evaluated_network,
evaluated_endpoint,
) = Subtensor.determine_chain_endpoint_and_network(
config.subtensor.chain_endpoint
)
elif config.subtensor.get("network"):
(
evaluated_network,
evaluated_endpoint,
) = Subtensor.determine_chain_endpoint_and_network(
config.subtensor.network
)
else:
(
evaluated_network,
evaluated_endpoint,
) = Subtensor.determine_chain_endpoint_and_network(
bittensor.defaults.subtensor.network
)
return (
networking.get_formatted_ws_endpoint_url(evaluated_endpoint),
evaluated_network,
)
def close(self):
"""Cleans up resources for this subtensor instance like active websocket connection and active extensions."""
self.substrate.close()
##############
# Delegation #
##############
def nominate(
self,
wallet: "bittensor.wallet",
wait_for_finalization: bool = False,
wait_for_inclusion: bool = True,
) -> bool:
"""
Becomes a delegate for the hotkey associated with the given wallet. This method is used to nominate
a neuron (identified by the hotkey in the wallet) as a delegate on the Bittensor network, allowing it
to participate in consensus and validation processes.
Args:
wallet (bittensor.wallet): The wallet containing the hotkey to be nominated.
wait_for_finalization (bool, optional): If ``True``, waits until the transaction is finalized on the
blockchain.
wait_for_inclusion (bool, optional): If ``True``, waits until the transaction is included in a block.
Returns:
bool: ``True`` if the nomination process is successful, ``False`` otherwise.
This function is a key part of the decentralized governance mechanism of Bittensor, allowing for the
dynamic selection and participation of validators in the network's consensus process.
"""
return nominate_extrinsic(
subtensor=self,
wallet=wallet,
wait_for_finalization=wait_for_finalization,
wait_for_inclusion=wait_for_inclusion,
)
def delegate(
self,
wallet: "bittensor.wallet",
delegate_ss58: Optional[str] = None,
amount: Optional[Union[Balance, float]] = None,
wait_for_inclusion: bool = True,
wait_for_finalization: bool = False,
prompt: bool = False,
) -> bool:
"""
Becomes a delegate for the hotkey associated with the given wallet. This method is used to nominate
a neuron (identified by the hotkey in the wallet) as a delegate on the Bittensor network, allowing it
to participate in consensus and validation processes.
Args:
wallet (bittensor.wallet): The wallet containing the hotkey to be nominated.
delegate_ss58 (Optional[str]): The ``SS58`` address of the delegate neuron.
amount (Union[Balance, float]): The amount of TAO to undelegate.
wait_for_finalization (bool, optional): If ``True``, waits until the transaction is finalized on the
blockchain.
wait_for_inclusion (bool, optional): If ``True``, waits until the transaction is included in a block.
prompt (bool, optional): If ``True``, prompts for user confirmation before proceeding.
Returns:
bool: ``True`` if the nomination process is successful, False otherwise.
This function is a key part of the decentralized governance mechanism of Bittensor, allowing for the
dynamic selection and participation of validators in the network's consensus process.
"""
return delegate_extrinsic(
subtensor=self,
wallet=wallet,
delegate_ss58=delegate_ss58,
amount=amount,
wait_for_inclusion=wait_for_inclusion,
wait_for_finalization=wait_for_finalization,
prompt=prompt,
)
def undelegate(
self,
wallet: "bittensor.wallet",
delegate_ss58: Optional[str] = None,
amount: Optional[Union[Balance, float]] = None,
wait_for_inclusion: bool = True,
wait_for_finalization: bool = False,
prompt: bool = False,
) -> bool:
"""
Removes a specified amount of stake from a delegate neuron using the provided wallet. This action
reduces the staked amount on another neuron, effectively withdrawing support or speculation.
Args:
wallet (bittensor.wallet): The wallet used for the undelegation process.
delegate_ss58 (Optional[str]): The ``SS58`` address of the delegate neuron.
amount (Union[Balance, float]): The amount of TAO to undelegate.
wait_for_inclusion (bool, optional): Waits for the transaction to be included in a block.
wait_for_finalization (bool, optional): Waits for the transaction to be finalized on the blockchain.
prompt (bool, optional): If ``True``, prompts for user confirmation before proceeding.
Returns:
bool: ``True`` if the undelegation is successful, False otherwise.
This function reflects the dynamic and speculative nature of the Bittensor network, allowing neurons
to adjust their stakes and investments based on changing perceptions and performances within the network.
"""
return undelegate_extrinsic(
subtensor=self,
wallet=wallet,
delegate_ss58=delegate_ss58,
amount=amount,
wait_for_inclusion=wait_for_inclusion,
wait_for_finalization=wait_for_finalization,
prompt=prompt,
)
def set_take(
self,
wallet: "bittensor.wallet",
delegate_ss58: Optional[str] = None,
take: float = 0.0,
wait_for_inclusion: bool = True,
wait_for_finalization: bool = False,
) -> bool:
"""
Set delegate hotkey take
Args:
wallet (bittensor.wallet): The wallet containing the hotkey to be nominated.
delegate_ss58 (str, optional): Hotkey
take (float): Delegate take on subnet ID
wait_for_finalization (bool, optional): If ``True``, waits until the transaction is finalized on the
blockchain.
wait_for_inclusion (bool, optional): If ``True``, waits until the transaction is included in a block.
Returns:
bool: ``True`` if the process is successful, False otherwise.
This function is a key part of the decentralized governance mechanism of Bittensor, allowing for the
dynamic selection and participation of validators in the network's consensus process.
"""
# Ensure delegate_ss58 is not None
if delegate_ss58 is None:
raise ValueError("delegate_ss58 cannot be None")
# Calculate u16 representation of the take
takeu16 = int(take * 0xFFFF)
# Check if the new take is greater or lower than existing take or if existing is set
delegate = self.get_delegate_by_hotkey(delegate_ss58)
current_take = None
if delegate is not None:
current_take = int(float(delegate.take) * 65535.0)
if takeu16 == current_take:
bittensor.__console__.print("Nothing to do, take hasn't changed")
return True
if current_take is None or current_take < takeu16:
bittensor.__console__.print(
"Current take is either not set or is lower than the new one. Will use increase_take"
)
return increase_take_extrinsic(
subtensor=self,
wallet=wallet,
hotkey_ss58=delegate_ss58,
take=takeu16,
wait_for_inclusion=wait_for_inclusion,
wait_for_finalization=wait_for_finalization,
)
else:
bittensor.__console__.print(
"Current take is higher than the new one. Will use decrease_take"
)
return decrease_take_extrinsic(
subtensor=self,
wallet=wallet,
hotkey_ss58=delegate_ss58,
take=takeu16,
wait_for_inclusion=wait_for_inclusion,
wait_for_finalization=wait_for_finalization,
)
def send_extrinsic(
self,
wallet: "bittensor.wallet",
module: str,
function: str,
params: dict,
period: int = 5,
wait_for_inclusion: bool = False,
wait_for_finalization: bool = False,
max_retries: int = 3,
wait_time: int = 3,
max_wait: int = 20,
) -> Optional[ExtrinsicReceipt]:
"""
Sends an extrinsic to the Bittensor blockchain using the provided wallet and parameters. This method
constructs and submits the extrinsic, handling retries and blockchain communication.
Args:
wallet (bittensor.wallet): The wallet associated with the extrinsic.
module (str): The module name for the extrinsic.
function (str): The function name for the extrinsic.
params (dict): The parameters for the extrinsic.
period (int, optional): The number of blocks for the extrinsic to live in the mempool. Defaults to 5.
wait_for_inclusion (bool, optional): Waits for the transaction to be included in a block.
wait_for_finalization (bool, optional): Waits for the transaction to be finalized on the blockchain.
max_retries (int, optional): The maximum number of retries for the extrinsic. Defaults to 3.
wait_time (int, optional): The wait time between retries. Defaults to 3.
max_wait (int, optional): The maximum wait time for the extrinsic. Defaults to 20.
Returns:
Optional[ExtrinsicReceipt]: The receipt of the extrinsic if successful, None otherwise.
"""
call = self.substrate.compose_call(
call_module=module,
call_function=function,
call_params=params,
)
hotkey = wallet.get_hotkey().ss58_address
# Periodically update the nonce cache
if hotkey not in KEY_NONCE or self.get_current_block() % 5 == 0:
KEY_NONCE[hotkey] = self.substrate.get_account_nonce(hotkey)
nonce = KEY_NONCE[hotkey]
# <3 parity tech
old_init_runtime = self.substrate.init_runtime
self.substrate.init_runtime = lambda: None
self.substrate.init_runtime = old_init_runtime
response = None
for attempt in range(1, max_retries + 1):
try:
# Create the extrinsic with new nonce
extrinsic = self.substrate.create_signed_extrinsic(
call=call,
keypair=wallet.hotkey,
era={"period": period},
nonce=nonce,
)
# Submit the extrinsic
response = self.substrate.submit_extrinsic(
extrinsic,
wait_for_inclusion=wait_for_inclusion,
wait_for_finalization=wait_for_finalization,
)
# Return immediately if we don't wait
if not wait_for_inclusion and not wait_for_finalization:
KEY_NONCE[hotkey] = nonce + 1 # update the nonce cache
return response
# If we wait for finalization or inclusion, check if it is successful
if response.is_success:
KEY_NONCE[hotkey] = nonce + 1 # update the nonce cache
return response
else:
# Wait for a while
wait = min(wait_time * attempt, max_wait)
time.sleep(wait)
# Incr the nonce and try again
nonce = nonce + 1
continue
# This dies because user is spamming... incr and try again
except SubstrateRequestException as e:
if "Priority is too low" in e.args[0]["message"]:
wait = min(wait_time * attempt, max_wait)
_logger.warning(
f"Priority is too low, retrying with new nonce: {nonce} in {wait} seconds."
)
nonce = nonce + 1
time.sleep(wait)
continue
else:
_logger.error(f"Error sending extrinsic: {e}")
response = None
return response
###############
# Set Weights #
###############
# TODO: still needed? Can't find any usage of this method.
def set_weights(
self,
wallet: "bittensor.wallet",
netuid: int,
uids: Union[NDArray[np.int64], "torch.LongTensor", list],
weights: Union[NDArray[np.float32], "torch.FloatTensor", list],
version_key: int = bittensor.__version_as_int__,
wait_for_inclusion: bool = False,
wait_for_finalization: bool = False,
prompt: bool = False,
max_retries: int = 5,
) -> Tuple[bool, str]:
"""
Sets the inter-neuronal weights for the specified neuron. This process involves specifying the
influence or trust a neuron places on other neurons in the network, which is a fundamental aspect
of Bittensor's decentralized learning architecture.
Args:
wallet (bittensor.wallet): The wallet associated with the neuron setting the weights.
netuid (int): The unique identifier of the subnet.
uids (Union[NDArray[np.int64], torch.LongTensor, list]): The list of neuron UIDs that the weights are being
set for.
weights (Union[NDArray[np.float32], torch.FloatTensor, list]): The corresponding weights to be set for each
UID.
version_key (int, optional): Version key for compatibility with the network.
wait_for_inclusion (bool, optional): Waits for the transaction to be included in a block.
wait_for_finalization (bool, optional): Waits for the transaction to be finalized on the blockchain.
prompt (bool, optional): If ``True``, prompts for user confirmation before proceeding.
max_retries (int, optional): The number of maximum attempts to set weights. (Default: 5)
Returns:
Tuple[bool, str]: ``True`` if the setting of weights is successful, False otherwise. And `msg`, a string
value describing the success or potential error.
This function is crucial in shaping the network's collective intelligence, where each neuron's
learning and contribution are influenced by the weights it sets towards others【81†source】.
"""
uid = self.get_uid_for_hotkey_on_subnet(wallet.hotkey.ss58_address, netuid)
retries = 0
success = False
message = "No attempt made. Perhaps it is too soon to set weights!"
while (
self.blocks_since_last_update(netuid, uid) > self.weights_rate_limit(netuid) # type: ignore
and retries < max_retries
):
try:
success, message = set_weights_extrinsic(
subtensor=self,
wallet=wallet,
netuid=netuid,
uids=uids,
weights=weights,
version_key=version_key,
wait_for_inclusion=wait_for_inclusion,
wait_for_finalization=wait_for_finalization,
prompt=prompt,
)
except Exception as e:
_logger.error(f"Error setting weights: {e}")
finally:
retries += 1
return success, message
def _do_set_weights(
self,
wallet: "bittensor.wallet",
uids: List[int],
vals: List[int],
netuid: int,
version_key: int = bittensor.__version_as_int__,
wait_for_inclusion: bool = False,
wait_for_finalization: bool = False,
) -> Tuple[bool, Optional[str]]: # (success, error_message)
"""
Internal method to send a transaction to the Bittensor blockchain, setting weights
for specified neurons. This method constructs and submits the transaction, handling
retries and blockchain communication.
Args:
wallet (bittensor.wallet): The wallet associated with the neuron setting the weights.
uids (List[int]): List of neuron UIDs for which weights are being set.
vals (List[int]): List of weight values corresponding to each UID.
netuid (int): Unique identifier for the network.
version_key (int, optional): Version key for compatibility with the network.
wait_for_inclusion (bool, optional): Waits for the transaction to be included in a block.
wait_for_finalization (bool, optional): Waits for the transaction to be finalized on the blockchain.
Returns:
Tuple[bool, Optional[str]]: A tuple containing a success flag and an optional error message.
This method is vital for the dynamic weighting mechanism in Bittensor, where neurons adjust their
trust in other neurons based on observed performance and contributions.
"""
@retry(delay=1, tries=3, backoff=2, max_delay=4, logger=_logger)
def make_substrate_call_with_retry():
call = self.substrate.compose_call(
call_module="SubtensorModule",
call_function="set_weights",
call_params={
"dests": uids,
"weights": vals,
"netuid": netuid,
"version_key": version_key,
},
)
# Period dictates how long the extrinsic will stay as part of waiting pool
extrinsic = self.substrate.create_signed_extrinsic(
call=call,
keypair=wallet.hotkey,
era={"period": 5},
)
response = self.substrate.submit_extrinsic(
extrinsic,
wait_for_inclusion=wait_for_inclusion,
wait_for_finalization=wait_for_finalization,
)
# We only wait here if we expect finalization.
if not wait_for_finalization and not wait_for_inclusion:
return True, "Not waiting for finalization or inclusion."
response.process_events()
if response.is_success:
return True, "Successfully set weights."
else:
return False, format_error_message(response.error_message)
return make_substrate_call_with_retry()
##################
# Commit Weights #
##################
def commit_weights(
self,
wallet: "bittensor.wallet",
netuid: int,
salt: List[int],
uids: Union[NDArray[np.int64], list],
weights: Union[NDArray[np.int64], list],
version_key: int = bittensor.__version_as_int__,
wait_for_inclusion: bool = False,
wait_for_finalization: bool = False,
prompt: bool = False,
max_retries: int = 5,
) -> Tuple[bool, str]:
"""
Commits a hash of the neuron's weights to the Bittensor blockchain using the provided wallet.
This action serves as a commitment or snapshot of the neuron's current weight distribution.
Args:
wallet (bittensor.wallet): The wallet associated with the neuron committing the weights.
netuid (int): The unique identifier of the subnet.
salt (List[int]): list of randomly generated integers as salt to generated weighted hash.
uids (np.ndarray): NumPy array of neuron UIDs for which weights are being committed.
weights (np.ndarray): NumPy array of weight values corresponding to each UID.
version_key (int, optional): Version key for compatibility with the network.
wait_for_inclusion (bool, optional): Waits for the transaction to be included in a block.
wait_for_finalization (bool, optional): Waits for the transaction to be finalized on the blockchain.
prompt (bool, optional): If ``True``, prompts for user confirmation before proceeding.
max_retries (int, optional): The number of maximum attempts to commit weights. (Default: 5)
Returns:
Tuple[bool, str]: ``True`` if the weight commitment is successful, False otherwise. And `msg`, a string
value describing the success or potential error.
This function allows neurons to create a tamper-proof record of their weight distribution at a specific point in time,
enhancing transparency and accountability within the Bittensor network.
"""
retries = 0
success = False
message = "No attempt made. Perhaps it is too soon to commit weights!"
_logger.info(
"Committing weights with params: netuid={}, uids={}, weights={}, version_key={}".format(
netuid, uids, weights, version_key
)
)
# Generate the hash of the weights
commit_hash = weight_utils.generate_weight_hash(
address=wallet.hotkey.ss58_address,
netuid=netuid,
uids=list(uids),
values=list(weights),
salt=salt,
version_key=version_key,
)
_logger.info("Commit Hash: {}".format(commit_hash))
while retries < max_retries:
try:
success, message = commit_weights_extrinsic(
subtensor=self,
wallet=wallet,
netuid=netuid,
commit_hash=commit_hash,
wait_for_inclusion=wait_for_inclusion,
wait_for_finalization=wait_for_finalization,
prompt=prompt,
)
if success:
break
except Exception as e:
bittensor.logging.error(f"Error committing weights: {e}")
finally:
retries += 1
return success, message
def _do_commit_weights(
self,
wallet: "bittensor.wallet",
netuid: int,
commit_hash: str,
wait_for_inclusion: bool = False,
wait_for_finalization: bool = False,
) -> Tuple[bool, Optional[str]]:
"""
Internal method to send a transaction to the Bittensor blockchain, committing the hash of a neuron's weights.
This method constructs and submits the transaction, handling retries and blockchain communication.
Args: