diff --git a/CHANGELOG.md b/CHANGELOG.md index 6d3859e6b3..dc46f70733 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,28 @@ # Changelog + +## 6.7.0 / 2024-01-25 + +## What's Changed +* First docstrings formatting PR by @rajkaramchedu in https://github.com/opentensor/bittensor/pull/1663 +* Second docstrings formatting PR by @rajkaramchedu in https://github.com/opentensor/bittensor/pull/1665 +* Third docstrings formatting PR by @rajkaramchedu in https://github.com/opentensor/bittensor/pull/1666 +* updated mac yaml mac yaml by @dougsillars in https://github.com/opentensor/bittensor/pull/1668 +* Fourth docstrings formatting PR by @rajkaramchedu in https://github.com/opentensor/bittensor/pull/1670 +* Fifth docstrings formatting PR by @rajkaramchedu in https://github.com/opentensor/bittensor/pull/1671 +* ensure branch off from staging and rm old docs by @ifrit98 in https://github.com/opentensor/bittensor/pull/1667 +* staging black format fix by @ifrit98 in https://github.com/opentensor/bittensor/pull/1669 +* wallet history url for taostats by @ifrit98 in https://github.com/opentensor/bittensor/pull/1672 +* take bt.config as a first argument regardless if specified by @ifrit98 in https://github.com/opentensor/bittensor/pull/1664 +* Hparams update by @ifrit98 in https://github.com/opentensor/bittensor/pull/1673 + +## New Contributors +* @rajkaramchedu made their first contribution in https://github.com/opentensor/bittensor/pull/1663 +* @dougsillars made their first contribution in https://github.com/opentensor/bittensor/pull/1668 + +**Full Changelog**: https://github.com/opentensor/bittensor/compare/v6.6.1...v6.7.0 + + ## 6.6.1 / 2024-01-17 ## What's Changed diff --git a/VERSION b/VERSION index ba92e72f57..07a7b03c99 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -6.6.1 \ No newline at end of file +6.7.0 \ No newline at end of file diff --git a/bittensor/__init__.py b/bittensor/__init__.py index 05171430f2..f27a85ebd4 100644 --- a/bittensor/__init__.py +++ b/bittensor/__init__.py @@ -27,7 +27,7 @@ nest_asyncio.apply() # Bittensor code and protocol version. -__version__ = "6.6.1" +__version__ = "6.7.0" version_split = __version__.split(".") __version_as_int__ = ( diff --git a/bittensor/axon.py b/bittensor/axon.py index 899186ecb8..59f45ba4f0 100644 --- a/bittensor/axon.py +++ b/bittensor/axon.py @@ -1,4 +1,4 @@ -""" Create and init Axon, whcih services Forward and Backward requests from other neurons. +""" Create and initialize Axon, which services the forward and backward requests from other neurons. """ # The MIT License (MIT) # Copyright © 2021 Yuma Rao @@ -59,47 +59,37 @@ class FastAPIThreadedServer(uvicorn.Server): """ - The `FastAPIThreadedServer` class is a specialized server implementation for the Axon server in the - Bittensor network. It extends the functionality of `uvicorn.Server` to run the FastAPI application - in a separate thread, allowing the Axon server to handle HTTP requests concurrently and non-blocking. + The ``FastAPIThreadedServer`` class is a specialized server implementation for the Axon server in the Bittensor network. - This class is designed to facilitate the integration of FastAPI with the Axon's asynchronous - architecture, ensuring efficient and scalable handling of network requests. + It extends the functionality of :func:`uvicorn.Server` to run the FastAPI application in a separate thread, allowing the Axon server to handle HTTP requests concurrently and non-blocking. - Importance and Functionality: - Threaded Execution: The class allows the FastAPI application to run in a separate thread, - enabling concurrent handling of HTTP requests which is crucial for the performance and - scalability of the Axon server. + This class is designed to facilitate the integration of FastAPI with the Axon's asynchronous architecture, ensuring efficient and scalable handling of network requests. - Seamless Integration: By running FastAPI in a threaded manner, this class ensures seamless integration - of FastAPI's capabilities with the Axon server's asynchronous and multi-threaded architecture. + Importance and Functionality + Threaded Execution + The class allows the FastAPI application to run in a separate thread, enabling concurrent handling of HTTP requests which is crucial for the performance and scalability of the Axon server. + + Seamless Integration + By running FastAPI in a threaded manner, this class ensures seamless integration of FastAPI's capabilities with the Axon server's asynchronous and multi-threaded architecture. - Controlled Server Management: The methods start and stop provide controlled management of the server's - lifecycle, ensuring that the server can be started and stopped as needed, which is vital for - maintaining the Axon server's reliability and availability. + Controlled Server Management + The methods start and stop provide controlled management of the server's lifecycle, ensuring that the server can be started and stopped as needed, which is vital for maintaining the Axon server's reliability and availability. - Signal Handling: Overriding the default signal handlers prevents potential conflicts with the Axon - server's main application flow, ensuring stable operation in various network conditions. + Signal Handling + Overriding the default signal handlers prevents potential conflicts with the Axon server's main application flow, ensuring stable operation in various network conditions. - Use Cases: - Starting the Server: When the Axon server is initialized, it can use this class to start the - FastAPI application in a separate thread, enabling it to begin handling HTTP requests immediately. - Stopping the Server: During shutdown or maintenance of the Axon server, this class can be used - to stop the FastAPI application gracefully, ensuring that all resources are properly released. + Use Cases + Starting the Server + When the Axon server is initialized, it can use this class to start the FastAPI application in a separate thread, enabling it to begin handling HTTP requests immediately. - Attributes: + Stopping the Server + During shutdown or maintenance of the Axon server, this class can be used to stop the FastAPI application gracefully, ensuring that all resources are properly released. + + Args: should_exit (bool): Flag to indicate whether the server should stop running. is_running (bool): Flag to indicate whether the server is currently running. - The server overrides the default signal handlers to prevent interference with the main application - flow and provides methods to start and stop the server in a controlled manner. - - Methods: - install_signal_handlers: Overrides the default signal handlers. - run_in_thread: Manages the execution of the server in a separate thread. - _wrapper_run: Wraps the run_in_thread method for thread execution. - start: Starts the server thread if it is not already running. - stop: Signals the server thread to stop running. + The server overrides the default signal handlers to prevent interference with the main application flow and provides methods to start and stop the server in a controlled manner. """ should_exit: bool = False @@ -107,22 +97,17 @@ class FastAPIThreadedServer(uvicorn.Server): def install_signal_handlers(self): """ - Overrides the default signal handlers provided by `uvicorn.Server`. This method is essential to - ensure that the signal handling in the threaded server does not interfere with the main - application's flow, especially in a complex asynchronous environment like the Axon server. + Overrides the default signal handlers provided by ``uvicorn.Server``. This method is essential to ensure that the signal handling in the threaded server does not interfere with the main application's flow, especially in a complex asynchronous environment like the Axon server. """ pass @contextlib.contextmanager def run_in_thread(self): """ - Manages the execution of the server in a separate thread, allowing the FastAPI application to - run asynchronously without blocking the main thread of the Axon server. This method is a key - component in enabling concurrent request handling in the Axon server. + Manages the execution of the server in a separate thread, allowing the FastAPI application to run asynchronously without blocking the main thread of the Axon server. This method is a key component in enabling concurrent request handling in the Axon server. Yields: - None: This method yields control back to the caller while the server is running in the - background thread. + None: This method yields control back to the caller while the server is running in the background thread. """ thread = threading.Thread(target=self.run, daemon=True) thread.start() @@ -136,8 +121,7 @@ def run_in_thread(self): def _wrapper_run(self): """ - A wrapper method for the `run_in_thread` context manager. This method is used internally by the - `start` method to initiate the server's execution in a separate thread. + A wrapper method for the :func:`run_in_thread` context manager. This method is used internally by the ``start`` method to initiate the server's execution in a separate thread. """ with self.run_in_thread(): while not self.should_exit: @@ -145,12 +129,10 @@ def _wrapper_run(self): def start(self): """ - Starts the FastAPI server in a separate thread if it is not already running. This method sets up - the server to handle HTTP requests concurrently, enabling the Axon server to efficiently manage + Starts the FastAPI server in a separate thread if it is not already running. This method sets up the server to handle HTTP requests concurrently, enabling the Axon server to efficiently manage incoming network requests. - The method ensures that the server starts running in a non-blocking manner, allowing the Axon - server to continue its other operations seamlessly. + The method ensures that the server starts running in a non-blocking manner, allowing the Axon server to continue its other operations seamlessly. """ if not self.is_running: self.should_exit = False @@ -160,11 +142,9 @@ def start(self): def stop(self): """ - Signals the FastAPI server to stop running. This method sets the `should_exit` flag to `True`, - indicating that the server should cease its operations and exit the running thread. + Signals the FastAPI server to stop running. This method sets the :func:`should_exit` flag to ``True``, indicating that the server should cease its operations and exit the running thread. - Stopping the server is essential for controlled shutdowns and resource management in the Axon - server, especially during maintenance or when redeploying with updated configurations. + Stopping the server is essential for controlled shutdowns and resource management in the Axon server, especially during maintenance or when redeploying with updated configurations. """ if self.is_running: self.should_exit = True @@ -172,8 +152,9 @@ def stop(self): class axon: """ - The `axon` class in Bittensor is a fundamental component that serves as the server-side - interface for a neuron within the Bittensor network. This class is responsible for managing + The ``axon`` class in Bittensor is a fundamental component that serves as the server-side interface for a neuron within the Bittensor network. + + This class is responsible for managing incoming requests from other neurons and implements various mechanisms to ensure efficient and secure network interactions. @@ -191,85 +172,83 @@ class is designed to be flexible and customizable, allowing users to specify cus the attachment and operation of endpoints. Key Features: + - FastAPI router integration for endpoint creation and management. - Customizable request handling including forwarding, blacklisting, and prioritization. - Verification of incoming requests against custom-defined functions. - Thread pool management for concurrent request handling. - Command-line argument support for user-friendly program interaction. - Example Usage: - - ```python - import bittensor - - # Define your custom synapse class - class MySyanpse( bittensor.Synapse ): - input: int = 1 - output: int = None - - # Define a custom request forwarding function using your synapse class - def forward( synapse: MySyanpse ) -> MySyanpse: - # Apply custom logic to synapse and return it - synapse.output = 2 - return synapse + Example Usage:: + + import bittensor + # Define your custom synapse class + class MySyanpse( bittensor.Synapse ): + input: int = 1 + output: int = None + + # Define a custom request forwarding function using your synapse class + def forward( synapse: MySyanpse ) -> MySyanpse: + # Apply custom logic to synapse and return it + synapse.output = 2 + return synapse + + # Define a custom request verification function + def verify_my_synapse( synapse: MySyanpse ): + # Apply custom verification logic to synapse + # Optionally raise Exception + assert synapse.input == 1 + ... - # Define a custom request verification function - def verify_my_synapse( synapse: MySyanpse ): - # Apply custom verification logic to synapse - # Optionally raise Exception - assert synapse.input == 1 - ... - - # Define a custom request blacklist fucntion - def blacklist_my_synapse( synapse: MySyanpse ) -> bool: - # Apply custom blacklist - return False ( if non blacklisted ) or True ( if blacklisted ) - - # Define a custom request priority fucntion - def prioritize_my_synape( synapse: MySyanpse ) -> float: - # Apply custom priority - return 1.0 - - # Initialize Axon object with a custom configuration - my_axon = bittensor.axon( - config=my_config, - wallet=my_wallet, - port=9090, - ip="192.0.2.0", - external_ip="203.0.113.0", - external_port=7070 - ) + # Define a custom request blacklist fucntion + def blacklist_my_synapse( synapse: MySyanpse ) -> bool: + # Apply custom blacklist + return False ( if non blacklisted ) or True ( if blacklisted ) + + # Define a custom request priority fucntion + def prioritize_my_synape( synapse: MySyanpse ) -> float: + # Apply custom priority + return 1.0 + + # Initialize Axon object with a custom configuration + my_axon = bittensor.axon( + config=my_config, + wallet=my_wallet, + port=9090, + ip="192.0.2.0", + external_ip="203.0.113.0", + external_port=7070 + ) - # Attach the endpoint with the specified verification and forward functions. - my_axon.attach( - forward_fn = forward_my_synapse, - verify_fn = verify_my_synapse, - blacklist_fn = blacklist_my_synapse, - priority_fn = prioritize_my_synape - ) + # Attach the endpoint with the specified verification and forward functions. + my_axon.attach( + forward_fn = forward_my_synapse, + verify_fn = verify_my_synapse, + blacklist_fn = blacklist_my_synapse, + priority_fn = prioritize_my_synape + ) - # Serve and start your axon. - my_axon.serve( - netuid = ... - subtensor = ... - ).start() - - # If you have multiple forwarding functions, you can chain attach them. - my_axon.attach( - forward_fn = forward_my_synapse, - verify_fn = verify_my_synapse, - blacklist_fn = blacklist_my_synapse, - priority_fn = prioritize_my_synape - ).attach( - forward_fn = forward_my_synapse_2, - verify_fn = verify_my_synapse_2, - blacklist_fn = blacklist_my_synapse_2, - priority_fn = prioritize_my_synape_2 - ).serve( - netuid = ... - subtensor = ... - ).start() - ``` + # Serve and start your axon. + my_axon.serve( + netuid = ... + subtensor = ... + ).start() + + # If you have multiple forwarding functions, you can chain attach them. + my_axon.attach( + forward_fn = forward_my_synapse, + verify_fn = verify_my_synapse, + blacklist_fn = blacklist_my_synapse, + priority_fn = prioritize_my_synape + ).attach( + forward_fn = forward_my_synapse_2, + verify_fn = verify_my_synapse_2, + blacklist_fn = blacklist_my_synapse_2, + priority_fn = prioritize_my_synape_2 + ).serve( + netuid = ... + subtensor = ... + ).start() Args: wallet (bittensor.wallet, optional): Wallet with hotkey and coldkeypub. @@ -288,22 +267,21 @@ def prioritize_my_synape( synapse: MySyanpse ) -> float: allowing neurons to communicate effectively and securely. Importance and Functionality - Endpoint Registration: This method dynamically registers API endpoints based on the Synapse class - used, allowing the Axon to respond to specific types of requests and synapses. + Endpoint Registration + This method dynamically registers API endpoints based on the Synapse used, allowing the Axon to respond to specific types of requests and synapses. - Customization of Request Handling: By attaching different functions, the Axon can customize how it - handles, verifies, prioritizes, and potentially blocks incoming requests, making it adaptable - to various network scenarios. + Customization of Request Handling + By attaching different functions, the Axon can customize how it + handles, verifies, prioritizes, and potentially blocks incoming requests, making it adaptable to various network scenarios. - Security and Efficiency: The method contributes to both the security (via verification and blacklisting) - and efficiency (via prioritization) of request handling, which are crucial in a decentralized - network environment. + Security and Efficiency + The method contributes to both the security (via verification and blacklisting) and efficiency (via prioritization) of request handling, which are crucial in a decentralized network environment. - Flexibility: The ability to define custom functions for different aspects of request handling - provides great flexibility, allowing the Axon to be tailored to specific needs and use cases - within the Bittensor network. + Flexibility + The ability to define custom functions for different aspects of request handling provides great flexibility, allowing the Axon to be tailored to specific needs and use cases within the Bittensor network. - Error Handling and Validation: The method ensures that the attached functions meet the required + Error Handling and Validation + The method ensures that the attached functions meet the required signatures, providing error handling to prevent runtime issues. """ @@ -436,7 +414,7 @@ def attach( prioritization, thereby customizing its interaction within the Bittensor network. Registers an API endpoint to the FastAPI application router. - It uses the name of the first argument of the 'forward_fn' function as the endpoint name. + It uses the name of the first argument of the :func:`forward_fn` function as the endpoint name. The attach method in the Bittensor framework's axon class is a crucial function for registering API endpoints to the Axon's FastAPI application router. This method allows the Axon server to @@ -445,33 +423,25 @@ def attach( and ensuring efficient and secure handling of requests within the Bittensor network. Args: - forward_fn (Callable): Function to be called when the API endpoint is accessed. - It should have at least one argument. - blacklist_fn (Callable, optional): Function to filter out undesired requests. It should take - the same arguments as 'forward_fn' and return a boolean - value. Defaults to None, meaning no blacklist filter will - be used. - priority_fn (Callable, optional): Function to rank requests based on their priority. It should - take the same arguments as 'forward_fn' and return a numerical - value representing the request's priority. Defaults to None, - meaning no priority sorting will be applied. - verify_fn (Callable, optional): Function to verify requests. It should take the same arguments as - 'forward_fn' and return a boolean value. If None, - 'self.default_verify' function will be used. - - Note: 'forward_fn', 'blacklist_fn', 'priority_fn', and 'verify_fn' should be designed to receive the same parameters. + forward_fn (Callable): Function to be called when the API endpoint is accessed. It should have at least one argument. + blacklist_fn (Callable, optional): Function to filter out undesired requests. It should take the same arguments as :func:`forward_fn` and return a boolean value. Defaults to ``None``, meaning no blacklist filter will be used. + priority_fn (Callable, optional): Function to rank requests based on their priority. It should take the same arguments as :func:`forward_fn` and return a numerical value representing the request's priority. Defaults to ``None``, meaning no priority sorting will be applied. + verify_fn (Callable, optional): Function to verify requests. It should take the same arguments as :func:`forward_fn` and return a boolean value. If ``None``, :func:`self.default_verify` function will be used. + + Note: + The methods :func:`forward_fn`, :func:`blacklist_fn`, :func:`priority_fn`, and :func:`verify_fn` should be designed to receive the same parameters. Raises: - AssertionError: If 'forward_fn' does not have the signature: forward( synapse: YourSynapse ) -> synapse: - AssertionError: If 'blacklist_fn' does not have the signature: blacklist( synapse: YourSynapse ) -> bool - AssertionError: If 'priority_fn' does not have the signature: priority( synapse: YourSynapse ) -> float - AssertionError: If 'verify_fn' does not have the signature: verify( synapse: YourSynapse ) -> None + AssertionError: If :func:`forward_fn` does not have the signature: ``forward( synapse: YourSynapse ) -> synapse``. + AssertionError: If :func:`blacklist_fn` does not have the signature: ``blacklist( synapse: YourSynapse ) -> bool``. + AssertionError: If :func:`priority_fn` does not have the signature: ``priority( synapse: YourSynapse ) -> float``. + AssertionError: If :func:`verify_fn` does not have the signature: ``verify( synapse: YourSynapse ) -> None``. Returns: self: Returns the instance of the AxonServer class for potential method chaining. - Example Usage: - ```python + Example Usage:: + def forward_custom(synapse: MyCustomSynapse) -> MyCustomSynapse: # Custom logic for processing the request return synapse @@ -488,10 +458,9 @@ def verify_custom(synapse: MyCustomSynapse): my_axon = bittensor.axon(...) my_axon.attach(forward_fn=forward_custom, verify_fn=verify_custom) - ``` Note: - The 'attach' method is fundamental in setting up the Axon server's request handling capabilities, + The :func:`attach` method is fundamental in setting up the Axon server's request handling capabilities, enabling it to participate effectively and securely in the Bittensor network. The flexibility offered by this method allows developers to tailor the Axon's behavior to specific requirements and use cases. @@ -607,7 +576,7 @@ def verify_custom(synapse: MyCustomSynapse): @classmethod def config(cls) -> "bittensor.config": """ - Parses command-line arguments to form a bittensor configuration object. + Parses the command-line arguments to form a Bittensor configuration object. Returns: bittensor.config: Configuration object with settings from command-line arguments. @@ -688,11 +657,11 @@ def add_args(cls, parser: argparse.ArgumentParser, prefix: str = None): async def verify_body_integrity(self, request: Request): """ - The verify_body_integrity method in the Bittensor framework is a key security function within the + The ``verify_body_integrity`` method in the Bittensor framework is a key security function within the Axon server's middleware. It is responsible for ensuring the integrity of the body of incoming HTTP requests. - Asynchronously verifies the integrity of the body of a request by comparing the hash of required fields + It asynchronously verifies the integrity of the body of a request by comparing the hash of required fields with the corresponding hashes provided in the request headers. This method is critical for ensuring that the incoming request payload has not been altered or tampered with during transmission, establishing a level of trust and security between the sender and receiver in the network. @@ -710,6 +679,7 @@ async def verify_body_integrity(self, request: Request): The response includes the detailed error message specifying which field has a hash mismatch. This method performs several key functions: + 1. Decoding and loading the request body for inspection. 2. Gathering required field names for hash comparison from the Axon configuration. 3. Loading and parsing the request body into a dictionary. @@ -799,7 +769,7 @@ def __del__(self): def start(self) -> "bittensor.axon": """ Starts the Axon server and its underlying FastAPI server thread, transitioning the state of the - Axon instance to 'started'. This method initiates the server's ability to accept and process + Axon instance to ``started``. This method initiates the server's ability to accept and process incoming network requests, making it an active participant in the Bittensor network. The start method triggers the FastAPI server associated with the Axon to begin listening for @@ -809,16 +779,14 @@ def start(self) -> "bittensor.axon": Returns: bittensor.axon: The Axon instance in the 'started' state. - Example: - ```python + Example:: + my_axon = bittensor.axon(...) ... # setup axon, attach functions, etc. my_axon.start() # Starts the axon server - ``` Note: - After invoking this method, the Axon is ready to handle requests as per its configured - endpoints and custom logic. + After invoking this method, the Axon is ready to handle requests as per its configured endpoints and custom logic. """ self.fast_server.start() self.started = True @@ -827,7 +795,7 @@ def start(self) -> "bittensor.axon": def stop(self) -> "bittensor.axon": """ Stops the Axon server and its underlying GRPC server thread, transitioning the state of the Axon - instance to 'stopped'. This method ceases the server's ability to accept new network requests, + instance to ``stopped``. This method ceases the server's ability to accept new network requests, effectively removing the neuron's server-side presence in the Bittensor network. By stopping the FastAPI server, the Axon ceases to listen for incoming requests, and any existing @@ -837,17 +805,16 @@ def stop(self) -> "bittensor.axon": Returns: bittensor.axon: The Axon instance in the 'stopped' state. - Example: - ```python + Example:: + my_axon = bittensor.axon(...) my_axon.start() ... my_axon.stop() # Stops the axon server - ``` + Note: - It is advisable to ensure that all ongoing processes or requests are completed or properly - handled before invoking this method. + It is advisable to ensure that all ongoing processes or requests are completed or properly handled before invoking this method. """ self.fast_server.stop() self.started = False @@ -858,28 +825,25 @@ def serve( ) -> "bittensor.axon": """ Serves the Axon on the specified subtensor connection using the configured wallet. This method - registers the Axon with a specific subnet within the Bittensor network, identified by the 'netuid'. + registers the Axon with a specific subnet within the Bittensor network, identified by the ``netuid``. It links the Axon to the broader network, allowing it to participate in the decentralized exchange of information. Args: - netuid (int): The unique identifier of the subnet to register on. This ID is essential for the - Axon to correctly position itself within the Bittensor network topology. - subtensor (bittensor.subtensor, optional): The subtensor connection to use for serving. If not - provided, a new connection is established based on default configurations. + netuid (int): The unique identifier of the subnet to register on. This ID is essential for the Axon to correctly position itself within the Bittensor network topology. + subtensor (bittensor.subtensor, optional): The subtensor connection to use for serving. If not provided, a new connection is established based on default configurations. Returns: bittensor.axon: The Axon instance that is now actively serving on the specified subtensor. - Example: - ```python + Example:: + my_axon = bittensor.axon(...) subtensor = bt.subtensor(network="local") # Local by default my_axon.serve(netuid=1, subtensor=subtensor) # Serves the axon on subnet with netuid 1 - ``` Note: - The 'serve' method is crucial for integrating the Axon into the Bittensor network, allowing it + The ``serve`` method is crucial for integrating the Axon into the Bittensor network, allowing it to start receiving and processing requests from other neurons. """ if subtensor == None: @@ -893,30 +857,34 @@ async def default_verify(self, synapse: bittensor.Synapse): It ensures that the message was not tampered with and was sent by the expected sender. - The `default_verify` method in the Bittensor framework is a critical security function within the + The :func:`default_verify` method in the Bittensor framework is a critical security function within the Axon server. It is designed to authenticate incoming messages by verifying their digital signatures. This verification ensures the integrity of the message and confirms that it was indeed sent by the claimed sender. The method plays a pivotal role in maintaining the trustworthiness and reliability of the communication within the Bittensor network. - Key Features: - Security Assurance: The default_verify method is crucial for ensuring the security of the - Bittensor network. By verifying digital signatures, it guards against unauthorized access + Key Features + Security Assurance + The default_verify method is crucial for ensuring the security of the Bittensor network. By verifying digital signatures, it guards against unauthorized access and data manipulation. - Preventing Replay Attacks: The method checks for increasing nonce values, which is a vital + Preventing Replay Attacks + The method checks for increasing nonce values, which is a vital step in preventing replay attacks. A replay attack involves an adversary reusing or delaying the transmission of a valid data transmission to deceive the receiver. - Authenticity and Integrity Checks: By verifying that the message's digital signature matches + Authenticity and Integrity Checks + By verifying that the message's digital signature matches its content, the method ensures the message's authenticity (it comes from the claimed sender) and integrity (it hasn't been altered during transmission). - Trust in Communication: This method fosters trust in the network communication. Neurons + Trust in Communication + This method fosters trust in the network communication. Neurons (nodes in the Bittensor network) can confidently interact, knowing that the messages they receive are genuine and have not been tampered with. - Cryptographic Techniques: The method's reliance on asymmetric encryption techniques is a + Cryptographic Techniques + The method's reliance on asymmetric encryption techniques is a cornerstone of modern cryptographic security, ensuring that only entities with the correct cryptographic keys can participate in secure communication. @@ -925,7 +893,7 @@ async def default_verify(self, synapse: bittensor.Synapse): bittensor request synapse. Raises: - Exception: If the receiver_hotkey doesn't match with self.receiver_hotkey. + Exception: If the ``receiver_hotkey`` doesn't match with ``self.receiver_hotkey``. Exception: If the nonce is not larger than the previous nonce for the same endpoint key. Exception: If the signature verification fails. @@ -994,8 +962,9 @@ def log_and_handle_error( class AxonMiddleware(BaseHTTPMiddleware): """ - The `AxonMiddleware` class is a key component in the Axon server, responsible for processing all - incoming requests. It handles the essential tasks of verifying requests, executing blacklist checks, + The `AxonMiddleware` class is a key component in the Axon server, responsible for processing all incoming requests. + + It handles the essential tasks of verifying requests, executing blacklist checks, running priority functions, and managing the logging of messages and errors. Additionally, the class is responsible for updating the headers of the response and executing the requested functions. @@ -1033,13 +1002,13 @@ async def dispatch( Args: request (Request): The incoming HTTP request to be processed. - call_next (RequestResponseEndpoint): A callable that processes the request and returns a - response. + call_next (RequestResponseEndpoint): A callable that processes the request and returns a response. Returns: Response: The HTTP response generated after processing the request. This method performs several key functions: + 1. Request Preprocessing: Sets up Synapse object from request headers and fills necessary information. 2. Logging: Logs the start of request processing. 3. Blacklist Checking: Verifies if the request is blacklisted. @@ -1151,6 +1120,7 @@ async def preprocess(self, request: Request) -> bittensor.Synapse: bittensor.Synapse: The Synapse object representing the preprocessed state of the request. The preprocessing involves: + 1. Extracting the request name from the URL path. 2. Creating a Synapse instance from the request headers using the appropriate class type. 3. Filling in the Axon and Dendrite information into the Synapse object. @@ -1218,6 +1188,7 @@ async def verify(self, synapse: bittensor.Synapse): Exception: If the verification process fails due to unmet criteria or security concerns. The verification process involves: + 1. Retrieving the specific verification function for the request's Synapse type. 2. Executing the verification function and handling any exceptions that arise. @@ -1265,6 +1236,7 @@ async def blacklist(self, synapse: bittensor.Synapse): Exception: If the request is found in the blacklist. The blacklist check involves: + 1. Retrieving the blacklist checking function for the request's Synapse type. 2. Executing the check and handling the case where the request is blacklisted. diff --git a/bittensor/commands/delegates.py b/bittensor/commands/delegates.py index 9d87cbff58..e96a43963b 100644 --- a/bittensor/commands/delegates.py +++ b/bittensor/commands/delegates.py @@ -54,24 +54,20 @@ def show_delegates( width: Optional[int] = None, ): """ - Displays a formatted table of Bittensor network delegates with detailed statistics - to the console. The table is sorted by total stake in descending order and provides - a snapshot of delegate performance and status, helping users make informed decisions - for staking or nominating. - - This is a helper function that is called by the 'list_delegates' and 'my_delegates' - and not intended to be used directly in user code unless specifically required. - - Parameters: - - delegates (List[bittensor.DelegateInfo]): A list of delegate information objects - to be displayed. - - prev_delegates (Optional[List[bittensor.DelegateInfo]]): A list of delegate - information objects from a previous state, used to calculate changes in stake. - Defaults to None. - - width (Optional[int]): The width of the console output table. Defaults to None, - which will make the table expand to the maximum width of the console. + Displays a formatted table of Bittensor network delegates with detailed statistics to the console. + + The table is sorted by total stake in descending order and provides + a snapshot of delegate performance and status, helping users make informed decisions for staking or nominating. + + This is a helper function that is called by the :func:`list_delegates` and :func:`my_delegates`, and is not intended to be used directly in user code unless specifically required. + + Args: + - delegates (List[bittensor.DelegateInfo]): A list of delegate information objects to be displayed. + - prev_delegates (Optional[List[bittensor.DelegateInfo]]): A list of delegate information objects from a previous state, used to calculate changes in stake. Defaults to ``None``. + - width (Optional[int]): The width of the console output table. Defaults to ``None``, which will make the table expand to the maximum width of the console. The output table includes the following columns: + - INDEX: The numerical index of the delegate. - DELEGATE: The name of the delegate. - SS58: The truncated SS58 address of the delegate. @@ -86,16 +82,17 @@ def show_delegates( - Desc: A brief description provided by the delegate. Usage: - This function is typically used within the Bittensor CLI to show current delegate - options to users who are considering where to stake their tokens. + This function is typically used within the Bittensor CLI to show current delegate + options to users who are considering where to stake their tokens. + + Example usage:: - Example usage: - >>> show_delegates(current_delegates, previous_delegates, width=80) + show_delegates(current_delegates, previous_delegates, width=80) Note: - This function is primarily for display purposes within a command-line interface and does - not return any values. It relies on the 'rich' Python library to render the table in the - console. + This function is primarily for display purposes within a command-line interface and does + not return any values. It relies on the `rich `_ Python library to render the table in the + console. """ delegates.sort(key=lambda delegate: delegate.total_stake, reverse=True) @@ -217,33 +214,28 @@ def show_delegates( class DelegateStakeCommand: """ - Executes the 'delegate' command, which stakes Tao to a specified delegate on the - Bittensor network. This action allocates the user's Tao to support a delegate, - potentially earning staking rewards in return. + Executes the ``delegate`` command, which stakes Tao to a specified delegate on the Bittensor network. + + This action allocates the user's Tao to support a delegate, potentially earning staking rewards in return. Optional Arguments: - - wallet.name: The name of the wallet to use for the command. - - delegate_ss58key: The SS58 address of the delegate to stake to. - - amount: The amount of Tao to stake. - - all: If specified, the command stakes all available Tao. + - ``wallet.name``: The name of the wallet to use for the command. + - ``delegate_ss58key``: The ``SS58`` address of the delegate to stake to. + - ``amount``: The amount of Tao to stake. + - ``all``: If specified, the command stakes all available Tao. - The command interacts with the user to determine the delegate and the amount of Tao - to be staked. If the '--all' flag is used, it delegates the entire available balance. + The command interacts with the user to determine the delegate and the amount of Tao to be staked. If the ``--all`` flag is used, it delegates the entire available balance. Usage: - The user must specify the delegate's SS58 address and the amount of Tao to stake. The - function sends a transaction to the subtensor network to delegate the specified amount - to the chosen delegate. These values are prompted if not provided. + The user must specify the delegate's SS58 address and the amount of Tao to stake. The function sends a transaction to the subtensor network to delegate the specified amount to the chosen delegate. These values are prompted if not provided. + + Example usage:: - Example usage: - >>> btcli delegate --delegate_ss58key --amount - >>> btcli delegate --delegate_ss58key --all + btcli delegate --delegate_ss58key --amount + btcli delegate --delegate_ss58key --all Note: - This command modifies the blockchain state and may incur transaction fees. It requires - user confirmation and interaction, and is designed to be used within the Bittensor CLI - environment. The user should ensure the delegate's address and the amount to be staked - are correct before executing the command. + This command modifies the blockchain state and may incur transaction fees. It requires user confirmation and interaction, and is designed to be used within the Bittensor CLI environment. The user should ensure the delegate's address and the amount to be staked are correct before executing the command. """ @staticmethod @@ -351,34 +343,29 @@ def check_config(config: "bittensor.config"): class DelegateUnstakeCommand: """ - Executes the 'undelegate' command, allowing users to withdraw their staked Tao from - a delegate on the Bittensor network. This process is known as "undelegating" and it - reverses the delegation process, freeing up the staked tokens. + Executes the ``undelegate`` command, allowing users to withdraw their staked Tao from a delegate on the Bittensor network. + + This process is known as "undelegating" and it reverses the delegation process, freeing up the staked tokens. Optional Arguments: - - wallet.name: The name of the wallet to use for the command. - - delegate_ss58key: The SS58 address of the delegate to undelegate from. - - amount: The amount of Tao to undelegate. - - all: If specified, the command undelegates all staked Tao from the delegate. + - ``wallet.name``: The name of the wallet to use for the command. + - ``delegate_ss58key``: The ``SS58`` address of the delegate to undelegate from. + - ``amount``: The amount of Tao to undelegate. + - ``all``: If specified, the command undelegates all staked Tao from the delegate. - The command prompts the user for the amount of Tao to undelegate and the SS58 address - of the delegate from which to undelegate. If the '--all' flag is used, it will attempt - to undelegate the entire staked amount from the specified delegate. + The command prompts the user for the amount of Tao to undelegate and the ``SS58`` address of the delegate from which to undelegate. If the ``--all`` flag is used, it will attempt to undelegate the entire staked amount from the specified delegate. Usage: - The user must provide the delegate's SS58 address and the amount of Tao to undelegate. - The function will then send a transaction to the Bittensor network to process the - undelegation. + The user must provide the delegate's SS58 address and the amount of Tao to undelegate. The function will then send a transaction to the Bittensor network to process the undelegation. + + Example usage:: - Example usage: - >>> btcli undelegate --delegate_ss58key --amount - >>> btcli undelegate --delegate_ss58key --all + btcli undelegate --delegate_ss58key --amount + btcli undelegate --delegate_ss58key --all Note: - This command can result in a change to the blockchain state and may incur transaction - fees. It is interactive and requires confirmation from the user before proceeding. It - should be used with care as undelegating can affect the delegate's total stake and - potentially the user's staking rewards. + This command can result in a change to the blockchain state and may incur transaction fees. It is interactive and requires confirmation from the user before proceeding. It should be used with care as undelegating can affect the delegate's total stake and + potentially the user's staking rewards. """ @staticmethod @@ -491,15 +478,16 @@ def check_config(config: "bittensor.config"): class ListDelegatesCommand: """ - Displays a formatted table of Bittensor network delegates, providing a comprehensive - overview of delegate statistics and information. This table helps users make informed - decisions on which delegates to allocate their Tao stake. + Displays a formatted table of Bittensor network delegates, providing a comprehensive overview of delegate statistics and information. + + This table helps users make informed decisions on which delegates to allocate their Tao stake. Optional Arguments: - - wallet.name: The name of the wallet to use for the command. - - subtensor.network: The name of the network to use for the command. + - ``wallet.name``: The name of the wallet to use for the command. + - ``subtensor.network``: The name of the network to use for the command. The table columns include: + - INDEX: The delegate's index in the sorted list. - DELEGATE: The name of the delegate. - SS58: The delegate's unique SS58 address (truncated for display). @@ -513,18 +501,16 @@ class ListDelegatesCommand: - DELEGATE/(24h): The total earnings of the delegate in the last 24 hours. - DESCRIPTION: A brief description of the delegate's purpose and operations. - Sorting is done based on the 'TOTAL STAKE' column in descending order. Changes in stake - are highlighted: increases in green and decreases in red. Entries with no previous data - are marked with 'NA'. Each delegate's name is a hyperlink to their respective URL, if available. + Sorting is done based on the ``TOTAL STAKE`` column in descending order. Changes in stake are highlighted: increases in green and decreases in red. Entries with no previous data are marked with ``NA``. Each delegate's name is a hyperlink to their respective URL, if available. + + Example usage:: - Example usage: - >>> btcli root list_delegates - >>> btcli root list_delegates --wallet.name my_wallet - >>> btcli root list_delegates --subtensor.network finney # can also be `test` or `local` + btcli root list_delegates + btcli root list_delegates --wallet.name my_wallet + btcli root list_delegates --subtensor.network finney # can also be `test` or `local` Note: - This function is part of the Bittensor CLI tools and is intended for use within a console - application. It prints directly to the console and does not return any value. + This function is part of the Bittensor CLI tools and is intended for use within a console application. It prints directly to the console and does not return any value. """ @staticmethod @@ -581,33 +567,31 @@ def check_config(config: "bittensor.config"): class NominateCommand: """ - Executes the 'nominate' command, which facilitates a wallet to become a delegate - on the Bittensor network. This command handles the nomination process, including - wallet unlocking and verification of the hotkey's current delegate status. + Executes the ``nominate`` command, which facilitates a wallet to become a delegate on the Bittensor network. + + This command handles the nomination process, including wallet unlocking and verification of the hotkey's current delegate status. The command performs several checks: + - Verifies that the hotkey is not already a delegate to prevent redundant nominations. - Tries to nominate the wallet and reports success or failure. Upon success, the wallet's hotkey is registered as a delegate on the network. Optional Arguments: - - wallet.name: The name of the wallet to use for the command. - - wallet.hotkey: The name of the hotkey to use for the command. + - ``wallet.name``: The name of the wallet to use for the command. + - ``wallet.hotkey``: The name of the hotkey to use for the command. Usage: - To run the command, the user must have a configured wallet with both hotkey and - coldkey. If the wallet is not already nominated, this command will initiate the - process. + To run the command, the user must have a configured wallet with both hotkey and coldkey. If the wallet is not already nominated, this command will initiate the process. - Example usage: - >>> btcli root nominate - >>> btcli root nominate --wallet.name my_wallet --wallet.hotkey my_hotkey + Example usage:: + + btcli root nominate + btcli root nominate --wallet.name my_wallet --wallet.hotkey my_hotkey Note: - This function is intended to be used as a CLI command. It prints the outcome directly - to the console and does not return any value. It should not be called programmatically - in user code due to its interactive nature and side effects on the network state. + This function is intended to be used as a CLI command. It prints the outcome directly to the console and does not return any value. It should not be called programmatically in user code due to its interactive nature and side effects on the network state. """ @staticmethod @@ -685,16 +669,17 @@ def check_config(config: "bittensor.config"): class MyDelegatesCommand: """ - Executes the 'my_delegates' command within the Bittensor CLI, which retrieves and - displays a table of delegated stakes from a user's wallet(s) to various delegates - on the Bittensor network. The command provides detailed insights into the user's + Executes the ``my_delegates`` command within the Bittensor CLI, which retrieves and displays a table of delegated stakes from a user's wallet(s) to various delegates on the Bittensor network. + + The command provides detailed insights into the user's staking activities and the performance of their chosen delegates. Optional Arguments: - - wallet.name: The name of the wallet to use for the command. - - all: If specified, the command aggregates information across all wallets. + - ``wallet.name``: The name of the wallet to use for the command. + - ``all``: If specified, the command aggregates information across all wallets. The table output includes the following columns: + - Wallet: The name of the user's wallet. - OWNER: The name of the delegate's owner. - SS58: The truncated SS58 address of the delegate. @@ -711,18 +696,16 @@ class MyDelegatesCommand: The command also sums and prints the total amount of Tao delegated across all wallets. Usage: - The command can be run as part of the Bittensor CLI suite of tools and requires - no parameters if a single wallet is used. If multiple wallets are present, the - --all flag can be specified to aggregate information across all wallets. + The command can be run as part of the Bittensor CLI suite of tools and requires no parameters if a single wallet is used. If multiple wallets are present, the ``--all`` flag can be specified to aggregate information across all wallets. + + Example usage:: - Example usage: - >>> btcli my_delegates - >>> btcli my_delegates --all - >>> btcli my_delegates --wallet.name my_wallet + btcli my_delegates + btcli my_delegates --all + btcli my_delegates --wallet.name my_wallet Note: - This function is typically called by the CLI parser and is not intended to be used - directly in user code. + This function is typically called by the CLI parser and is not intended to be used directly in user code. """ @staticmethod diff --git a/bittensor/commands/identity.py b/bittensor/commands/identity.py index 0e90f8476e..2e71bf406b 100644 --- a/bittensor/commands/identity.py +++ b/bittensor/commands/identity.py @@ -9,21 +9,22 @@ class SetIdentityCommand: """ - Executes the 'set_identity' command within the Bittensor network, which allows for the - creation or update of a delegate's on-chain identity. This identity includes various + Executes the :func:`set_identity` command within the Bittensor network, which allows for the creation or update of a delegate's on-chain identity. + + This identity includes various attributes such as display name, legal name, web URL, PGP fingerprint, and contact information, among others. Optional Arguments: - --display: The display name for the identity. - --legal: The legal name for the identity. - --web: The web URL for the identity. - --riot: The riot handle for the identity. - --email: The email address for the identity. - --pgp_fingerprint: The PGP fingerprint for the identity. - --image: The image URL for the identity. - --info: The info for the identity. - --twitter: The twitter URL for the identity. + - ``display``: The display name for the identity. + - ``legal``: The legal name for the identity. + - ``web``: The web URL for the identity. + - ``riot``: The riot handle for the identity. + - ``email``: The email address for the identity. + - ``pgp_fingerprint``: The PGP fingerprint for the identity. + - ``image``: The image URL for the identity. + - ``info``: The info for the identity. + - ``twitter``: The X (twitter) URL for the identity. The command prompts the user for the different identity attributes and validates the input size for each attribute. It provides an option to update an existing validator @@ -33,25 +34,26 @@ class SetIdentityCommand: Each field has a maximum size of 64 bytes. The PGP fingerprint field is an exception and has a maximum size of 20 bytes. The user is prompted to enter the PGP fingerprint as a hex string, which is then converted to bytes. The user is also prompted to enter - the coldkey or hotkey ss58 address for the identity to be updated. If the user does + the coldkey or hotkey ``ss58`` address for the identity to be updated. If the user does not have a hotkey, the coldkey address is used by default. If setting a validator identity, the hotkey will be used by default. If the user is setting an identity for a subnet, the coldkey will be used by default. Usage: - The user should call this command from the command line and follow the interactive - prompts to enter or update the identity information. The command will display the - updated identity details in a table format upon successful execution. + The user should call this command from the command line and follow the interactive + prompts to enter or update the identity information. The command will display the + updated identity details in a table format upon successful execution. + + Example usage:: - Example usage: - >>> btcli root set_identity + btcli wallet set_identity Note: - This command should only be used if the user is willing to incur the 1 TAO transaction - fee associated with setting an identity on the blockchain. It is a high-level command - that makes changes to the blockchain state and should not be used programmatically as - part of other scripts or applications. + This command should only be used if the user is willing to incur the 1 TAO transaction + fee associated with setting an identity on the blockchain. It is a high-level command + that makes changes to the blockchain state and should not be used programmatically as + part of other scripts or applications. """ def run(cli: "bittensor.cli"): @@ -240,33 +242,35 @@ def add_args(parser: argparse.ArgumentParser): class GetIdentityCommand: """ - Executes the 'get_identity' command, which retrieves and displays the identity details - of a user's coldkey or hotkey associated with the Bittensor network. This function + Executes the :func:`get_identity` command, which retrieves and displays the identity details of a user's coldkey or hotkey associated with the Bittensor network. This function queries the subtensor chain for information such as the stake, rank, and trust associated with the provided key. Optional Arguments: - --key: The ss58 address of the coldkey or hotkey to query. + - ``key``: The ``ss58`` address of the coldkey or hotkey to query. The command performs the following actions: + - Connects to the subtensor network and retrieves the identity information. - Displays the information in a structured table format. The displayed table includes: - - Address: The ss58 address of the queried key. - - Item: Various attributes of the identity such as stake, rank, and trust. - - Value: The corresponding values of the attributes. + + - **Address**: The ``ss58`` address of the queried key. + - **Item**: Various attributes of the identity such as stake, rank, and trust. + - **Value**: The corresponding values of the attributes. Usage: - The user must provide an ss58 address as input to the command. If the address is not - provided in the configuration, the user is prompted to enter one. + The user must provide an ``ss58`` address as input to the command. If the address is not + provided in the configuration, the user is prompted to enter one. + + Example usage:: - Example usage: - >>> btli get_identity --key + btcli wallet get_identity --key Note: - This function is designed for CLI use and should be executed in a terminal. It is - primarily used for informational purposes and has no side effects on the network state. + This function is designed for CLI use and should be executed in a terminal. It is + primarily used for informational purposes and has no side effects on the network state. """ def run(cli: "bittensor.cli"): diff --git a/bittensor/commands/inspect.py b/bittensor/commands/inspect.py index 4db3f64702..bdf2a00e26 100644 --- a/bittensor/commands/inspect.py +++ b/bittensor/commands/inspect.py @@ -73,41 +73,44 @@ def _get_hotkey_wallets_for_wallet(wallet) -> List["bittensor.wallet"]: class InspectCommand: """ - Executes the 'inspect' command, which compiles and displays a detailed report of a user's - wallet pairs (coldkey, hotkey) on the Bittensor network. This report includes balance and + Executes the ``inspect`` command, which compiles and displays a detailed report of a user's wallet pairs (coldkey, hotkey) on the Bittensor network. + + This report includes balance and staking information for both the coldkey and hotkey associated with the wallet. Optional arguments: - -all: If set to True, the command will inspect all wallets located within the specified - path. If set to False, the command will inspect only the wallet specified by the user. + - ``all``: If set to ``True``, the command will inspect all wallets located within the specified path. If set to ``False``, the command will inspect only the wallet specified by the user. The command gathers data on: + - Coldkey balance and delegated stakes. - Hotkey stake and emissions per neuron on the network. - Delegate names and details fetched from the network. The resulting table includes columns for: - - Coldkey: The coldkey associated with the user's wallet. - - Balance: The balance of the coldkey. - - Delegate: The name of the delegate to which the coldkey has staked funds. - - Stake: The amount of stake held by both the coldkey and hotkey. - - Emission: The emission or rewards earned from staking. - - Netuid: The network unique identifier of the subnet where the hotkey is active. - - Hotkey: The hotkey associated with the neuron on the network. + + - **Coldkey**: The coldkey associated with the user's wallet. + - **Balance**: The balance of the coldkey. + - **Delegate**: The name of the delegate to which the coldkey has staked funds. + - **Stake**: The amount of stake held by both the coldkey and hotkey. + - **Emission**: The emission or rewards earned from staking. + - **Netuid**: The network unique identifier of the subnet where the hotkey is active. + - **Hotkey**: The hotkey associated with the neuron on the network. Usage: - This command can be used to inspect a single wallet or all wallets located within a - specified path. It is useful for a comprehensive overview of a user's participation - and performance in the Bittensor network. + This command can be used to inspect a single wallet or all wallets located within a + specified path. It is useful for a comprehensive overview of a user's participation + and performance in the Bittensor network. + + Example usage:: - Example usage: - >>> btcli inspect - >>> btcli inspect --all + btcli wallet inspect + btcli wallet inspect --all Note: - The 'inspect' command is for displaying information only and does not perform any - transactions or state changes on the Bittensor network. It is intended to be used as - part of the Bittensor CLI and not as a standalone function within user code. + The ``inspect`` command is for displaying information only and does not perform any + transactions or state changes on the Bittensor network. It is intended to be used as + part of the Bittensor CLI and not as a standalone function within user code. """ @staticmethod diff --git a/bittensor/commands/list.py b/bittensor/commands/list.py index 1625d56375..6079112ed1 100644 --- a/bittensor/commands/list.py +++ b/bittensor/commands/list.py @@ -26,28 +26,26 @@ class ListCommand: """ - Executes the 'list' command which enumerates all wallets and their respective hotkeys - present in the user's Bittensor configuration directory. The command organizes the - information in a tree structure, displaying each wallet along with the SS58 addresses - for the coldkey public key and any hotkeys associated with it. + Executes the ``list`` command which enumerates all wallets and their respective hotkeys present in the user's Bittensor configuration directory. + + The command organizes the information in a tree structure, displaying each wallet along with the ``ss58`` addresses for the coldkey public key and any hotkeys associated with it. Optional arguments: - -p, --path: The path to the Bittensor configuration directory. Defaults to '~/.bittensor'. + - ``-p``, ``--path``: The path to the Bittensor configuration directory. Defaults to '~/.bittensor'. The output is presented in a hierarchical tree format, with each wallet as a root node, - and any associated hotkeys as child nodes. The SS58 address is displayed for each + and any associated hotkeys as child nodes. The ``ss58`` address is displayed for each coldkey and hotkey that is not encrypted and exists on the device. Usage: - Upon invocation, the command scans the wallet directory and prints a list of all wallets, - indicating whether the public keys are available ('?' denotes unavailable or encrypted keys). + Upon invocation, the command scans the wallet directory and prints a list of all wallets, indicating whether the public keys are available (``?`` denotes unavailable or encrypted keys). + + Example usage:: - Example usage: - >>> btcli list --path ~/.bittensor + btcli wallet list --path ~/.bittensor Note: - This command is read-only and does not modify the filesystem or the network state. It is - intended for use within the Bittensor CLI to provide a quick overview of the user's wallets. + This command is read-only and does not modify the filesystem or the network state. It is intended for use within the Bittensor CLI to provide a quick overview of the user's wallets. """ @staticmethod diff --git a/bittensor/commands/metagraph.py b/bittensor/commands/metagraph.py index 661b4dd3d9..d837e19028 100644 --- a/bittensor/commands/metagraph.py +++ b/bittensor/commands/metagraph.py @@ -26,16 +26,18 @@ class MetagraphCommand: """ - Executes the 'metagraph' command to retrieve and display the entire metagraph - for a specified network. This metagraph contains detailed information about + Executes the ``metagraph`` command to retrieve and display the entire metagraph for a specified network. + + This metagraph contains detailed information about all the neurons (nodes) participating in the network, including their stakes, trust scores, and more. Optional arguments: - --netuid: The netuid of the network to query. Defaults to the default network UID. - --subtensor.network: The name of the network to query. Defaults to the default network name. + - ``--netuid``: The netuid of the network to query. Defaults to the default network UID. + - ``--subtensor.network``: The name of the network to query. Defaults to the default network name. The table displayed includes the following columns for each neuron: + - UID: Unique identifier of the neuron. - STAKE(τ): Total stake of the neuron in Tau (τ). - RANK: Rank score of the neuron. @@ -52,21 +54,20 @@ class MetagraphCommand: - HOTKEY: Partial hotkey (public key) of the neuron. - COLDKEY: Partial coldkey (public key) of the neuron. - The command also prints network-wide statistics such as total stake, issuance, - and difficulty. + The command also prints network-wide statistics such as total stake, issuance, and difficulty. Usage: - The user must specify the network UID to query the metagraph. If not specified, - the default network UID is used. + The user must specify the network UID to query the metagraph. If not specified, the default network UID is used. + + Example usage:: - Example usage: - >>> btcli metagraph --netuid 0 # Root network - >>> btcli metagraph --netuid 1 --subtensor.network test + btcli subnet metagraph --netuid 0 # Root network + btcli subnet metagraph --netuid 1 --subtensor.network test Note: - This command provides a snapshot of the network's state at the time of calling. - It is useful for network analysis and diagnostics. It is intended to be used as - part of the Bittensor CLI and not as a standalone function within user code. + This command provides a snapshot of the network's state at the time of calling. + It is useful for network analysis and diagnostics. It is intended to be used as + part of the Bittensor CLI and not as a standalone function within user code. """ @staticmethod diff --git a/bittensor/commands/misc.py b/bittensor/commands/misc.py index 87c81a9fcb..ded0a6c06b 100644 --- a/bittensor/commands/misc.py +++ b/bittensor/commands/misc.py @@ -28,22 +28,26 @@ class UpdateCommand: """ - Executes the 'update' command to update the local Bittensor package. This command performs a series of operations to ensure that the user's local Bittensor installation is updated to the latest version from the master branch of its GitHub repository. It primarily involves pulling the latest changes from the repository and reinstalling the package. + Executes the ``update`` command to update the local Bittensor package. + + This command performs a series of operations to ensure that the user's local Bittensor installation is updated to the latest version from the master branch of its GitHub repository. It primarily involves pulling the latest changes from the repository and reinstalling the package. Usage: - Upon invocation, the command first checks the user's configuration for the 'no_prompt' setting. If 'no_prompt' is set to True, or if the user explicitly confirms with 'Y' when prompted, the command proceeds to update the local Bittensor package. It changes the current directory to the Bittensor package directory, checks out the master branch of the Bittensor repository, pulls the latest changes, and then reinstalls the package using pip. + Upon invocation, the command first checks the user's configuration for the ``no_prompt`` setting. If ``no_prompt`` is set to ``True``, or if the user explicitly confirms with ``Y`` when prompted, the command proceeds to update the local Bittensor package. It changes the current directory to the Bittensor package directory, checks out the master branch of the Bittensor repository, pulls the latest changes, and then reinstalls the package using ``pip``. The command structure is as follows: + 1. Change directory to the Bittensor package directory. 2. Check out the master branch of the Bittensor GitHub repository. - 3. Pull the latest changes with the '--ff-only' option to ensure a fast-forward update. + 3. Pull the latest changes with the ``--ff-only`` option to ensure a fast-forward update. 4. Reinstall the Bittensor package using pip. - Example usage: - >>> btcli legacy update + Example usage:: + + btcli legacy update Note: - This command is intended to be used within the Bittensor CLI to facilitate easy updates of the Bittensor package. It should be used with caution as it directly affects the local installation of the package. It is recommended to ensure that any important data or configurations are backed up before running this command. + This command is intended to be used within the Bittensor CLI to facilitate easy updates of the Bittensor package. It should be used with caution as it directly affects the local installation of the package. It is recommended to ensure that any important data or configurations are backed up before running this command. """ @staticmethod diff --git a/bittensor/commands/network.py b/bittensor/commands/network.py index 2a3deb9225..d88f1def50 100644 --- a/bittensor/commands/network.py +++ b/bittensor/commands/network.py @@ -29,28 +29,33 @@ class RegisterSubnetworkCommand: """ - Executes the 'register_subnetwork' command to register a new subnetwork on the Bittensor network. This command facilitates the creation and registration of a subnetwork, which involves interaction with the user's wallet and the Bittensor subtensor. It ensures that the user has the necessary credentials and configurations to successfully register a new subnetwork. + Executes the ``register_subnetwork`` command to register a new subnetwork on the Bittensor network. + + This command facilitates the creation and registration of a subnetwork, which involves interaction with the user's wallet and the Bittensor subtensor. It ensures that the user has the necessary credentials and configurations to successfully register a new subnetwork. Usage: - Upon invocation, the command performs several key steps to register a subnetwork: - 1. It copies the user's current configuration settings. - 2. It accesses the user's wallet using the provided configuration. - 3. It initializes the Bittensor subtensor object with the user's configuration. - 4. It then calls the `register_subnetwork` function of the subtensor object, passing the user's wallet and a prompt setting based on the user's configuration. + Upon invocation, the command performs several key steps to register a subnetwork: + + 1. It copies the user's current configuration settings. + 2. It accesses the user's wallet using the provided configuration. + 3. It initializes the Bittensor subtensor object with the user's configuration. + 4. It then calls the ``register_subnetwork`` function of the subtensor object, passing the user's wallet and a prompt setting based on the user's configuration. - If the user's configuration does not specify a wallet name and 'no_prompt' is not set, the command will prompt the user to enter a wallet name. This name is then used in the registration process. + If the user's configuration does not specify a wallet name and ``no_prompt`` is not set, the command will prompt the user to enter a wallet name. This name is then used in the registration process. The command structure includes: + - Copying the user's configuration. - Accessing and preparing the user's wallet. - Initializing the Bittensor subtensor. - Registering the subnetwork with the necessary credentials. - Example usage: - >>> btcli subnets create + Example usage:: + + btcli subnets create Note: - This command is intended for advanced users of the Bittensor network who wish to contribute by adding new subnetworks. It requires a clear understanding of the network's functioning and the roles of subnetworks. Users should ensure that they have secured their wallet and are aware of the implications of adding a new subnetwork to the Bittensor ecosystem. + This command is intended for advanced users of the Bittensor network who wish to contribute by adding new subnetworks. It requires a clear understanding of the network's functioning and the roles of subnetworks. Users should ensure that they have secured their wallet and are aware of the implications of adding a new subnetwork to the Bittensor ecosystem. """ @staticmethod @@ -96,29 +101,34 @@ def add_args(cls, parser: argparse.ArgumentParser): class SubnetLockCostCommand: """ - Executes the 'lock_cost' command to view the locking cost required for creating a new subnetwork on the Bittensor network. This command is designed to provide users with the current cost of registering a new subnetwork, which is a critical piece of information for anyone considering expanding the network's infrastructure. + Executes the ``lock_cost`` command to view the locking cost required for creating a new subnetwork on the Bittensor network. + + This command is designed to provide users with the current cost of registering a new subnetwork, which is a critical piece of information for anyone considering expanding the network's infrastructure. The current implementation anneals the cost of creating a subnet over a period of two days. If the cost is unappealing currently, check back in a day or two to see if it has reached an amenble level. Usage: - Upon invocation, the command performs the following operations: - 1. It copies the user's current Bittensor configuration. - 2. It initializes the Bittensor subtensor object with this configuration. - 3. It then retrieves the subnet lock cost using the `get_subnet_burn_cost()` method from the subtensor object. - 4. The cost is displayed to the user in a readable format, indicating the amount of Tao required to lock for registering a new subnetwork. + Upon invocation, the command performs the following operations: + + 1. It copies the user's current Bittensor configuration. + 2. It initializes the Bittensor subtensor object with this configuration. + 3. It then retrieves the subnet lock cost using the ``get_subnet_burn_cost()`` method from the subtensor object. + 4. The cost is displayed to the user in a readable format, indicating the amount of Tao required to lock for registering a new subnetwork. In case of any errors during the process (e.g., network issues, configuration problems), the command will catch these exceptions and inform the user that it failed to retrieve the lock cost, along with the specific error encountered. The command structure includes: + - Copying and using the user's configuration for Bittensor. - Retrieving the current subnet lock cost from the Bittensor network. - Displaying the cost in a user-friendly manner. - Example usage: - >>> btcli subnets lock_cost + Example usage:: + + btcli subnets lock_cost Note: - This command is particularly useful for users who are planning to contribute to the Bittensor network by adding new subnetworks. Understanding the lock cost is essential for these users to make informed decisions about their potential contributions and investments in the network. + This command is particularly useful for users who are planning to contribute to the Bittensor network by adding new subnetworks. Understanding the lock cost is essential for these users to make informed decisions about their potential contributions and investments in the network. """ @staticmethod @@ -165,35 +175,37 @@ def add_args(cls, parser: argparse.ArgumentParser): class SubnetListCommand: """ - Executes the 'list' command to list all subnets and their detailed information on the Bittensor network. + Executes the ``list`` command to list all subnets and their detailed information on the Bittensor network. + This command is designed to provide users with comprehensive information about each subnet within the network, including its unique identifier (netuid), the number of neurons, maximum neuron capacity, emission rate, tempo, recycle register cost (burn), proof of work (PoW) difficulty, and the name or SS58 address of the subnet owner. Usage: - Upon invocation, the command performs the following actions: - 1. It initializes the Bittensor subtensor object with the user's configuration. - 2. It retrieves a list of all subnets in the network along with their detailed information. - 3. The command compiles this data into a table format, displaying key information about each subnet. + Upon invocation, the command performs the following actions: + + 1. It initializes the Bittensor subtensor object with the user's configuration. + 2. It retrieves a list of all subnets in the network along with their detailed information. + 3. The command compiles this data into a table format, displaying key information about each subnet. In addition to the basic subnet details, the command also fetches delegate information to provide the - name of the subnet owner where available. If the owner's name is not available, the owner's SS58 + name of the subnet owner where available. If the owner's name is not available, the owner's ``SS58`` address is displayed. The command structure includes: + - Initializing the Bittensor subtensor and retrieving subnet information. - Calculating the total number of neurons across all subnets. - - Constructing a table that includes columns for NETUID, N (current neurons), MAX_N (maximum neurons), - EMISSION, TEMPO, BURN, POW (proof of work difficulty), and SUDO (owner's name or SS58 address). + - Constructing a table that includes columns for ``NETUID``, ``N`` (current neurons), ``MAX_N`` (maximum neurons), ``EMISSION``, ``TEMPO``, ``BURN``, ``POW`` (proof of work difficulty), and ``SUDO`` (owner's name or ``SS58`` address). - Displaying the table with a footer that summarizes the total number of subnets and neurons. - Example usage: - >>> btcli subnets list + Example usage:: + + btcli subnets list Note: - This command is particularly useful for users seeking an overview of the Bittensor network's structure - and the distribution of its resources and ownership information for each subnet. + This command is particularly useful for users seeking an overview of the Bittensor network's structure and the distribution of its resources and ownership information for each subnet. """ @staticmethod @@ -280,33 +292,41 @@ def add_args(parser: argparse.ArgumentParser): HYPERPARAMS = { "serving_rate_limit": "sudo_set_serving_rate_limit", + "min_difficulty": "sudo_set_min_difficulty", + "max_difficulty": "sudo_set_max_difficulty", "weights_version": "sudo_set_weights_version_key", "weights_rate_limit": "sudo_set_weights_set_rate_limit", "max_weight_limit": "sudo_set_max_weight_limit", "immunity_period": "sudo_set_immunity_period", "min_allowed_weights": "sudo_set_min_allowed_weights", "activity_cutoff": "sudo_set_activity_cutoff", + "network_registration_allowed": "sudo_set_network_registration_allowed", + "network_pow_registration_allowed": "sudo_set_network_pow_registration_allowed", + "min_burn": "sudo_set_min_burn", + "max_burn": "sudo_set_max_burn", } class SubnetSudoCommand: """ - Executes the 'set' command to set hyperparameters for a specific subnet on the Bittensor network. + Executes the ``set`` command to set hyperparameters for a specific subnet on the Bittensor network. + This command allows subnet owners to modify various hyperparameters of theirs subnet, such as its tempo, emission rates, and other network-specific settings. Usage: - The command first prompts the user to enter the hyperparameter they wish to change and its new value. - It then uses the user's wallet and configuration settings to authenticate and send the hyperparameter update - to the specified subnet. + The command first prompts the user to enter the hyperparameter they wish to change and its new value. + It then uses the user's wallet and configuration settings to authenticate and send the hyperparameter update + to the specified subnet. - Example usage: - >>> btcli sudo set --netuid 1 --param 'tempo' --value '0.5' + Example usage:: + + btcli sudo set --netuid 1 --param 'tempo' --value '0.5' Note: - This command requires the user to specify the subnet identifier (netuid) and both the hyperparameter - and its new value. It is intended for advanced users who are familiar with the network's functioning - and the impact of changing these parameters. + This command requires the user to specify the subnet identifier (``netuid``) and both the hyperparameter + and its new value. It is intended for advanced users who are familiar with the network's functioning + and the impact of changing these parameters. """ @staticmethod @@ -338,6 +358,12 @@ def _run( value = Prompt.ask("Enter new value") cli.config.value = value + if ( + cli.config.param == "network_registration_allowed" + or cli.config.param == "network_pow_registration_allowed" + ): + cli.config.value = True if cli.config.value.lower() == "true" else False + subtensor.set_hyperparameter( wallet, netuid=cli.config.netuid, @@ -372,42 +398,44 @@ def add_args(parser: argparse.ArgumentParser): class SubnetHyperparamsCommand: """ - Executes the 'hyperparameters' command to view the current hyperparameters of a specific subnet on - the Bittensor network. This command is useful for users who wish to understand the configuration and + Executes the '``hyperparameters``' command to view the current hyperparameters of a specific subnet on the Bittensor network. + + This command is useful for users who wish to understand the configuration and operational parameters of a particular subnet. Usage: - Upon invocation, the command fetches and displays a list of all hyperparameters for the specified subnet. - These include settings like tempo, emission rates, and other critical network parameters that define - the subnet's behavior. - - Example usage: - >>> btcli subnets hyperparameters --netuid 1 - - Subnet Hyperparameters - NETUID: 1 - finney - HYPERPARAMETER VALUE - rho 10 - kappa 32767 - immunity_period 7200 - min_allowed_weights 8 - max_weight_limit 455 - tempo 99 - min_difficulty 1000000000000000000 - max_difficulty 1000000000000000000 - weights_version 2013 - weights_rate_limit 100 - adjustment_interval 112 - activity_cutoff 5000 - registration_allowed True - target_regs_per_interval 2 - min_burn 1000000000 - max_burn 100000000000 - bonds_moving_avg 900000 - max_regs_per_block 1 + Upon invocation, the command fetches and displays a list of all hyperparameters for the specified subnet. + These include settings like tempo, emission rates, and other critical network parameters that define + the subnet's behavior. + + Example usage:: + + $ btcli subnets hyperparameters --netuid 1 + + Subnet Hyperparameters - NETUID: 1 - finney + HYPERPARAMETER VALUE + rho 10 + kappa 32767 + immunity_period 7200 + min_allowed_weights 8 + max_weight_limit 455 + tempo 99 + min_difficulty 1000000000000000000 + max_difficulty 1000000000000000000 + weights_version 2013 + weights_rate_limit 100 + adjustment_interval 112 + activity_cutoff 5000 + registration_allowed True + target_regs_per_interval 2 + min_burn 1000000000 + max_burn 100000000000 + bonds_moving_avg 900000 + max_regs_per_block 1 Note: - The user must specify the subnet identifier (netuid) for which they want to view the hyperparameters. - This command is read-only and does not modify the network state or configurations. + The user must specify the subnet identifier (``netuid``) for which they want to view the hyperparameters. + This command is read-only and does not modify the network state or configurations. """ @staticmethod @@ -468,41 +496,43 @@ def add_args(parser: argparse.ArgumentParser): class SubnetGetHyperparamsCommand: """ - Executes the 'get' command to retrieve the hyperparameters of a specific subnet on the Bittensor network. - This command is similar to the 'hyperparameters' command but may be used in different contexts within the CLI. + Executes the ``get`` command to retrieve the hyperparameters of a specific subnet on the Bittensor network. + + This command is similar to the ``hyperparameters`` command but may be used in different contexts within the CLI. Usage: - The command connects to the Bittensor network, queries the specified subnet, and returns a detailed list - of all its hyperparameters. This includes crucial operational parameters that determine the subnet's - performance and interaction within the network. - - Example usage: - >>> btcli sudo get --netuid 1 - - Subnet Hyperparameters - NETUID: 1 - finney - HYPERPARAMETER VALUE - rho 10 - kappa 32767 - immunity_period 7200 - min_allowed_weights 8 - max_weight_limit 455 - tempo 99 - min_difficulty 1000000000000000000 - max_difficulty 1000000000000000000 - weights_version 2013 - weights_rate_limit 100 - adjustment_interval 112 - activity_cutoff 5000 - registration_allowed True - target_regs_per_interval 2 - min_burn 1000000000 - max_burn 100000000000 - bonds_moving_avg 900000 - max_regs_per_block 1 + The command connects to the Bittensor network, queries the specified subnet, and returns a detailed list + of all its hyperparameters. This includes crucial operational parameters that determine the subnet's + performance and interaction within the network. + + Example usage:: + + $ btcli sudo get --netuid 1 + + Subnet Hyperparameters - NETUID: 1 - finney + HYPERPARAMETER VALUE + rho 10 + kappa 32767 + immunity_period 7200 + min_allowed_weights 8 + max_weight_limit 455 + tempo 99 + min_difficulty 1000000000000000000 + max_difficulty 1000000000000000000 + weights_version 2013 + weights_rate_limit 100 + adjustment_interval 112 + activity_cutoff 5000 + registration_allowed True + target_regs_per_interval 2 + min_burn 1000000000 + max_burn 100000000000 + bonds_moving_avg 900000 + max_regs_per_block 1 Note: - Users need to provide the netuid of the subnet whose hyperparameters they wish to view. This command is - designed for informational purposes and does not alter any network settings or configurations. + Users need to provide the ``netuid`` of the subnet whose hyperparameters they wish to view. This command is + designed for informational purposes and does not alter any network settings or configurations. """ @staticmethod diff --git a/bittensor/commands/overview.py b/bittensor/commands/overview.py index c70ced5374..068c11f004 100644 --- a/bittensor/commands/overview.py +++ b/bittensor/commands/overview.py @@ -38,40 +38,43 @@ class OverviewCommand: """ - Executes the 'overview' command to present a detailed overview of the user's registered accounts on the Bittensor network. + Executes the ``overview`` command to present a detailed overview of the user's registered accounts on the Bittensor network. + This command compiles and displays comprehensive information about each neuron associated with the user's wallets, including both hotkeys and coldkeys. It is especially useful for users managing multiple accounts or seeking a summary of their network activities and stake distributions. Usage: - The command offers various options to customize the output. Users can filter the displayed data by specific netuids, - sort by different criteria, and choose to include all wallets in the user's configuration directory. The output is - presented in a tabular format with the following columns: - - COLDKEY: The SS58 address of the coldkey. - - HOTKEY: The SS58 address of the hotkey. - - UID: Unique identifier of the neuron. - - ACTIVE: Indicates if the neuron is active. - - STAKE(τ): Amount of stake in the neuron, in Tao. - - RANK: The rank of the neuron within the network. - - TRUST: Trust score of the neuron. - - CONSENSUS: Consensus score of the neuron. - - INCENTIVE: Incentive score of the neuron. - - DIVIDENDS: Dividends earned by the neuron. - - EMISSION(p): Emission received by the neuron, in Rho. - - VTRUST: Validator trust score of the neuron. - - VPERMIT: Indicates if the neuron has a validator permit. - - UPDATED: Time since last update. - - AXON: IP address and port of the neuron. - - HOTKEY_SS58: Human-readable representation of the hotkey. - - Example usage: - >>> btcli wallet overview - >>> btcli wallet overview --all --sort_by stake --sort_order descending + The command offers various options to customize the output. Users can filter the displayed data by specific netuids, + sort by different criteria, and choose to include all wallets in the user's configuration directory. The output is + presented in a tabular format with the following columns: + + - COLDKEY: The SS58 address of the coldkey. + - HOTKEY: The SS58 address of the hotkey. + - UID: Unique identifier of the neuron. + - ACTIVE: Indicates if the neuron is active. + - STAKE(τ): Amount of stake in the neuron, in Tao. + - RANK: The rank of the neuron within the network. + - TRUST: Trust score of the neuron. + - CONSENSUS: Consensus score of the neuron. + - INCENTIVE: Incentive score of the neuron. + - DIVIDENDS: Dividends earned by the neuron. + - EMISSION(p): Emission received by the neuron, in Rho. + - VTRUST: Validator trust score of the neuron. + - VPERMIT: Indicates if the neuron has a validator permit. + - UPDATED: Time since last update. + - AXON: IP address and port of the neuron. + - HOTKEY_SS58: Human-readable representation of the hotkey. + + Example usage:: + + btcli wallet overview + btcli wallet overview --all --sort_by stake --sort_order descending Note: - This command is read-only and does not modify the network state or account configurations. It provides a quick and - comprehensive view of the user's network presence, making it ideal for monitoring account status, stake distribution, - and overall contribution to the Bittensor network. + This command is read-only and does not modify the network state or account configurations. It provides a quick and + comprehensive view of the user's network presence, making it ideal for monitoring account status, stake distribution, + and overall contribution to the Bittensor network. """ @staticmethod diff --git a/bittensor/commands/register.py b/bittensor/commands/register.py index 2e3008c54b..07225ca2f8 100644 --- a/bittensor/commands/register.py +++ b/bittensor/commands/register.py @@ -29,32 +29,35 @@ class RegisterCommand: """ - Executes the 'register' command to register a neuron on the Bittensor network by recycling some TAO (the network's native token). + Executes the ``register`` command to register a neuron on the Bittensor network by recycling some TAO (the network's native token). + This command is used to add a new neuron to a specified subnet within the network, contributing to the decentralization and robustness of Bittensor. Usage: - Before registering, the command checks if the specified subnet exists and whether the user's balance is sufficient to cover the registration cost. - The registration cost is determined by the current recycle amount for the specified subnet. If the balance is insufficient or the subnet does not exist, - the command will exit with an appropriate error message. + Before registering, the command checks if the specified subnet exists and whether the user's balance is sufficient to cover the registration cost. + + The registration cost is determined by the current recycle amount for the specified subnet. If the balance is insufficient or the subnet does not exist, the command will exit with an appropriate error message. - If the preconditions are met, and the user confirms the transaction (if 'no_prompt' is not set), the command proceeds to register the neuron by burning the required amount of TAO. + If the preconditions are met, and the user confirms the transaction (if ``no_prompt`` is not set), the command proceeds to register the neuron by burning the required amount of TAO. The command structure includes: + - Verification of subnet existence. - Checking the user's balance against the current recycle amount for the subnet. - User confirmation prompt for proceeding with registration. - Execution of the registration process. - Columns Displayed in the Confirmation Prompt: + Columns Displayed in the confirmation prompt: + - Balance: The current balance of the user's wallet in TAO. - Cost to Register: The required amount of TAO needed to register on the specified subnet. - Example usage: - >>> btcli subnets register --netuid 1 + Example usage:: + + btcli subnets register --netuid 1 Note: - This command is critical for users who wish to contribute a new neuron to the network. It requires careful consideration of the subnet selection and - an understanding of the registration costs. Users should ensure their wallet is sufficiently funded before attempting to register a neuron. + This command is critical for users who wish to contribute a new neuron to the network. It requires careful consideration of the subnet selection and an understanding of the registration costs. Users should ensure their wallet is sufficiently funded before attempting to register a neuron. """ @staticmethod @@ -155,34 +158,35 @@ def check_config(config: "bittensor.config"): class PowRegisterCommand: """ - Executes the 'pow_register' command to register a neuron on the Bittensor network using Proof of Work (PoW). + Executes the ``pow_register`` command to register a neuron on the Bittensor network using Proof of Work (PoW). + This method is an alternative registration process that leverages computational work for securing a neuron's place on the network. Usage: - The command starts by verifying the existence of the specified subnet. If the subnet does not exist, it terminates with an error message. - On successful verification, the PoW registration process is initiated, which requires solving computational puzzles. + The command starts by verifying the existence of the specified subnet. If the subnet does not exist, it terminates with an error message. + On successful verification, the PoW registration process is initiated, which requires solving computational puzzles. Optional arguments: - - --netuid (int): The netuid for the subnet on which to serve the neuron. Mandatory for specifying the target subnet. - - --pow_register.num_processes (int): The number of processors to use for PoW registration. Defaults to the system's default setting. - - --pow_register.update_interval (int): The number of nonces to process before checking for the next block during registration. - Affects the frequency of update checks. - - --pow_register.no_output_in_place (bool): When set, disables the output of registration statistics in place. Useful for cleaner logs. - - --pow_register.verbose (bool): Enables verbose output of registration statistics for detailed information. - - --pow_register.cuda.use_cuda (bool): Enables the use of CUDA for GPU-accelerated PoW calculations. Requires a CUDA-compatible GPU. - - --pow_register.cuda.no_cuda (bool): Disables the use of CUDA, defaulting to CPU-based calculations. - - --pow_register.cuda.dev_id (int): Specifies the CUDA device ID, useful for systems with multiple CUDA-compatible GPUs. - - --pow_register.cuda.tpb (int): Sets the number of Threads Per Block for CUDA operations, affecting the GPU calculation dynamics. + - ``--netuid`` (int): The netuid for the subnet on which to serve the neuron. Mandatory for specifying the target subnet. + - ``--pow_register.num_processes`` (int): The number of processors to use for PoW registration. Defaults to the system's default setting. + - ``--pow_register.update_interval`` (int): The number of nonces to process before checking for the next block during registration. Affects the frequency of update checks. + - ``--pow_register.no_output_in_place`` (bool): When set, disables the output of registration statistics in place. Useful for cleaner logs. + - ``--pow_register.verbose`` (bool): Enables verbose output of registration statistics for detailed information. + - ``--pow_register.cuda.use_cuda`` (bool): Enables the use of CUDA for GPU-accelerated PoW calculations. Requires a CUDA-compatible GPU. + - ``--pow_register.cuda.no_cuda`` (bool): Disables the use of CUDA, defaulting to CPU-based calculations. + - ``--pow_register.cuda.dev_id`` (int): Specifies the CUDA device ID, useful for systems with multiple CUDA-compatible GPUs. + - ``--pow_register.cuda.tpb`` (int): Sets the number of Threads Per Block for CUDA operations, affecting the GPU calculation dynamics. The command also supports additional wallet and subtensor arguments, enabling further customization of the registration process. - Example usage: - >>> btcli pow_register --netuid 1 --pow_register.num_processes 4 --cuda.use_cuda + Example usage:: + + btcli pow_register --netuid 1 --pow_register.num_processes 4 --cuda.use_cuda Note: - This command is suited for users with adequate computational resources to participate in PoW registration. It requires a sound understanding - of the network's operations and PoW mechanics. Users should ensure their systems meet the necessary hardware and software requirements, - particularly when opting for CUDA-based GPU acceleration. + This command is suited for users with adequate computational resources to participate in PoW registration. It requires a sound understanding + of the network's operations and PoW mechanics. Users should ensure their systems meet the necessary hardware and software requirements, + particularly when opting for CUDA-based GPU acceleration. This command may be disabled according on the subnet owner's directive. For example, on netuid 1 this is permanently disabled. """ @@ -354,35 +358,37 @@ def check_config(config: "bittensor.config"): class RunFaucetCommand: """ - Executes the 'faucet' command to obtain test TAO tokens by performing Proof of Work (PoW). + Executes the ``faucet`` command to obtain test TAO tokens by performing Proof of Work (PoW). + + IMPORTANT: + **THIS COMMAND IS CURRENTLY DISABLED.** + This command is particularly useful for users who need test tokens for operations on the Bittensor testnet. Usage: - The command uses the PoW mechanism to validate the user's effort and rewards them with test TAO tokens. - It is typically used in testnet environments where real value transactions are not necessary. + The command uses the PoW mechanism to validate the user's effort and rewards them with test TAO tokens. It is typically used in testnet environments where real value transactions are not necessary. Optional arguments: - - --faucet.num_processes (int): Specifies the number of processors to use for the PoW operation. - A higher number of processors may increase the chances of successful computation. - - --faucet.update_interval (int): Sets the frequency of nonce processing before checking for the next block, - which impacts the PoW operation's responsiveness. - - --faucet.no_output_in_place (bool): When set, it disables in-place output of registration statistics for cleaner log visibility. - - --faucet.verbose (bool): Enables verbose output for detailed statistical information during the PoW process. - - --faucet.cuda.use_cuda (bool): Activates the use of CUDA for GPU acceleration in the PoW process, suitable for CUDA-compatible GPUs. - - --faucet.cuda.no_cuda (bool): Disables the use of CUDA, opting for CPU-based calculations. - - --faucet.cuda.dev_id (int[]): Allows selection of specific CUDA device IDs for the operation, useful in multi-GPU setups. - - --faucet.cuda.tpb (int): Determines the number of Threads Per Block for CUDA operations, affecting GPU calculation efficiency. + - ``--faucet.num_processes`` (int): Specifies the number of processors to use for the PoW operation. A higher number of processors may increase the chances of successful computation. + - ``--faucet.update_interval`` (int): Sets the frequency of nonce processing before checking for the next block, which impacts the PoW operation's responsiveness. + - ``--faucet.no_output_in_place`` (bool): When set, it disables in-place output of registration statistics for cleaner log visibility. + - ``--faucet.verbose`` (bool): Enables verbose output for detailed statistical information during the PoW process. + - ``--faucet.cuda.use_cuda`` (bool): Activates the use of CUDA for GPU acceleration in the PoW process, suitable for CUDA-compatible GPUs. + - ``--faucet.cuda.no_cuda`` (bool): Disables the use of CUDA, opting for CPU-based calculations. + - ``--faucet.cuda.dev_id`` (int[]): Allows selection of specific CUDA device IDs for the operation, useful in multi-GPU setups. + - ``--faucet.cuda.tpb`` (int): Determines the number of Threads Per Block for CUDA operations, affecting GPU calculation efficiency. These options provide flexibility in configuring the PoW process according to the user's hardware capabilities and preferences. - Example usage: - >>> btcli wallet faucet --faucet.num_processes 4 --faucet.cuda.use_cuda + Example usage:: + + btcli wallet faucet --faucet.num_processes 4 --faucet.cuda.use_cuda Note: - This command is meant for use in testnet environments where users can experiment with the network without using real TAO tokens. - It's important for users to have the necessary hardware setup, especially when opting for CUDA-based GPU calculations. + This command is meant for use in testnet environments where users can experiment with the network without using real TAO tokens. + It's important for users to have the necessary hardware setup, especially when opting for CUDA-based GPU calculations. - **THIS COMMAND IS CURRENTLY DISABLED!** + **THIS COMMAND IS CURRENTLY DISABLED.** """ @staticmethod diff --git a/bittensor/commands/root.py b/bittensor/commands/root.py index ea9450b872..49355d23f2 100644 --- a/bittensor/commands/root.py +++ b/bittensor/commands/root.py @@ -34,21 +34,24 @@ class RootRegisterCommand: """ - Executes the 'register' command to register a wallet to the root network of the Bittensor network. + Executes the ``register`` command to register a wallet to the root network of the Bittensor network. + This command is used to formally acknowledge a wallet's participation in the network's root layer. Usage: - The command registers the user's wallet with the root network, which is a crucial step for participating in network governance and other advanced functions. + The command registers the user's wallet with the root network, which is a crucial step for participating in network governance and other advanced functions. Optional arguments: - - None. The command primarily uses the wallet and subtensor configurations. + - None. The command primarily uses the wallet and subtensor configurations. + + Example usage:: - Example usage: - >>> btcli root register + btcli root register Note: - This command is important for users seeking to engage deeply with the Bittensor network, particularly in aspects related to network governance and decision-making. - It is a straightforward process but requires the user to have an initialized and configured wallet. + This command is important for users seeking to engage deeply with the Bittensor network, particularly in aspects related to network governance and decision-making. + + It is a straightforward process but requires the user to have an initialized and configured wallet. """ @staticmethod @@ -93,32 +96,32 @@ def check_config(config: "bittensor.config"): class RootList: """ - Executes the 'list' command to display the members of the root network on the Bittensor network. + Executes the ``list`` command to display the members of the root network on the Bittensor network. + This command provides an overview of the neurons that constitute the network's foundational layer. Usage: - Upon execution, the command fetches and lists the neurons in the root network, showing their unique identifiers (UIDs), names, addresses, stakes, - and whether they are part of the senate (network governance body). + Upon execution, the command fetches and lists the neurons in the root network, showing their unique identifiers (UIDs), names, addresses, stakes, and whether they are part of the senate (network governance body). Optional arguments: - - None. The command uses the subtensor configuration to retrieve data. + - None. The command uses the subtensor configuration to retrieve data. - Example usage: - >>> btcli root list + Example usage:: - UID NAME ADDRESS STAKE(τ) SENATOR - 0 5CaCUPsSSdKWcMJbmdmJdnWVa15fJQuz5HsSGgVdZffpHAUa 27086.37070 Yes - 1 RaoK9 5GmaAk7frPXnAxjbQvXcoEzMGZfkrDee76eGmKoB3wxUburE 520.24199 No - 2 Openτensor Foundaτion 5F4tQyWrhfGVcNhoqeiNsR6KjD4wMZ2kfhLj4oHYuyHbZAc3 1275437.45895 Yes - 3 RoundTable21 5FFApaS75bv5pJHfAp2FVLBj9ZaXuFDjEypsaBNc1wCfe52v 84718.42095 Yes - 4 5HK5tp6t2S59DywmHRWPBVJeJ86T61KjurYqeooqj8sREpeN 168897.40859 Yes - 5 Rizzo 5CXRfP2ekFhe62r7q3vppRajJmGhTi7vwvb2yr79jveZ282w 53383.34400 No - 6 τaosτaτs and BitAPAI 5Hddm3iBFD2GLT5ik7LZnT3XJUnRnN8PoeCFgGQgawUVKNm8 646944.73569 Yes - ... + $ btcli root list + + UID NAME ADDRESS STAKE(τ) SENATOR + 0 5CaCUPsSSdKWcMJbmdmJdnWVa15fJQuz5HsSGgVdZffpHAUa 27086.37070 Yes + 1 RaoK9 5GmaAk7frPXnAxjbQvXcoEzMGZfkrDee76eGmKoB3wxUburE 520.24199 No + 2 Openτensor Foundaτion 5F4tQyWrhfGVcNhoqeiNsR6KjD4wMZ2kfhLj4oHYuyHbZAc3 1275437.45895 Yes + 3 RoundTable21 5FFApaS75bv5pJHfAp2FVLBj9ZaXuFDjEypsaBNc1wCfe52v 84718.42095 Yes + 4 5HK5tp6t2S59DywmHRWPBVJeJ86T61KjurYqeooqj8sREpeN 168897.40859 Yes + 5 Rizzo 5CXRfP2ekFhe62r7q3vppRajJmGhTi7vwvb2yr79jveZ282w 53383.34400 No + 6 τaosτaτs and BitAPAI 5Hddm3iBFD2GLT5ik7LZnT3XJUnRnN8PoeCFgGQgawUVKNm8 646944.73569 Yes + ... Note: - This command is useful for users interested in understanding the composition and governance structure of the Bittensor network's root layer. - It provides insights into which neurons hold significant influence and responsibility within the network. + This command is useful for users interested in understanding the composition and governance structure of the Bittensor network's root layer. It provides insights into which neurons hold significant influence and responsibility within the network. """ @staticmethod @@ -216,17 +219,18 @@ def check_config(config: "bittensor.config"): class RootSetBoostCommand: """ - Executes the 'boost' command to boost the weights for a specific subnet within the root network on the Bittensor network. + Executes the ``boost`` command to boost the weights for a specific subnet within the root network on the Bittensor network. Usage: - The command allows boosting the weights for different subnets within the root network. + The command allows boosting the weights for different subnets within the root network. Optional arguments: - - --netuid (int): A single netuid for which weights are to be boosted. - - --increase (float): The cooresponding increase in the weight for this subnet. + - ``--netuid`` (int): A single netuid for which weights are to be boosted. + - ``--increase`` (float): The cooresponding increase in the weight for this subnet. + + Example usage:: - Example usage: - >>> btcli root boost --netuid 1 --increase 0.01 + $ btcli root boost --netuid 1 --increase 0.01 Enter netuid (e.g. 1): 1 Enter amount (e.g. 0.01): 0.1 @@ -336,17 +340,18 @@ def check_config(config: "bittensor.config"): class RootSetSlashCommand: """ - Executes the 'slash' command to decrease the weights for a specific subnet within the root network on the Bittensor network. + Executes the ``slash`` command to decrease the weights for a specific subnet within the root network on the Bittensor network. Usage: - The command allows slashing (decreasing) the weights for different subnets within the root network. + The command allows slashing (decreasing) the weights for different subnets within the root network. Optional arguments: - - --netuid (int): A single netuid for which weights are to be slashed. - - --decrease (float): The corresponding decrease in the weight for this subnet. + - ``--netuid`` (int): A single netuid for which weights are to be slashed. + - ``--decrease`` (float): The corresponding decrease in the weight for this subnet. + + Example usage:: - Example usage: - >>> btcli root slash --netuid 1 --decrease 0.01 + $ btcli root slash --netuid 1 --decrease 0.01 Enter netuid (e.g. 1): 1 Enter decrease amount (e.g. 0.01): 0.2 @@ -452,23 +457,24 @@ def check_config(config: "bittensor.config"): class RootSetWeightsCommand: """ - Executes the 'weights' command to set the weights for the root network on the Bittensor network. + Executes the ``weights`` command to set the weights for the root network on the Bittensor network. + This command is used by network senators to influence the distribution of network rewards and responsibilities. Usage: - The command allows setting weights for different subnets within the root network. - Users need to specify the netuids (network unique identifiers) and corresponding weights they wish to assign. + The command allows setting weights for different subnets within the root network. Users need to specify the netuids (network unique identifiers) and corresponding weights they wish to assign. Optional arguments: - - --netuids (str): A comma-separated list of netuids for which weights are to be set. - - --weights (str): Corresponding weights for the specified netuids, in comma-separated format. + - ``--netuids`` (str): A comma-separated list of netuids for which weights are to be set. + - ``--weights`` (str): Corresponding weights for the specified netuids, in comma-separated format. + + Example usage:: - Example usage: - >>> btcli root weights --netuids 1,2,3 --weights 0.3,0.3,0.4 + btcli root weights --netuids 1,2,3 --weights 0.3,0.3,0.4 Note: - This command is particularly important for network senators and requires a comprehensive understanding of the network's dynamics. - It is a powerful tool that directly impacts the network's operational mechanics and reward distribution. + This command is particularly important for network senators and requires a comprehensive understanding of the network's dynamics. + It is a powerful tool that directly impacts the network's operational mechanics and reward distribution. """ @staticmethod @@ -554,35 +560,35 @@ def check_config(config: "bittensor.config"): class RootGetWeightsCommand: """ - Executes the 'get_weights' command to retrieve the weights set for the root network on the Bittensor network. + Executes the ``get_weights`` command to retrieve the weights set for the root network on the Bittensor network. + This command provides visibility into how network responsibilities and rewards are distributed among various subnets. Usage: - The command outputs a table listing the weights assigned to each subnet within the root network. - This information is crucial for understanding the current influence and reward distribution among the subnets. + The command outputs a table listing the weights assigned to each subnet within the root network. This information is crucial for understanding the current influence and reward distribution among the subnets. Optional arguments: - - None. The command fetches weight information based on the subtensor configuration. - - Example usage: - >>> btcli root get_weights - - Root Network Weights - UID 0 1 2 3 4 5 8 9 11 13 18 19 - 1 100.00% - - - - - - - - - - - - 2 - 40.00% 5.00% 10.00% 10.00% 10.00% 10.00% 5.00% - - 10.00% - - 3 - - 25.00% - 25.00% - 25.00% - - - 25.00% - - 4 - - 7.00% 7.00% 20.00% 20.00% 20.00% - 6.00% - 20.00% - - 5 - 20.00% - 10.00% 15.00% 15.00% 15.00% 5.00% - - 10.00% 10.00% - 6 - - - - 10.00% 10.00% 25.00% 25.00% - - 30.00% - - 7 - 60.00% - - 20.00% - - - 20.00% - - - - 8 - 49.35% - 7.18% 13.59% 21.14% 1.53% 0.12% 7.06% 0.03% - - - 9 100.00% - - - - - - - - - - - - ... + - None. The command fetches weight information based on the subtensor configuration. + + Example usage:: + + $ btcli root get_weights + + Root Network Weights + UID 0 1 2 3 4 5 8 9 11 13 18 19 + 1 100.00% - - - - - - - - - - - + 2 - 40.00% 5.00% 10.00% 10.00% 10.00% 10.00% 5.00% - - 10.00% - + 3 - - 25.00% - 25.00% - 25.00% - - - 25.00% - + 4 - - 7.00% 7.00% 20.00% 20.00% 20.00% - 6.00% - 20.00% - + 5 - 20.00% - 10.00% 15.00% 15.00% 15.00% 5.00% - - 10.00% 10.00% + 6 - - - - 10.00% 10.00% 25.00% 25.00% - - 30.00% - + 7 - 60.00% - - 20.00% - - - 20.00% - - - + 8 - 49.35% - 7.18% 13.59% 21.14% 1.53% 0.12% 7.06% 0.03% - - + 9 100.00% - - - - - - - - - - - + ... Note: - This command is essential for users interested in the governance and operational dynamics of the Bittensor network. - It offers transparency into how network rewards and responsibilities are allocated across different subnets. + This command is essential for users interested in the governance and operational dynamics of the Bittensor network. It offers transparency into how network rewards and responsibilities are allocated across different subnets. """ @staticmethod diff --git a/bittensor/commands/senate.py b/bittensor/commands/senate.py index d3d8c67bbd..adb704a582 100644 --- a/bittensor/commands/senate.py +++ b/bittensor/commands/senate.py @@ -30,19 +30,20 @@ class SenateCommand: """ - Executes the 'senate' command to view the members of Bittensor's governance protocol, known as the Senate. + Executes the ``senate`` command to view the members of Bittensor's governance protocol, known as the Senate. + This command lists the delegates involved in the decision-making process of the Bittensor network. Usage: - The command retrieves and displays a list of Senate members, showing their names and wallet addresses. - This information is crucial for understanding who holds governance roles within the network. + The command retrieves and displays a list of Senate members, showing their names and wallet addresses. + This information is crucial for understanding who holds governance roles within the network. + + Example usage:: - Example usage: - >>> btcli root senate + btcli root senate Note: - This command is particularly useful for users interested in the governance structure and participants of the Bittensor network. - It provides transparency into the network's decision-making body. + This command is particularly useful for users interested in the governance structure and participants of the Bittensor network. It provides transparency into the network's decision-making body. """ @staticmethod @@ -166,19 +167,20 @@ def display_votes( class ProposalsCommand: """ - Executes the 'proposals' command to view active proposals within Bittensor's governance protocol. + Executes the ``proposals`` command to view active proposals within Bittensor's governance protocol. + This command displays the details of ongoing proposals, including votes, thresholds, and proposal data. Usage: - The command lists all active proposals, showing their hash, voting threshold, number of ayes and nays, - detailed votes by address, end block number, and call data associated with each proposal. + The command lists all active proposals, showing their hash, voting threshold, number of ayes and nays, detailed votes by address, end block number, and call data associated with each proposal. + + Example usage:: - Example usage: - >>> btcli root proposals + btcli root proposals Note: - This command is essential for users who are actively participating in or monitoring the governance of the Bittensor network. - It provides a detailed view of the proposals being considered, along with the community's response to each. + This command is essential for users who are actively participating in or monitoring the governance of the Bittensor network. + It provides a detailed view of the proposals being considered, along with the community's response to each. """ @staticmethod @@ -280,24 +282,28 @@ def add_args(cls, parser: argparse.ArgumentParser): class ShowVotesCommand: """ - Executes the 'proposal_votes' command to view the votes for a specific proposal in Bittensor's governance protocol. + Executes the ``proposal_votes`` command to view the votes for a specific proposal in Bittensor's governance protocol. + + IMPORTANT + **THIS COMMAND IS DEPRECATED**. Use ``btcli root proposals`` to see vote status. + This command provides a detailed breakdown of the votes cast by the senators for a particular proposal. Usage: - Users need to specify the hash of the proposal they are interested in. The command then displays the voting addresses - and their respective votes (Aye or Nay) for the specified proposal. + Users need to specify the hash of the proposal they are interested in. The command then displays the voting addresses and their respective votes (Aye or Nay) for the specified proposal. Optional arguments: - - --proposal (str): The hash of the proposal for which votes need to be displayed. + - ``--proposal`` (str): The hash of the proposal for which votes need to be displayed. + + Example usage:: - Example usage: - >>> btcli root proposal_votes --proposal + btcli root proposal_votes --proposal Note: - This command is crucial for users seeking detailed insights into the voting behavior of the Senate on specific governance proposals. - It helps in understanding the level of consensus or disagreement within the Senate on key decisions. + This command is crucial for users seeking detailed insights into the voting behavior of the Senate on specific governance proposals. + It helps in understanding the level of consensus or disagreement within the Senate on key decisions. - **THIS COMMAND IS DEPRECATED: Please use `btcli root proposals` to see vote status.** + **THIS COMMAND IS DEPRECATED**. Use ``btcli root proposals`` to see vote status. """ @staticmethod @@ -387,19 +393,21 @@ def add_args(cls, parser: argparse.ArgumentParser): class SenateRegisterCommand: """ - Executes the 'senate_register' command to register as a member of the Senate in Bittensor's governance protocol. + Executes the ``senate_register`` command to register as a member of the Senate in Bittensor's governance protocol. + This command is used by delegates who wish to participate in the governance and decision-making process of the network. Usage: - The command checks if the user's hotkey is a delegate and not already a Senate member before registering them to the Senate. - Successful execution allows the user to participate in proposal voting and other governance activities. + The command checks if the user's hotkey is a delegate and not already a Senate member before registering them to the Senate. + Successful execution allows the user to participate in proposal voting and other governance activities. + + Example usage:: - Example usage: - >>> btcli root senate_register + btcli root senate_register Note: - This command is intended for delegates who are interested in actively participating in the governance of the Bittensor network. - It is a significant step towards engaging in network decision-making processes. + This command is intended for delegates who are interested in actively participating in the governance of the Bittensor network. + It is a significant step towards engaging in network decision-making processes. """ @staticmethod @@ -467,19 +475,21 @@ def add_args(cls, parser: argparse.ArgumentParser): class SenateLeaveCommand: """ - Executes the 'senate_leave' command to discard membership in Bittensor's Senate. + Executes the ``senate_leave`` command to discard membership in Bittensor's Senate. + This command allows a Senate member to voluntarily leave the governance body. Usage: - The command checks if the user's hotkey is currently a Senate member before processing the request to leave the Senate. - It effectively removes the user from participating in future governance decisions. + The command checks if the user's hotkey is currently a Senate member before processing the request to leave the Senate. + It effectively removes the user from participating in future governance decisions. - Example usage: - >>> btcli root senate_leave + Example usage:: + + btcli root senate_leave Note: - This command is relevant for Senate members who wish to step down from their governance responsibilities within the Bittensor network. - It should be used when a member no longer desires to participate in the Senate activities. + This command is relevant for Senate members who wish to step down from their governance responsibilities within the Bittensor network. + It should be used when a member no longer desires to participate in the Senate activities. """ @staticmethod @@ -538,22 +548,22 @@ def add_args(cls, parser: argparse.ArgumentParser): class VoteCommand: """ - Executes the 'senate_vote' command to cast a vote on an active proposal in Bittensor's governance protocol. + Executes the ``senate_vote`` command to cast a vote on an active proposal in Bittensor's governance protocol. + This command is used by Senate members to vote on various proposals that shape the network's future. Usage: - The user needs to specify the hash of the proposal they want to vote on. The command then allows the Senate member - to cast an 'Aye' or 'Nay' vote, contributing to the decision-making process. + The user needs to specify the hash of the proposal they want to vote on. The command then allows the Senate member to cast an 'Aye' or 'Nay' vote, contributing to the decision-making process. Optional arguments: - - --proposal (str): The hash of the proposal to vote on. + - ``--proposal`` (str): The hash of the proposal to vote on. + + Example usage:: - Example usage: - >>> btcli root senate_vote --proposal + btcli root senate_vote --proposal Note: - This command is crucial for Senate members to exercise their voting rights on key proposals. It plays a vital role in the governance - and evolution of the Bittensor network. + This command is crucial for Senate members to exercise their voting rights on key proposals. It plays a vital role in the governance and evolution of the Bittensor network. """ @staticmethod diff --git a/bittensor/commands/stake.py b/bittensor/commands/stake.py index 71613335cf..cbb210f34b 100644 --- a/bittensor/commands/stake.py +++ b/bittensor/commands/stake.py @@ -30,30 +30,31 @@ class StakeCommand: """ - Executes the 'add' command to stake tokens to one or more hotkeys from a user's coldkey on the Bittensor network. + Executes the ``add`` command to stake tokens to one or more hotkeys from a user's coldkey on the Bittensor network. + This command is used to allocate tokens to different hotkeys, securing their position and influence on the network. Usage: - Users can specify the amount to stake, the hotkeys to stake to (either by name or SS58 address), - and whether to stake to all hotkeys. The command checks for sufficient balance and hotkey registration - before proceeding with the staking process. + Users can specify the amount to stake, the hotkeys to stake to (either by name or ``SS58`` address), and whether to stake to all hotkeys. The command checks for sufficient balance and hotkey registration + before proceeding with the staking process. Optional arguments: - - --all (bool): When set, stakes all available tokens from the coldkey. - - --uid (int): The unique identifier of the neuron to which the stake is to be added. - - --amount (float): The amount of TAO tokens to stake. - - --max_stake (float): Sets the maximum amount of TAO to have staked in each hotkey. - - --hotkeys (list): Specifies hotkeys by name or SS58 address to stake to. - - --all_hotkeys (bool): When set, stakes to all hotkeys associated with the wallet, excluding any specified in --hotkeys. + - ``--all`` (bool): When set, stakes all available tokens from the coldkey. + - ``--uid`` (int): The unique identifier of the neuron to which the stake is to be added. + - ``--amount`` (float): The amount of TAO tokens to stake. + - ``--max_stake`` (float): Sets the maximum amount of TAO to have staked in each hotkey. + - ``--hotkeys`` (list): Specifies hotkeys by name or SS58 address to stake to. + - ``--all_hotkeys`` (bool): When set, stakes to all hotkeys associated with the wallet, excluding any specified in --hotkeys. The command prompts for confirmation before executing the staking operation. - Example usage: - >>> btcli stake add --amount 100 --wallet.name --wallet.hotkey + Example usage:: + + btcli stake add --amount 100 --wallet.name --wallet.hotkey Note: - This command is critical for users who wish to distribute their stakes among different neurons (hotkeys) on the network. - It allows for a strategic allocation of tokens to enhance network participation and influence. + This command is critical for users who wish to distribute their stakes among different neurons (hotkeys) on the network. + It allows for a strategic allocation of tokens to enhance network participation and influence. """ @staticmethod @@ -343,29 +344,32 @@ def _get_hotkey_wallets_for_wallet(wallet) -> List["bittensor.wallet"]: class StakeShow: """ - Executes the 'show' command to list all stake accounts associated with a user's wallet on the Bittensor network. + Executes the ``show`` command to list all stake accounts associated with a user's wallet on the Bittensor network. + This command provides a comprehensive view of the stakes associated with both hotkeys and delegates linked to the user's coldkey. Usage: - The command lists all stake accounts for a specified wallet or all wallets in the user's configuration directory. - It displays the coldkey, balance, account details (hotkey/delegate name), stake amount, and the rate of return. + The command lists all stake accounts for a specified wallet or all wallets in the user's configuration directory. + It displays the coldkey, balance, account details (hotkey/delegate name), stake amount, and the rate of return. Optional arguments: - - --all (bool): When set, the command checks all coldkey wallets instead of just the specified wallet. + - ``--all`` (bool): When set, the command checks all coldkey wallets instead of just the specified wallet. The command compiles a table showing: + - Coldkey: The coldkey associated with the wallet. - Balance: The balance of the coldkey. - Account: The name of the hotkey or delegate. - Stake: The amount of TAO staked to the hotkey or delegate. - Rate: The rate of return on the stake, typically shown in TAO per day. - Example usage: - >>> btcli stake show --all + Example usage:: + + btcli stake show --all Note: - This command is essential for users who wish to monitor their stake distribution and returns across various accounts on the Bittensor network. - It provides a clear and detailed overview of the user's staking activities. + This command is essential for users who wish to monitor their stake distribution and returns across various accounts on the Bittensor network. + It provides a clear and detailed overview of the user's staking activities. """ @staticmethod diff --git a/bittensor/commands/transfer.py b/bittensor/commands/transfer.py index ae50305c61..24c6e78402 100644 --- a/bittensor/commands/transfer.py +++ b/bittensor/commands/transfer.py @@ -27,25 +27,26 @@ class TransferCommand: """ - Executes the 'transfer' command to transfer TAO tokens from one account to another on the Bittensor network. + Executes the ``transfer`` command to transfer TAO tokens from one account to another on the Bittensor network. + This command is used for transactions between different accounts, enabling users to send tokens to other participants on the network. Usage: - The command requires specifying the destination address (public key) and the amount of TAO to be transferred. - It checks for sufficient balance and prompts for confirmation before proceeding with the transaction. + The command requires specifying the destination address (public key) and the amount of TAO to be transferred. + It checks for sufficient balance and prompts for confirmation before proceeding with the transaction. Optional arguments: - - --dest (str): The destination address for the transfer. This can be in the form of an SS58 or ed2519 public key. - - --amount (float): The amount of TAO tokens to transfer. + - ``--dest`` (str): The destination address for the transfer. This can be in the form of an SS58 or ed2519 public key. + - ``--amount`` (float): The amount of TAO tokens to transfer. The command displays the user's current balance before prompting for the amount to transfer, ensuring transparency and accuracy in the transaction. - Example usage: - >>> btcli wallet transfer --dest 5Dp8... --amount 100 + Example usage:: + + btcli wallet transfer --dest 5Dp8... --amount 100 Note: - This command is crucial for executing token transfers within the Bittensor network. Users should verify the destination address and amount - before confirming the transaction to avoid errors or loss of funds. + This command is crucial for executing token transfers within the Bittensor network. Users should verify the destination address and amount before confirming the transaction to avoid errors or loss of funds. """ @staticmethod diff --git a/bittensor/commands/unstake.py b/bittensor/commands/unstake.py index f1e121abe4..a2290d5b84 100644 --- a/bittensor/commands/unstake.py +++ b/bittensor/commands/unstake.py @@ -29,29 +29,30 @@ class UnStakeCommand: """ - Executes the 'remove' command to unstake TAO tokens from one or more hotkeys and transfer them back to the user's coldkey on the Bittensor network. + Executes the ``remove`` command to unstake TAO tokens from one or more hotkeys and transfer them back to the user's coldkey on the Bittensor network. + This command is used to withdraw tokens previously staked to different hotkeys. Usage: - Users can specify the amount to unstake, the hotkeys to unstake from (either by name or SS58 address), - and whether to unstake from all hotkeys. The command checks for sufficient stake and prompts for confirmation before proceeding with the unstaking process. + Users can specify the amount to unstake, the hotkeys to unstake from (either by name or ``SS58`` address), and whether to unstake from all hotkeys. The command checks for sufficient stake and prompts for confirmation before proceeding with the unstaking process. Optional arguments: - - --all (bool): When set, unstakes all staked tokens from the specified hotkeys. - - --amount (float): The amount of TAO tokens to unstake. - - --hotkey_ss58address (str): The SS58 address of the hotkey to unstake from. - - --max_stake (float): Sets the maximum amount of TAO to remain staked in each hotkey. - - --hotkeys (list): Specifies hotkeys by name or SS58 address to unstake from. - - --all_hotkeys (bool): When set, unstakes from all hotkeys associated with the wallet, excluding any specified in --hotkeys. + - ``--all`` (bool): When set, unstakes all staked tokens from the specified hotkeys. + - ``--amount`` (float): The amount of TAO tokens to unstake. + - --hotkey_ss58address (str): The SS58 address of the hotkey to unstake from. + - ``--max_stake`` (float): Sets the maximum amount of TAO to remain staked in each hotkey. + - ``--hotkeys`` (list): Specifies hotkeys by name or SS58 address to unstake from. + - ``--all_hotkeys`` (bool): When set, unstakes from all hotkeys associated with the wallet, excluding any specified in --hotkeys. The command prompts for confirmation before executing the unstaking operation. - Example usage: - >>> btcli stake remove --amount 100 --hotkeys hk1,hk2 + Example usage:: + + btcli stake remove --amount 100 --hotkeys hk1,hk2 Note: - This command is important for users who wish to reallocate their stakes or withdraw them from the network. - It allows for flexible management of token stakes across different neurons (hotkeys) on the network. + This command is important for users who wish to reallocate their stakes or withdraw them from the network. + It allows for flexible management of token stakes across different neurons (hotkeys) on the network. """ @classmethod diff --git a/bittensor/commands/wallets.py b/bittensor/commands/wallets.py index 22d62c00da..ea19155b6e 100644 --- a/bittensor/commands/wallets.py +++ b/bittensor/commands/wallets.py @@ -29,27 +29,29 @@ class RegenColdkeyCommand: """ - Executes the 'regen_coldkey' command to regenerate a coldkey for a wallet on the Bittensor network. + Executes the ``regen_coldkey`` command to regenerate a coldkey for a wallet on the Bittensor network. + This command is used to create a new coldkey from an existing mnemonic, seed, or JSON file. Usage: - Users can specify a mnemonic, a seed string, or a JSON file path to regenerate a coldkey. - The command supports optional password protection for the generated key and can overwrite an existing coldkey. + Users can specify a mnemonic, a seed string, or a JSON file path to regenerate a coldkey. + The command supports optional password protection for the generated key and can overwrite an existing coldkey. Optional arguments: - - --mnemonic (str): A mnemonic phrase used to regenerate the key. - - --seed (str): A seed hex string used for key regeneration. - - --json (str): Path to a JSON file containing an encrypted key backup. - - --json_password (str): Password to decrypt the JSON file. - - --use_password (bool): Enables password protection for the generated key. - - --overwrite_coldkey (bool): Overwrites the existing coldkey with the new one. + - ``--mnemonic`` (str): A mnemonic phrase used to regenerate the key. + - ``--seed`` (str): A seed hex string used for key regeneration. + - ``--json`` (str): Path to a JSON file containing an encrypted key backup. + - ``--json_password`` (str): Password to decrypt the JSON file. + - ``--use_password`` (bool): Enables password protection for the generated key. + - ``--overwrite_coldkey`` (bool): Overwrites the existing coldkey with the new one. + + Example usage:: - Example usage: - >>> btcli wallet regen_coldkey --mnemonic "word1 word2 ... word12" + btcli wallet regen_coldkey --mnemonic "word1 word2 ... word12" Note: - This command is critical for users who need to regenerate their coldkey, possibly for recovery or security reasons. - It should be used with caution to avoid overwriting existing keys unintentionally. + This command is critical for users who need to regenerate their coldkey, possibly for recovery or security reasons. + It should be used with caution to avoid overwriting existing keys unintentionally. """ def run(cli): @@ -153,24 +155,25 @@ def add_args(parser: argparse.ArgumentParser): class RegenColdkeypubCommand: """ - Executes the 'regen_coldkeypub' command to regenerate the public part of a coldkey (coldkeypub) for a wallet on the Bittensor network. + Executes the ``regen_coldkeypub`` command to regenerate the public part of a coldkey (coldkeypub) for a wallet on the Bittensor network. + This command is used when a user needs to recreate their coldkeypub from an existing public key or SS58 address. Usage: - The command requires either a public key in hexadecimal format or an SS58 address to regenerate the coldkeypub. - It optionally allows overwriting an existing coldkeypub file. + The command requires either a public key in hexadecimal format or an ``SS58`` address to regenerate the coldkeypub. It optionally allows overwriting an existing coldkeypub file. Optional arguments: - - --public_key_hex (str): The public key in hex format. - - --ss58_address (str): The SS58 address of the coldkey. - - --overwrite_coldkeypub (bool): Overwrites the existing coldkeypub file with the new one. + - ``--public_key_hex`` (str): The public key in hex format. + - ``--ss58_address`` (str): The SS58 address of the coldkey. + - ``--overwrite_coldkeypub`` (bool): Overwrites the existing coldkeypub file with the new one. - Example usage: - >>> btcli wallet regen_coldkeypub --ss58_address 5DkQ4... + Example usage:: + + btcli wallet regen_coldkeypub --ss58_address 5DkQ4... Note: - This command is particularly useful for users who need to regenerate their coldkeypub, perhaps due to file corruption or loss. - It is a recovery-focused utility that ensures continued access to wallet functionalities. + This command is particularly useful for users who need to regenerate their coldkeypub, perhaps due to file corruption or loss. + It is a recovery-focused utility that ensures continued access to wallet functionalities. """ def run(cli): @@ -239,28 +242,30 @@ def add_args(parser: argparse.ArgumentParser): class RegenHotkeyCommand: """ - Executes the 'regen_hotkey' command to regenerate a hotkey for a wallet on the Bittensor network. + Executes the ``regen_hotkey`` command to regenerate a hotkey for a wallet on the Bittensor network. + Similar to regenerating a coldkey, this command creates a new hotkey from a mnemonic, seed, or JSON file. Usage: - Users can provide a mnemonic, seed string, or a JSON file to regenerate the hotkey. - The command supports optional password protection and can overwrite an existing hotkey. + Users can provide a mnemonic, seed string, or a JSON file to regenerate the hotkey. + The command supports optional password protection and can overwrite an existing hotkey. Optional arguments: - - --mnemonic (str): A mnemonic phrase used to regenerate the key. - - --seed (str): A seed hex string used for key regeneration. - - --json (str): Path to a JSON file containing an encrypted key backup. - - --json_password (str): Password to decrypt the JSON file. - - --use_password (bool): Enables password protection for the generated key. - - --overwrite_hotkey (bool): Overwrites the existing hotkey with the new one. + - ``--mnemonic`` (str): A mnemonic phrase used to regenerate the key. + - ``--seed`` (str): A seed hex string used for key regeneration. + - ``--json`` (str): Path to a JSON file containing an encrypted key backup. + - ``--json_password`` (str): Password to decrypt the JSON file. + - ``--use_password`` (bool): Enables password protection for the generated key. + - ``--overwrite_hotkey`` (bool): Overwrites the existing hotkey with the new one. - Example usage: - >>> btcli wallet regen_hotkey - >>> btcli wallet regen_hotkey --seed 0x1234... + Example usage:: + + btcli wallet regen_hotkey + btcli wallet regen_hotkey --seed 0x1234... Note: - This command is essential for users who need to regenerate their hotkey, possibly for security upgrades or key recovery. - It should be used cautiously to avoid accidental overwrites of existing keys. + This command is essential for users who need to regenerate their hotkey, possibly for security upgrades or key recovery. + It should be used cautiously to avoid accidental overwrites of existing keys. """ def run(cli): @@ -369,24 +374,26 @@ def add_args(parser: argparse.ArgumentParser): class NewHotkeyCommand: """ - Executes the 'new_hotkey' command to create a new hotkey under a wallet on the Bittensor network. + Executes the ``new_hotkey`` command to create a new hotkey under a wallet on the Bittensor network. + This command is used to generate a new hotkey for managing a neuron or participating in the network. Usage: - The command creates a new hotkey with an optional word count for the mnemonic and supports password protection. - It also allows overwriting an existing hotkey. + The command creates a new hotkey with an optional word count for the mnemonic and supports password protection. + It also allows overwriting an existing hotkey. Optional arguments: - - --n_words (int): The number of words in the mnemonic phrase. - - --use_password (bool): Enables password protection for the generated key. - - --overwrite_hotkey (bool): Overwrites the existing hotkey with the new one. + - ``--n_words`` (int): The number of words in the mnemonic phrase. + - ``--use_password`` (bool): Enables password protection for the generated key. + - ``--overwrite_hotkey`` (bool): Overwrites the existing hotkey with the new one. - Example usage: - >>> btcli wallet new_hotkey --n_words 24 + Example usage:: + + btcli wallet new_hotkey --n_words 24 Note: - This command is useful for users who wish to create additional hotkeys for different purposes, - such as running multiple miners or separating operational roles within the network. + This command is useful for users who wish to create additional hotkeys for different purposes, + such as running multiple miners or separating operational roles within the network. """ def run(cli): @@ -446,24 +453,26 @@ def add_args(parser: argparse.ArgumentParser): class NewColdkeyCommand: """ - Executes the 'new_coldkey' command to create a new coldkey under a wallet on the Bittensor network. + Executes the ``new_coldkey`` command to create a new coldkey under a wallet on the Bittensor network. + This command generates a coldkey, which is essential for holding balances and performing high-value transactions. Usage: - The command creates a new coldkey with an optional word count for the mnemonic and supports password protection. - It also allows overwriting an existing coldkey. + The command creates a new coldkey with an optional word count for the mnemonic and supports password protection. + It also allows overwriting an existing coldkey. Optional arguments: - - --n_words (int): The number of words in the mnemonic phrase. - - --use_password (bool): Enables password protection for the generated key. - - --overwrite_coldkey (bool): Overwrites the existing coldkey with the new one. + - ``--n_words`` (int): The number of words in the mnemonic phrase. + - ``--use_password`` (bool): Enables password protection for the generated key. + - ``--overwrite_coldkey`` (bool): Overwrites the existing coldkey with the new one. - Example usage: - >>> btcli wallet new_coldkey --n_words 15 + Example usage:: + + btcli wallet new_coldkey --n_words 15 Note: - This command is crucial for users who need to create a new coldkey for enhanced security or as part of setting up a new wallet. - It's a foundational step in establishing a secure presence on the Bittensor network. + This command is crucial for users who need to create a new coldkey for enhanced security or as part of setting up a new wallet. + It's a foundational step in establishing a secure presence on the Bittensor network. """ def run(cli): @@ -519,25 +528,27 @@ def add_args(parser: argparse.ArgumentParser): class WalletCreateCommand: """ - Executes the 'create' command to generate both a new coldkey and hotkey under a specified wallet on the Bittensor network. + Executes the ``create`` command to generate both a new coldkey and hotkey under a specified wallet on the Bittensor network. + This command is a comprehensive utility for creating a complete wallet setup with both cold and hotkeys. Usage: - The command facilitates the creation of a new coldkey and hotkey with an optional word count for the mnemonics. - It supports password protection for the coldkey and allows overwriting of existing keys. + The command facilitates the creation of a new coldkey and hotkey with an optional word count for the mnemonics. + It supports password protection for the coldkey and allows overwriting of existing keys. Optional arguments: - - --n_words (int): The number of words in the mnemonic phrase for both keys. - - --use_password (bool): Enables password protection for the coldkey. - - --overwrite_coldkey (bool): Overwrites the existing coldkey with the new one. - - --overwrite_hotkey (bool): Overwrites the existing hotkey with the new one. + - ``--n_words`` (int): The number of words in the mnemonic phrase for both keys. + - ``--use_password`` (bool): Enables password protection for the coldkey. + - ``--overwrite_coldkey`` (bool): Overwrites the existing coldkey with the new one. + - ``--overwrite_hotkey`` (bool): Overwrites the existing hotkey with the new one. + + Example usage:: - Example usage: - >>> btcli wallet create --n_words 21 + btcli wallet create --n_words 21 Note: - This command is ideal for new users setting up their wallet for the first time or for those who wish to completely renew their wallet keys. - It ensures a fresh start with new keys for secure and effective participation in the network. + This command is ideal for new users setting up their wallet for the first time or for those who wish to completely renew their wallet keys. + It ensures a fresh start with new keys for secure and effective participation in the network. """ def run(cli): @@ -618,23 +629,25 @@ def _get_coldkey_wallets_for_path(path: str) -> List["bittensor.wallet"]: class UpdateWalletCommand: """ - Executes the 'update' command to check and potentially update the security of the wallets in the Bittensor network. + Executes the ``update`` command to check and potentially update the security of the wallets in the Bittensor network. + This command is used to enhance wallet security using modern encryption standards. Usage: - The command checks if any of the wallets need an update in their security protocols. - It supports updating all legacy wallets or a specific one based on the user's choice. + The command checks if any of the wallets need an update in their security protocols. + It supports updating all legacy wallets or a specific one based on the user's choice. Optional arguments: - - --all (bool): When set, updates all legacy wallets. - - --no_prompt (bool): Disables user prompting during the update process. + - ``--all`` (bool): When set, updates all legacy wallets. + - ``--no_prompt`` (bool): Disables user prompting during the update process. + + Example usage:: - Example usage: - >>> btcli wallet update --all + btcli wallet update --all Note: - This command is important for maintaining the highest security standards for users' wallets. - It is recommended to run this command periodically to ensure wallets are up-to-date with the latest security practices. + This command is important for maintaining the highest security standards for users' wallets. + It is recommended to run this command periodically to ensure wallets are up-to-date with the latest security practices. """ @staticmethod @@ -711,22 +724,23 @@ def list_coldkeypub_files(dir_path): class WalletBalanceCommand: """ - Executes the 'balance' command to check the balance of the wallet on the Bittensor network. + Executes the ``balance`` command to check the balance of the wallet on the Bittensor network. + This command provides a detailed view of the wallet's coldkey balances, including free and staked balances. Usage: - The command lists the balances of all wallets in the user's configuration directory, showing the wallet name, - coldkey address, and the respective free and staked balances. + The command lists the balances of all wallets in the user's configuration directory, showing the wallet name, coldkey address, and the respective free and staked balances. Optional arguments: - None. The command uses the wallet and subtensor configurations to fetch balance data. + None. The command uses the wallet and subtensor configurations to fetch balance data. + + Example usage:: - Example usage: - >>> btcli wallet balance + btcli wallet balance Note: - This command is essential for users to monitor their financial status on the Bittensor network. - It helps in keeping track of assets and ensuring the wallet's financial health. + This command is essential for users to monitor their financial status on the Bittensor network. + It helps in keeping track of assets and ensuring the wallet's financial health. """ @staticmethod @@ -869,22 +883,23 @@ def check_config(config: "bittensor.config"): class GetWalletHistoryCommand: """ - Executes the 'history' command to fetch the latest transfers of the provided wallet on the Bittensor network. + Executes the ``history`` command to fetch the latest transfers of the provided wallet on the Bittensor network. This command provides a detailed view of the transfers carried out on the wallet. Usage: - The command lists the latest transfers of the provided wallet, showing the From, To, Amount, Extrinsic Id and Block Number. + The command lists the latest transfers of the provided wallet, showing the From, To, Amount, Extrinsic Id and Block Number. Optional arguments: - None. The command uses the wallet and subtensor configurations to fetch latest transfer data associated with a wallet. + None. The command uses the wallet and subtensor configurations to fetch latest transfer data associated with a wallet. - Example usage: - >>> btcli wallet history + Example usage:: + + btcli wallet history Note: - This command is essential for users to monitor their financial status on the Bittensor network. - It helps in fetching info on all the transfers so that user can easily tally and cross check the transactions. + This command is essential for users to monitor their financial status on the Bittensor network. + It helps in fetching info on all the transfers so that user can easily tally and cross check the transactions. """ @staticmethod @@ -947,7 +962,16 @@ def create_transfer_history_table(transfers): table = Table(show_footer=False) # Define the column names - column_names = ["Id", "From", "To", "Amount (Tao)", "Extrinsic Id", "Block Number"] + column_names = [ + "Id", + "From", + "To", + "Amount (Tao)", + "Extrinsic Id", + "Block Number", + "URL (taostats)", + ] + taostats_url_base = "https://x.taostats.io/extrinsic" # Create a table table = Table(show_footer=False) @@ -983,6 +1007,7 @@ def create_transfer_history_table(transfers): f"{tao_amount:.3f}", str(item["extrinsicId"]), item["blockNumber"], + f"{taostats_url_base}/{item['blockNumber']}-{item['extrinsicId']}", ) table.add_row() table.show_footer = True diff --git a/bittensor/extrinsics/delegation.py b/bittensor/extrinsics/delegation.py index aa61f14fb0..f64365f2bb 100644 --- a/bittensor/extrinsics/delegation.py +++ b/bittensor/extrinsics/delegation.py @@ -35,12 +35,11 @@ def nominate_extrinsic( wait_for_inclusion: bool = True, ) -> bool: r"""Becomes a delegate for the hotkey. + Args: - wallet ( bittensor.wallet ): - The wallet to become a delegate for. + wallet (bittensor.wallet): The wallet to become a delegate for. Returns: - success (bool): - True if the transaction was successful. + success (bool): ``True`` if the transaction was successful. """ # Unlock the coldkey. wallet.coldkey @@ -105,31 +104,20 @@ def delegate_extrinsic( prompt: bool = False, ) -> bool: r"""Delegates the specified amount of stake to the passed delegate. + Args: - wallet (bittensor.wallet): - Bittensor wallet object. - delegate_ss58 (Optional[str]): - ss58 address of the delegate. - amount (Union[Balance, float]): - Amount to stake as bittensor balance, or float interpreted as Tao. - wait_for_inclusion (bool): - If set, waits for the extrinsic to enter a block before returning true, - or returns false if the extrinsic fails to enter the block within the timeout. - wait_for_finalization (bool): - If set, waits for the extrinsic to be finalized on the chain before returning true, - or returns false if the extrinsic fails to be finalized within the timeout. - prompt (bool): - If true, the call waits for confirmation from the user before proceeding. + wallet (bittensor.wallet): Bittensor wallet object. + delegate_ss58 (Optional[str]): The ``ss58`` address of the delegate. + amount (Union[Balance, float]): Amount to stake as bittensor balance, or ``float`` interpreted as Tao. + wait_for_inclusion (bool): If set, waits for the extrinsic to enter a block before returning ``true``, or returns ``false`` if the extrinsic fails to enter the block within the timeout. + wait_for_finalization (bool): If set, waits for the extrinsic to be finalized on the chain before returning ``true``, or returns ``false`` if the extrinsic fails to be finalized within the timeout. + prompt (bool): If ``true``, the call waits for confirmation from the user before proceeding. Returns: - success (bool): - flag is true if extrinsic was finalized or uncluded in the block. - If we did not wait for finalization / inclusion, the response is true. + success (bool): Flag is ``true`` if extrinsic was finalized or uncluded in the block. If we did not wait for finalization / inclusion, the response is ``true``. Raises: - NotRegisteredError: - If the wallet is not registered on the chain. - NotDelegateError: - If the hotkey is not a delegate on the chain. + NotRegisteredError: If the wallet is not registered on the chain. + NotDelegateError: If the hotkey is not a delegate on the chain. """ # Decrypt keys, wallet.coldkey @@ -251,31 +239,20 @@ def undelegate_extrinsic( prompt: bool = False, ) -> bool: r"""Un-delegates stake from the passed delegate. + Args: - wallet (bittensor.wallet): - Bittensor wallet object. - delegate_ss58 (Optional[str]): - ss58 address of the delegate. - amount (Union[Balance, float]): - Amount to unstake as bittensor balance, or float interpreted as Tao. - wait_for_inclusion (bool): - If set, waits for the extrinsic to enter a block before returning true, - or returns false if the extrinsic fails to enter the block within the timeout. - wait_for_finalization (bool): - If set, waits for the extrinsic to be finalized on the chain before returning true, - or returns false if the extrinsic fails to be finalized within the timeout. - prompt (bool): - If true, the call waits for confirmation from the user before proceeding. + wallet (bittensor.wallet): Bittensor wallet object. + delegate_ss58 (Optional[str]): The ``ss58`` address of the delegate. + amount (Union[Balance, float]): Amount to unstake as bittensor balance, or ``float`` interpreted as Tao. + wait_for_inclusion (bool): If set, waits for the extrinsic to enter a block before returning ``true``, or returns ``false`` if the extrinsic fails to enter the block within the timeout. + wait_for_finalization (bool): If set, waits for the extrinsic to be finalized on the chain before returning ``true``, or returns ``false`` if the extrinsic fails to be finalized within the timeout. + prompt (bool): If ``true``, the call waits for confirmation from the user before proceeding. Returns: - success (bool): - flag is true if extrinsic was finalized or uncluded in the block. - If we did not wait for finalization / inclusion, the response is true. + success (bool): Flag is ``true`` if extrinsic was finalized or uncluded in the block. If we did not wait for finalization / inclusion, the response is ``true``. Raises: - NotRegisteredError: - If the wallet is not registered on the chain. - NotDelegateError: - If the hotkey is not a delegate on the chain. + NotRegisteredError: If the wallet is not registered on the chain. + NotDelegateError: If the hotkey is not a delegate on the chain. """ # Decrypt keys, wallet.coldkey diff --git a/bittensor/extrinsics/log_utilities.py b/bittensor/extrinsics/log_utilities.py index 917aeb1536..bcd6f09890 100644 --- a/bittensor/extrinsics/log_utilities.py +++ b/bittensor/extrinsics/log_utilities.py @@ -16,8 +16,7 @@ class ValidatorLogger: Including console log styling, console table print and prometheus. Args: - config (:obj:`bittensor.Config`, `optional`): - bittensor.server.config() + config (:func:`bittensor.Config`, optional): ``bittensor.server.config()`` """ def __init__(self, config=None): @@ -227,19 +226,19 @@ def print_response_table( tasks_per_server: int = 3, ): r""" - Prints the query response table: top prediction probabilities and texts for batch tasks. - - Args: - batch_predictions (:obj:`List[Union[str, Dict{torch.Tensor, str}]]`, `required`): - Predictions in string per task per uid. In the format of [(task, {uid, "prob: phrase" })] of length batch size. - stats (:obj:`Dict{Dict}`, `required`): - Statistics per endpoint for this batch. In the format of {uid, {statistics}}. - sort_col (:type:`str`, `required`): - Column name used for sorting. Options from self.neuron_stats_columns[:, 1]. - task_repeat (:type:`int`, `required`): - The number of servers to compare against under the same set of task. - tasks_per_server (:type:`int`, `required`): - How many tasks to show for each server. + Prints the query response table with top prediction probabilities and texts for batch tasks. + + Args: + batch_predictions (:obj:`List[Union[str, Dict{torch.Tensor, str}]]`, required): + Predictions in string per task per ``uid``. In the format of ``[(task, {uid, "prob: phrase" })]`` of length batch size. + stats (:obj:`Dict{Dict}`, required): + Statistics per endpoint for this batch. In the format of ``{uid, {statistics}}``. + sort_col (str, required): + Column name used for sorting. Options from ``self.neuron_stats_columns[:, 1]``. + task_repeat (int, required): + The number of servers to compare against under the same set of task. + tasks_per_server (int, required): + How many tasks to show for each server. """ # === Batch permutation === batch_size = len(batch_predictions) @@ -325,13 +324,13 @@ def print_synergy_table(self, stats: Dict, syn_loss_diff: Dict, sort_col: str): r""" Prints the synergy loss diff matrix with pairwise loss reduction due to synergy (original loss on diagonal). - Args: - stats (:obj:`Dict{Dict}`, `required`): - Statistics per endpoint for this batch. In the format of {uid, {statistics}}. - syn_loss_diff (:obj:`Dict`, `required`): - Dictionary table of pairwise synergies as loss reductions, with direct loss on diagonal. - sort_col (:type:`str`, `required`): - Column name used for sorting. Options from self.neuron_stats_columns[:, 1]. + Args: + stats (:obj:`Dict{Dict}`, required): + Statistics per endpoint for this batch. In the format of ``{uid, {statistics}}``. + syn_loss_diff (:obj:`Dict`, required): + Dictionary table of pairwise synergies as loss reductions, with direct loss on diagonal. + sort_col (str, required): + Column name used for sorting. Options from ``self.neuron_stats_columns[:, 1]``. """ sort = sorted( [(uid, s[sort_col]) for uid, s in stats.items() if sort_col in s], @@ -384,15 +383,15 @@ def print_stats_table( r""" Gathers data and constructs neuron statistics table and prints it. - Args: - stats (:obj:`Dict{Dict}`, `required`): - Statistics per endpoint for this batch. In the format of {uid, {statistics}}. - sort_col (:type:`str`, `required`): - Column name used for sorting. Options from self.neuron_stats_columns[:, 1]. - title (:type:`str`, `required`): - Title of the table. - caption (:type:`str`, `required`): - Caption shown at the end of table. + Args: + stats (:obj:`Dict{Dict}`, required): + Statistics per endpoint for this batch. In the format of ``{uid, {statistics}}``. + sort_col (str, required): + Column name used for sorting. Options from ``self.neuron_stats_columns[:, 1]``. + title (str, required): + Title of the table. + caption (str, required): + Caption shown at the end of table. """ # === Gather columns and rows === if mark_uids is None: @@ -459,17 +458,17 @@ def print_synapse_table( self, name: str, stats: Dict, sort_col: str, start_time: time.time ): r""" - Prints the evaluation of the neuron responses to the validator request - - Args: - stats (:obj:`Dict{Dict}`, `required`): - Statistics per endpoint for this batch. In the format of {uid, {statistics}}. - sort_col (:type:`str`, `required`): - Column name used for sorting. Options from self.neuron_stats_columns[:, 1]. - name (:obj:`str`, `required`): - Name of synapse for the title of the table. - start_time (:obj:`time.time`, `required`): - Starting time for shapley calculation. + Prints the evaluation of the neuron responses to the validator request. + + Args: + stats (Dict{Dict}, required): + Statistics per endpoint for this batch. In the format of ``{uid, {statistics}}``. + sort_col (str, required): + Column name used for sorting. Options from ``self.neuron_stats_columns[:, 1]``. + name (str, required): + Name of synapse for the title of the table. + start_time (time.time, required): + Starting time for shapley calculation. """ self.print_stats_table( @@ -496,25 +495,25 @@ def print_weights_table( r""" Prints weights table given sample_uids and sample_weights. - Args: - min_allowed_weights (:type:`int`, `required`): - subtensor minimum allowed weight to set. - max_weight_limit (:type:`int`, `required`): - subtensor maximum allowed weight to set. - neuron_stats (:obj:`Dict{Dict}`, `required`): - Statistics per endpoint for this batch. In the format of {uid, {statistics}}. - title (:type:`str`, `required`): - Title of the table. - metagraph_n (:type:`int`, `required`): - Total number of uids in the metagraph. - sample_uids (:obj:`torch.Tensor`, `required`): - Uids to set weight for. - sample_weights (:obj:`torch.Tensor`, `required`): - Weights to set uids for. - include_uids (:type:`list`, `optional`): - Set of uids to inculde in the table. - num_rows (:type:`int`, `optional`): - Total number of uids to print in total. + Args: + min_allowed_weights (int, required): + subtensor minimum allowed weight to set. + max_weight_limit (int, required): + subtensor maximum allowed weight to set. + neuron_stats (Dict{Dict}, required): + Statistics per endpoint for this batch. In the format of ``{uid, {statistics}}``. + title (str, required): + Title of the table. + metagraph_n (int, required): + Total number of ``uid``s in the metagraph. + sample_uids (torch.Tensor, required): + ``Uid``s to set weight for. + sample_weights (torch.Tensor, required): + Weights to set ``uid``s for. + include_uids (list, optional): + Set of ``uid``s to inculde in the table. + num_rows (int, optional): + Total number of ``uid``s to print in total. """ # === Weight table === # Prints exponential moving average statistics of valid neurons and latest weights @@ -666,9 +665,10 @@ def print_console_subtensor_weight( class ValidatorPrometheus: r""" Prometheis logging object for validator. - Args: - config (:obj:`bittensor.Config`, `optional`): - bittensor.server.config() + + Args: + config (bittensor.Config, optional): + ``bittensor.server.config()`` """ def __init__(self, config): diff --git a/bittensor/extrinsics/network.py b/bittensor/extrinsics/network.py index d148005e31..d9e8fe346a 100644 --- a/bittensor/extrinsics/network.py +++ b/bittensor/extrinsics/network.py @@ -30,22 +30,21 @@ def register_subnetwork_extrinsic( wait_for_finalization: bool = True, prompt: bool = False, ) -> bool: - r"""Registers a new subnetwork + r"""Registers a new subnetwork. + Args: wallet (bittensor.wallet): bittensor wallet object. wait_for_inclusion (bool): - If set, waits for the extrinsic to enter a block before returning true, - or returns false if the extrinsic fails to enter the block within the timeout. + If set, waits for the extrinsic to enter a block before returning ``true``, or returns ``false`` if the extrinsic fails to enter the block within the timeout. wait_for_finalization (bool): - If set, waits for the extrinsic to be finalized on the chain before returning true, - or returns false if the extrinsic fails to be finalized within the timeout. + If set, waits for the extrinsic to be finalized on the chain before returning ``true``, or returns ``false`` if the extrinsic fails to be finalized within the timeout. prompt (bool): If true, the call waits for confirmation from the user before proceeding. Returns: success (bool): - flag is true if extrinsic was finalized or included in the block. - If we did not wait for finalization / inclusion, the response is true. + Flag is ``true`` if extrinsic was finalized or included in the block. + If we did not wait for finalization / inclusion, the response is ``true``. """ your_balance = subtensor.get_balance(wallet.coldkeypub.ss58_address) burn_cost = bittensor.utils.balance.Balance(subtensor.get_subnet_burn_cost()) @@ -117,27 +116,26 @@ def set_hyperparameter_extrinsic( prompt: bool = False, ) -> bool: r"""Sets a hyperparameter for a specific subnetwork. + Args: wallet (bittensor.wallet): bittensor wallet object. netuid (int): - Subnetwork uid. + Subnetwork ``uid``. parameter (str): Hyperparameter name. value (any): New hyperparameter value. wait_for_inclusion (bool): - If set, waits for the extrinsic to enter a block before returning true, - or returns false if the extrinsic fails to enter the block within the timeout. + If set, waits for the extrinsic to enter a block before returning ``true``, or returns ``false`` if the extrinsic fails to enter the block within the timeout. wait_for_finalization (bool): - If set, waits for the extrinsic to be finalized on the chain before returning true, - or returns false if the extrinsic fails to be finalized within the timeout. + If set, waits for the extrinsic to be finalized on the chain before returning ``true``, or returns ``false`` if the extrinsic fails to be finalized within the timeout. prompt (bool): - If true, the call waits for confirmation from the user before proceeding. + If ``true``, the call waits for confirmation from the user before proceeding. Returns: success (bool): - flag is true if extrinsic was finalized or included in the block. - If we did not wait for finalization / inclusion, the response is true. + Flag is ``true`` if extrinsic was finalized or included in the block. + If we did not wait for finalization / inclusion, the response is ``true``. """ if subtensor.get_subnet_owner(netuid) != wallet.coldkeypub.ss58_address: bittensor.__console__.print( diff --git a/bittensor/extrinsics/prometheus.py b/bittensor/extrinsics/prometheus.py index 55a3224852..754f65ddd9 100644 --- a/bittensor/extrinsics/prometheus.py +++ b/bittensor/extrinsics/prometheus.py @@ -31,28 +31,27 @@ def prometheus_extrinsic( wait_for_inclusion: bool = False, wait_for_finalization=True, ) -> bool: - r"""Subscribes an bittensor endpoint to the substensor chain. + r"""Subscribes an Bittensor endpoint to the substensor chain. + Args: subtensor (bittensor.subtensor): - bittensor subtensor object. + Bittensor subtensor object. wallet (bittensor.wallet): - bittensor wallet object. + Bittensor wallet object. ip (str): - endpoint host port i.e. 192.122.31.4 + Endpoint host port i.e., ``192.122.31.4``. port (int): - endpoint port number i.e. 9221 + Endpoint port number i.e., `9221`. netuid (int): - network uid to serve on. + Network `uid` to serve on. wait_for_inclusion (bool): - if set, waits for the extrinsic to enter a block before returning true, - or returns false if the extrinsic fails to enter the block within the timeout. + If set, waits for the extrinsic to enter a block before returning ``true``, or returns ``false`` if the extrinsic fails to enter the block within the timeout. wait_for_finalization (bool): - if set, waits for the extrinsic to be finalized on the chain before returning true, - or returns false if the extrinsic fails to be finalized within the timeout. + If set, waits for the extrinsic to be finalized on the chain before returning ``true``, or returns ``false`` if the extrinsic fails to be finalized within the timeout. Returns: success (bool): - flag is true if extrinsic was finalized or uncluded in the block. - If we did not wait for finalization / inclusion, the response is true. + Flag is ``true`` if extrinsic was finalized or uncluded in the block. + If we did not wait for finalization / inclusion, the response is ``true``. """ # ---- Get external ip ---- diff --git a/bittensor/extrinsics/registration.py b/bittensor/extrinsics/registration.py index 285ee737a7..e75217b217 100644 --- a/bittensor/extrinsics/registration.py +++ b/bittensor/extrinsics/registration.py @@ -41,24 +41,23 @@ def register_extrinsic( update_interval: Optional[int] = None, log_verbose: bool = False, ) -> bool: - r"""Registers the wallet to chain. + r"""Registers the wallet to the chain. + Args: wallet (bittensor.wallet): - bittensor wallet object. + Bittensor wallet object. netuid (int): - The netuid of the subnet to register on. + The ``netuid`` of the subnet to register on. wait_for_inclusion (bool): - If set, waits for the extrinsic to enter a block before returning true, - or returns false if the extrinsic fails to enter the block within the timeout. + If set, waits for the extrinsic to enter a block before returning ``true``, or returns ``false`` if the extrinsic fails to enter the block within the timeout. wait_for_finalization (bool): - If set, waits for the extrinsic to be finalized on the chain before returning true, - or returns false if the extrinsic fails to be finalized within the timeout. + If set, waits for the extrinsic to be finalized on the chain before returning ``true``, or returns ``false`` if the extrinsic fails to be finalized within the timeout. prompt (bool): - If true, the call waits for confirmation from the user before proceeding. + If ``true``, the call waits for confirmation from the user before proceeding. max_allowed_attempts (int): Maximum number of attempts to register the wallet. cuda (bool): - If true, the wallet should be registered using CUDA device(s). + If ``true``, the wallet should be registered using CUDA device(s). dev_id (Union[List[int], int]): The CUDA device id to use, or a list of device ids. tpb (int): @@ -68,11 +67,10 @@ def register_extrinsic( update_interval (int): The number of nonces to solve between updates. log_verbose (bool): - If true, the registration process will log more information. + If ``true``, the registration process will log more information. Returns: success (bool): - flag is true if extrinsic was finalized or uncluded in the block. - If we did not wait for finalization / inclusion, the response is true. + Flag is ``true`` if extrinsic was finalized or uncluded in the block. If we did not wait for finalization / inclusion, the response is ``true``. """ if not subtensor.subnet_exists(netuid): bittensor.__console__.print( @@ -225,23 +223,21 @@ def burned_register_extrinsic( prompt: bool = False, ) -> bool: r"""Registers the wallet to chain by recycling TAO. + Args: wallet (bittensor.wallet): - bittensor wallet object. + Bittensor wallet object. netuid (int): - The netuid of the subnet to register on. + The ``netuid`` of the subnet to register on. wait_for_inclusion (bool): - If set, waits for the extrinsic to enter a block before returning true, - or returns false if the extrinsic fails to enter the block within the timeout. + If set, waits for the extrinsic to enter a block before returning ``true``, or returns ``false`` if the extrinsic fails to enter the block within the timeout. wait_for_finalization (bool): - If set, waits for the extrinsic to be finalized on the chain before returning true, - or returns false if the extrinsic fails to be finalized within the timeout. + If set, waits for the extrinsic to be finalized on the chain before returning ``true``, or returns ``false`` if the extrinsic fails to be finalized within the timeout. prompt (bool): - If true, the call waits for confirmation from the user before proceeding. + If ``true``, the call waits for confirmation from the user before proceeding. Returns: success (bool): - flag is true if extrinsic was finalized or uncluded in the block. - If we did not wait for finalization / inclusion, the response is true. + Flag is ``true`` if extrinsic was finalized or uncluded in the block. If we did not wait for finalization / inclusion, the response is ``true``. """ if not subtensor.subnet_exists(netuid): bittensor.__console__.print( @@ -345,21 +341,20 @@ def run_faucet_extrinsic( log_verbose: bool = False, ) -> bool: r"""Runs a continual POW to get a faucet of TAO on the test net. + Args: wallet (bittensor.wallet): - bittensor wallet object. + Bittensor wallet object. prompt (bool): - If true, the call waits for confirmation from the user before proceeding. + If ``true``, the call waits for confirmation from the user before proceeding. wait_for_inclusion (bool): - If set, waits for the extrinsic to enter a block before returning true, - or returns false if the extrinsic fails to enter the block within the timeout. + If set, waits for the extrinsic to enter a block before returning ``true``, or returns ``false`` if the extrinsic fails to enter the block within the timeout. wait_for_finalization (bool): - If set, waits for the extrinsic to be finalized on the chain before returning true, - or returns false if the extrinsic fails to be finalized within the timeout. + If set, waits for the extrinsic to be finalized on the chain before returning ``true``, or returns ``false`` if the extrinsic fails to be finalized within the timeout. max_allowed_attempts (int): Maximum number of attempts to register the wallet. cuda (bool): - If true, the wallet should be registered using CUDA device(s). + If ``true``, the wallet should be registered using CUDA device(s). dev_id (Union[List[int], int]): The CUDA device id to use, or a list of device ids. tpb (int): @@ -369,11 +364,10 @@ def run_faucet_extrinsic( update_interval (int): The number of nonces to solve between updates. log_verbose (bool): - If true, the registration process will log more information. + If ``true``, the registration process will log more information. Returns: success (bool): - flag is true if extrinsic was finalized or uncluded in the block. - If we did not wait for finalization / inclusion, the response is true. + Flag is ``true`` if extrinsic was finalized or uncluded in the block. If we did not wait for finalization / inclusion, the response is ``true``. """ if prompt: if not Confirm.ask( diff --git a/bittensor/extrinsics/root.py b/bittensor/extrinsics/root.py index a83dcfaa7e..71cd88c5ed 100644 --- a/bittensor/extrinsics/root.py +++ b/bittensor/extrinsics/root.py @@ -37,21 +37,19 @@ def root_register_extrinsic( prompt: bool = False, ) -> bool: r"""Registers the wallet to root network. + Args: wallet (bittensor.wallet): - bittensor wallet object. + Bittensor wallet object. wait_for_inclusion (bool): - If set, waits for the extrinsic to enter a block before returning true, - or returns false if the extrinsic fails to enter the block within the timeout. + If set, waits for the extrinsic to enter a block before returning ``true``, or returns ``false`` if the extrinsic fails to enter the block within the timeout. wait_for_finalization (bool): - If set, waits for the extrinsic to be finalized on the chain before returning true, - or returns false if the extrinsic fails to be finalized within the timeout. + If set, waits for the extrinsic to be finalized on the chain before returning ``true``, or returns ``false`` if the extrinsic fails to be finalized within the timeout. prompt (bool): - If true, the call waits for confirmation from the user before proceeding. + If ``true``, the call waits for confirmation from the user before proceeding. Returns: success (bool): - flag is true if extrinsic was finalized or uncluded in the block. - If we did not wait for finalization / inclusion, the response is true. + Flag is ``true`` if extrinsic was finalized or uncluded in the block. If we did not wait for finalization / inclusion, the response is ``true``. """ wallet.coldkey # unlock coldkey @@ -111,27 +109,25 @@ def set_root_weights_extrinsic( prompt: bool = False, ) -> bool: r"""Sets the given weights and values on chain for wallet hotkey account. + Args: wallet (bittensor.wallet): - bittensor wallet object. + Bittensor wallet object. netuids (List[int]): - netuid of the subent to set weights for. + The ``netuid`` of the subnet to set weights for. weights ( Union[torch.FloatTensor, list]): - weights to set which must floats and correspond to the passed uids. + Weights to set. These must be ``float`` s and must correspond to the passed ``netuid`` s. version_key (int): - version key of the validator. + The version key of the validator. wait_for_inclusion (bool): - if set, waits for the extrinsic to enter a block before returning true, - or returns false if the extrinsic fails to enter the block within the timeout. + If set, waits for the extrinsic to enter a block before returning ``true``, or returns ``false`` if the extrinsic fails to enter the block within the timeout. wait_for_finalization (bool): - if set, waits for the extrinsic to be finalized on the chain before returning true, - or returns false if the extrinsic fails to be finalized within the timeout. + If set, waits for the extrinsic to be finalized on the chain before returning ``true``, or returns ``false`` if the extrinsic fails to be finalized within the timeout. prompt (bool): - If true, the call waits for confirmation from the user before proceeding. + If ``true``, the call waits for confirmation from the user before proceeding. Returns: success (bool): - flag is true if extrinsic was finalized or uncluded in the block. - If we did not wait for finalization / inclusion, the response is true. + Flag is ``true`` if extrinsic was finalized or uncluded in the block. If we did not wait for finalization / inclusion, the response is ``true``. """ # First convert types. if isinstance(netuids, list): diff --git a/bittensor/extrinsics/senate.py b/bittensor/extrinsics/senate.py index ee27a20f15..565854dd69 100644 --- a/bittensor/extrinsics/senate.py +++ b/bittensor/extrinsics/senate.py @@ -32,21 +32,19 @@ def register_senate_extrinsic( prompt: bool = False, ) -> bool: r"""Registers the wallet to chain for senate voting. + Args: wallet (bittensor.wallet): - bittensor wallet object. + Bittensor wallet object. wait_for_inclusion (bool): - If set, waits for the extrinsic to enter a block before returning true, - or returns false if the extrinsic fails to enter the block within the timeout. + If set, waits for the extrinsic to enter a block before returning ``true``, or returns ``false`` if the extrinsic fails to enter the block within the timeout. wait_for_finalization (bool): - If set, waits for the extrinsic to be finalized on the chain before returning true, - or returns false if the extrinsic fails to be finalized within the timeout. + If set, waits for the extrinsic to be finalized on the chain before returning ``true``, or returns ``false`` if the extrinsic fails to be finalized within the timeout. prompt (bool): - If true, the call waits for confirmation from the user before proceeding. + If ``true``, the call waits for confirmation from the user before proceeding. Returns: success (bool): - flag is true if extrinsic was finalized or included in the block. - If we did not wait for finalization / inclusion, the response is true. + Flag is ``true`` if extrinsic was finalized or included in the block. If we did not wait for finalization / inclusion, the response is ``true``. """ wallet.coldkey # unlock coldkey wallet.hotkey # unlock hotkey @@ -111,21 +109,19 @@ def leave_senate_extrinsic( prompt: bool = False, ) -> bool: r"""Removes the wallet from chain for senate voting. + Args: wallet (bittensor.wallet): - bittensor wallet object. + Bittensor wallet object. wait_for_inclusion (bool): - If set, waits for the extrinsic to enter a block before returning true, - or returns false if the extrinsic fails to enter the block within the timeout. + If set, waits for the extrinsic to enter a block before returning ``true``, or returns ``false`` if the extrinsic fails to enter the block within the timeout. wait_for_finalization (bool): - If set, waits for the extrinsic to be finalized on the chain before returning true, - or returns false if the extrinsic fails to be finalized within the timeout. + If set, waits for the extrinsic to be finalized on the chain before returning ``true``, or returns ``false`` if the extrinsic fails to be finalized within the timeout. prompt (bool): - If true, the call waits for confirmation from the user before proceeding. + If ``true``, the call waits for confirmation from the user before proceeding. Returns: success (bool): - flag is true if extrinsic was finalized or included in the block. - If we did not wait for finalization / inclusion, the response is true. + Flag is ``true`` if extrinsic was finalized or included in the block. If we did not wait for finalization / inclusion, the response is ``true``. """ wallet.coldkey # unlock coldkey wallet.hotkey # unlock hotkey @@ -193,21 +189,19 @@ def vote_senate_extrinsic( prompt: bool = False, ) -> bool: r"""Removes the wallet from chain for senate voting. + Args: wallet (bittensor.wallet): - bittensor wallet object. + Bittensor wallet object. wait_for_inclusion (bool): - If set, waits for the extrinsic to enter a block before returning true, - or returns false if the extrinsic fails to enter the block within the timeout. + If set, waits for the extrinsic to enter a block before returning ``true``, or returns ``false`` if the extrinsic fails to enter the block within the timeout. wait_for_finalization (bool): - If set, waits for the extrinsic to be finalized on the chain before returning true, - or returns false if the extrinsic fails to be finalized within the timeout. + If set, waits for the extrinsic to be finalized on the chain before returning ``true``, or returns ``false`` if the extrinsic fails to be finalized within the timeout. prompt (bool): - If true, the call waits for confirmation from the user before proceeding. + If ``true``, the call waits for confirmation from the user before proceeding. Returns: success (bool): - flag is true if extrinsic was finalized or included in the block. - If we did not wait for finalization / inclusion, the response is true. + Flag is ``true`` if extrinsic was finalized or included in the block. If we did not wait for finalization / inclusion, the response is ``true``. """ wallet.coldkey # unlock coldkey wallet.hotkey # unlock hotkey diff --git a/bittensor/extrinsics/serving.py b/bittensor/extrinsics/serving.py index 11eb8e24e4..ed49e871e5 100644 --- a/bittensor/extrinsics/serving.py +++ b/bittensor/extrinsics/serving.py @@ -36,34 +36,32 @@ def serve_extrinsic( wait_for_finalization=True, prompt: bool = False, ) -> bool: - r"""Subscribes an bittensor endpoint to the substensor chain. + r"""Subscribes a Bittensor endpoint to the subtensor chain. + Args: wallet (bittensor.wallet): - bittensor wallet object. + Bittensor wallet object. ip (str): - endpoint host port i.e. 192.122.31.4 + Endpoint host port i.e., ``192.122.31.4``. port (int): - endpoint port number i.e. 9221 + Endpoint port number i.e., ``9221``. protocol (int): - int representation of the protocol + An ``int`` representation of the protocol. netuid (int): - network uid to serve on. + The network uid to serve on. placeholder1 (int): - placeholder for future use. + A placeholder for future use. placeholder2 (int): - placeholder for future use. + A placeholder for future use. wait_for_inclusion (bool): - if set, waits for the extrinsic to enter a block before returning true, - or returns false if the extrinsic fails to enter the block within the timeout. + If set, waits for the extrinsic to enter a block before returning ``true``, or returns ``false`` if the extrinsic fails to enter the block within the timeout. wait_for_finalization (bool): - if set, waits for the extrinsic to be finalized on the chain before returning true, - or returns false if the extrinsic fails to be finalized within the timeout. + If set, waits for the extrinsic to be finalized on the chain before returning ``true``, or returns ``false`` if the extrinsic fails to be finalized within the timeout. prompt (bool): - If true, the call waits for confirmation from the user before proceeding. + If ``true``, the call waits for confirmation from the user before proceeding. Returns: success (bool): - flag is true if extrinsic was finalized or uncluded in the block. - If we did not wait for finalization / inclusion, the response is true. + Flag is ``true`` if extrinsic was finalized or uncluded in the block. If we did not wait for finalization / inclusion, the response is ``true``. """ # Decrypt hotkey wallet.hotkey @@ -149,23 +147,21 @@ def serve_axon_extrinsic( prompt: bool = False, ) -> bool: r"""Serves the axon to the network. + Args: netuid ( int ): - The netuid being served on. + The ``netuid`` being served on. axon (bittensor.Axon): Axon to serve. wait_for_inclusion (bool): - If set, waits for the extrinsic to enter a block before returning true, - or returns false if the extrinsic fails to enter the block within the timeout. + If set, waits for the extrinsic to enter a block before returning ``true``, or returns ``false`` if the extrinsic fails to enter the block within the timeout. wait_for_finalization (bool): - If set, waits for the extrinsic to be finalized on the chain before returning true, - or returns false if the extrinsic fails to be finalized within the timeout. + If set, waits for the extrinsic to be finalized on the chain before returning ``true``, or returns ``false`` if the extrinsic fails to be finalized within the timeout. prompt (bool): - If true, the call waits for confirmation from the user before proceeding. + If ``true``, the call waits for confirmation from the user before proceeding. Returns: success (bool): - flag is true if extrinsic was finalized or uncluded in the block. - If we did not wait for finalization / inclusion, the response is true. + Flag is ``true`` if extrinsic was finalized or uncluded in the block. If we did not wait for finalization / inclusion, the response is ``true``. """ axon.wallet.hotkey axon.wallet.coldkeypub @@ -216,32 +212,27 @@ def publish_metadata( wait_for_finalization: bool = True, ) -> bool: """ - Publishes metadata on the bittensor network using the specified wallet and network identifier. + Publishes metadata on the Bittensor network using the specified wallet and network identifier. Args: subtensor (bittensor.subtensor): - The subtensor instance representing the bittensor blockchain connection. + The subtensor instance representing the Bittensor blockchain connection. wallet (bittensor.wallet): The wallet object used for authentication in the transaction. netuid (int): Network UID on which the metadata is to be published. type (str): - The data type of the information being submitted. It should be one of the following: - 'Sha256', 'Blake256', 'Keccak256', or 'Raw0-128'. This specifies the format or - hashing algorithm used for the data. + The data type of the information being submitted. It should be one of the following: ``'Sha256'``, ``'Blake256'``, ``'Keccak256'``, or ``'Raw0-128'``. This specifies the format or hashing algorithm used for the data. data (str): - The actual metadata content to be published. This should be formatted or hashed - according to the 'type' specified. (Note: max str length of 128 bytes) + The actual metadata content to be published. This should be formatted or hashed according to the ``type`` specified. (Note: max ``str`` length is 128 bytes) wait_for_inclusion (bool, optional): - If True, the function will wait for the extrinsic to be included in a block before returning. - Defaults to False. + If ``True``, the function will wait for the extrinsic to be included in a block before returning. Defaults to ``False``. wait_for_finalization (bool, optional): - If True, the function will wait for the extrinsic to be finalized on the chain before returning. - Defaults to True. + If ``True``, the function will wait for the extrinsic to be finalized on the chain before returning. Defaults to ``True``. Returns: bool: - True if the metadata was successfully published (and finalized if specified). False otherwise. + ``True`` if the metadata was successfully published (and finalized if specified). ``False`` otherwise. Raises: MetadataError: diff --git a/bittensor/extrinsics/set_weights.py b/bittensor/extrinsics/set_weights.py index bd5b623bd9..d27214cd36 100644 --- a/bittensor/extrinsics/set_weights.py +++ b/bittensor/extrinsics/set_weights.py @@ -40,29 +40,27 @@ def set_weights_extrinsic( prompt: bool = False, ) -> bool: r"""Sets the given weights and values on chain for wallet hotkey account. + Args: wallet (bittensor.wallet): - bittensor wallet object. + Bittensor wallet object. netuid (int): - netuid of the subent to set weights for. + The ``netuid`` of the subnet to set weights for. uids (Union[torch.LongTensor, list]): - uint64 uids of destination neurons. + The ``uint64`` uids of destination neurons. weights ( Union[torch.FloatTensor, list]): - weights to set which must floats and correspond to the passed uids. + The weights to set. These must be ``float`` s and correspond to the passed ``uid`` s. version_key (int): - version key of the validator. + The version key of the validator. wait_for_inclusion (bool): - if set, waits for the extrinsic to enter a block before returning true, - or returns false if the extrinsic fails to enter the block within the timeout. + If set, waits for the extrinsic to enter a block before returning ``true``, or returns ``false`` if the extrinsic fails to enter the block within the timeout. wait_for_finalization (bool): - if set, waits for the extrinsic to be finalized on the chain before returning true, - or returns false if the extrinsic fails to be finalized within the timeout. + If set, waits for the extrinsic to be finalized on the chain before returning ``true``, or returns ``false`` if the extrinsic fails to be finalized within the timeout. prompt (bool): - If true, the call waits for confirmation from the user before proceeding. + If ``true``, the call waits for confirmation from the user before proceeding. Returns: success (bool): - flag is true if extrinsic was finalized or uncluded in the block. - If we did not wait for finalization / inclusion, the response is true. + Flag is ``true`` if extrinsic was finalized or uncluded in the block. If we did not wait for finalization / inclusion, the response is ``true``. """ # First convert types. if isinstance(uids, list): diff --git a/bittensor/extrinsics/staking.py b/bittensor/extrinsics/staking.py index 926717270c..7f89b9fc00 100644 --- a/bittensor/extrinsics/staking.py +++ b/bittensor/extrinsics/staking.py @@ -32,27 +32,24 @@ def add_stake_extrinsic( wait_for_finalization: bool = False, prompt: bool = False, ) -> bool: - r"""Adds the specified amount of stake to passed hotkey uid. + r"""Adds the specified amount of stake to passed hotkey ``uid``. + Args: wallet (bittensor.wallet): Bittensor wallet object. hotkey_ss58 (Optional[str]): - ss58 address of the hotkey account to stake to - defaults to the wallet's hotkey. + The ``ss58`` address of the hotkey account to stake to defaults to the wallet's hotkey. amount (Union[Balance, float]): - Amount to stake as bittensor balance, or float interpreted as Tao. + Amount to stake as Bittensor balance, or ``float`` interpreted as Tao. wait_for_inclusion (bool): - If set, waits for the extrinsic to enter a block before returning true, - or returns false if the extrinsic fails to enter the block within the timeout. + If set, waits for the extrinsic to enter a block before returning ``true``, or returns ``false`` if the extrinsic fails to enter the block within the timeout. wait_for_finalization (bool): - If set, waits for the extrinsic to be finalized on the chain before returning true, - or returns false if the extrinsic fails to be finalized within the timeout. + If set, waits for the extrinsic to be finalized on the chain before returning ``true``, or returns ``false`` if the extrinsic fails to be finalized within the timeout. prompt (bool): - If true, the call waits for confirmation from the user before proceeding. + If ``true``, the call waits for confirmation from the user before proceeding. Returns: success (bool): - flag is true if extrinsic was finalized or uncluded in the block. - If we did not wait for finalization / inclusion, the response is true. + Flag is ``true`` if extrinsic was finalized or uncluded in the block. If we did not wait for finalization / inclusion, the response is ``true``. Raises: bittensor.errors.NotRegisteredError: @@ -212,27 +209,24 @@ def add_stake_multiple_extrinsic( wait_for_finalization: bool = False, prompt: bool = False, ) -> bool: - r"""Adds stake to each hotkey_ss58 in the list, using each amount, from a common coldkey. + r"""Adds stake to each ``hotkey_ss58`` in the list, using each amount, from a common coldkey. + Args: wallet (bittensor.wallet): Bittensor wallet object for the coldkey. hotkey_ss58s (List[str]): List of hotkeys to stake to. amounts (List[Union[Balance, float]]): - List of amounts to stake. If None, stake all to the first hotkey. + List of amounts to stake. If ``None``, stake all to the first hotkey. wait_for_inclusion (bool): - if set, waits for the extrinsic to enter a block before returning true, - or returns false if the extrinsic fails to enter the block within the timeout. + If set, waits for the extrinsic to enter a block before returning ``true``, or returns ``false`` if the extrinsic fails to enter the block within the timeout. wait_for_finalization (bool): - if set, waits for the extrinsic to be finalized on the chain before returning true, - or returns false if the extrinsic fails to be finalized within the timeout. + If set, waits for the extrinsic to be finalized on the chain before returning ``true``, or returns ``false`` if the extrinsic fails to be finalized within the timeout. prompt (bool): - If true, the call waits for confirmation from the user before proceeding. + If ``true``, the call waits for confirmation from the user before proceeding. Returns: success (bool): - flag is true if extrinsic was finalized or included in the block. - flag is true if any wallet was staked. - If we did not wait for finalization / inclusion, the response is true. + Flag is ``true`` if extrinsic was finalized or included in the block. Flag is ``true`` if any wallet was staked. If we did not wait for finalization / inclusion, the response is ``true``. """ if not isinstance(hotkey_ss58s, list) or not all( isinstance(hotkey_ss58, str) for hotkey_ss58 in hotkey_ss58s @@ -440,26 +434,24 @@ def __do_add_stake_single( wait_for_finalization: bool = False, ) -> bool: r""" - Executes a stake call to the chain using the wallet and amount specified. + Executes a stake call to the chain using the wallet and the amount specified. + Args: wallet (bittensor.wallet): Bittensor wallet object. hotkey_ss58 (str): Hotkey to stake to. amount (bittensor.Balance): - Amount to stake as bittensor balance object. + Amount to stake as Bittensor balance object. wait_for_inclusion (bool): - If set, waits for the extrinsic to enter a block before returning true, - or returns false if the extrinsic fails to enter the block within the timeout. + If set, waits for the extrinsic to enter a block before returning ``true``, or returns ``false`` if the extrinsic fails to enter the block within the timeout. wait_for_finalization (bool): - If set, waits for the extrinsic to be finalized on the chain before returning true, - or returns false if the extrinsic fails to be finalized within the timeout. + If set, waits for the extrinsic to be finalized on the chain before returning ``true``, or returns ``false`` if the extrinsic fails to be finalized within the timeout. prompt (bool): - If true, the call waits for confirmation from the user before proceeding. + If ``true``, the call waits for confirmation from the user before proceeding. Returns: success (bool): - flag is true if extrinsic was finalized or uncluded in the block. - If we did not wait for finalization / inclusion, the response is true. + Flag is ``true`` if extrinsic was finalized or uncluded in the block. If we did not wait for finalization / inclusion, the response is ``true``. Raises: bittensor.errors.StakeError: If the extrinsic fails to be finalized or included in the block. diff --git a/bittensor/extrinsics/transfer.py b/bittensor/extrinsics/transfer.py index 915cf8730a..2bb673eaf3 100644 --- a/bittensor/extrinsics/transfer.py +++ b/bittensor/extrinsics/transfer.py @@ -34,28 +34,26 @@ def transfer_extrinsic( keep_alive: bool = True, prompt: bool = False, ) -> bool: - r"""Transfers funds from this wallet to the destination public key address + r"""Transfers funds from this wallet to the destination public key address. + Args: wallet (bittensor.wallet): Bittensor wallet object to make transfer from. dest (str, ss58_address or ed25519): Destination public key address of reciever. amount (Union[Balance, int]): - Amount to stake as bittensor balance, or float interpreted as Tao. + Amount to stake as Bittensor balance, or ``float`` interpreted as Tao. wait_for_inclusion (bool): - If set, waits for the extrinsic to enter a block before returning true, - or returns false if the extrinsic fails to enter the block within the timeout. + If set, waits for the extrinsic to enter a block before returning ``true``, or returns ``false`` if the extrinsic fails to enter the block within the timeout. wait_for_finalization (bool): - If set, waits for the extrinsic to be finalized on the chain before returning true, - or returns false if the extrinsic fails to be finalized within the timeout. + If set, waits for the extrinsic to be finalized on the chain before returning ``true``, or returns ``false`` if the extrinsic fails to be finalized within the timeout. keep_alive (bool): If set, keeps the account alive by keeping the balance above the existential deposit. prompt (bool): - If true, the call waits for confirmation from the user before proceeding. + If ``true``, the call waits for confirmation from the user before proceeding. Returns: success (bool): - Flag is true if extrinsic was finalized or uncluded in the block. - If we did not wait for finalization / inclusion, the response is true. + Flag is ``true`` if extrinsic was finalized or uncluded in the block. If we did not wait for finalization / inclusion, the response is ``true``. """ # Validate destination address. if not is_valid_bittensor_address_or_public_key(dest): diff --git a/bittensor/extrinsics/unstaking.py b/bittensor/extrinsics/unstaking.py index a4a8e3c665..b2c19c876d 100644 --- a/bittensor/extrinsics/unstaking.py +++ b/bittensor/extrinsics/unstaking.py @@ -32,26 +32,24 @@ def __do_remove_stake_single( wait_for_finalization: bool = False, ) -> bool: r""" - Executes an unstake call to the chain using the wallet and amount specified. + Executes an unstake call to the chain using the wallet and the amount specified. + Args: wallet (bittensor.wallet): Bittensor wallet object. hotkey_ss58 (str): Hotkey address to unstake from. amount (bittensor.Balance): - Amount to unstake as bittensor balance object. + Amount to unstake as Bittensor balance object. wait_for_inclusion (bool): - If set, waits for the extrinsic to enter a block before returning true, - or returns false if the extrinsic fails to enter the block within the timeout. + If set, waits for the extrinsic to enter a block before returning ``true``, or returns ``false`` if the extrinsic fails to enter the block within the timeout. wait_for_finalization (bool): - If set, waits for the extrinsic to be finalized on the chain before returning true, - or returns false if the extrinsic fails to be finalized within the timeout. + If set, waits for the extrinsic to be finalized on the chain before returning ``true``, or returns ``false`` if the extrinsic fails to be finalized within the timeout. prompt (bool): - If true, the call waits for confirmation from the user before proceeding. + If ``true``, the call waits for confirmation from the user before proceeding. Returns: success (bool): - flag is true if extrinsic was finalized or uncluded in the block. - If we did not wait for finalization / inclusion, the response is true. + Flag is ``true`` if extrinsic was finalized or uncluded in the block. If we did not wait for finalization / inclusion, the response is ``true``. Raises: bittensor.errors.StakeError: If the extrinsic fails to be finalized or included in the block. @@ -82,27 +80,24 @@ def unstake_extrinsic( wait_for_finalization: bool = False, prompt: bool = False, ) -> bool: - r"""Removes stake into the wallet coldkey from the specified hotkey uid. + r"""Removes stake into the wallet coldkey from the specified hotkey ``uid``. + Args: wallet (bittensor.wallet): - bittensor wallet object. + Bittensor wallet object. hotkey_ss58 (Optional[str]): - ss58 address of the hotkey to unstake from. - by default, the wallet hotkey is used. + The ``ss58`` address of the hotkey to unstake from. By default, the wallet hotkey is used. amount (Union[Balance, float]): - Amount to stake as bittensor balance, or float interpreted as tao. + Amount to stake as Bittensor balance, or ``float`` interpreted as Tao. wait_for_inclusion (bool): - if set, waits for the extrinsic to enter a block before returning true, - or returns false if the extrinsic fails to enter the block within the timeout. + If set, waits for the extrinsic to enter a block before returning ``true``, or returns ``false`` if the extrinsic fails to enter the block within the timeout. wait_for_finalization (bool): - if set, waits for the extrinsic to be finalized on the chain before returning true, - or returns false if the extrinsic fails to be finalized within the timeout. + If set, waits for the extrinsic to be finalized on the chain before returning ``true``, or returns ``false`` if the extrinsic fails to be finalized within the timeout. prompt (bool): - If true, the call waits for confirmation from the user before proceeding. + If ``true``, the call waits for confirmation from the user before proceeding. Returns: success (bool): - flag is true if extrinsic was finalized or uncluded in the block. - If we did not wait for finalization / inclusion, the response is true. + Flag is ``true`` if extrinsic was finalized or uncluded in the block. If we did not wait for finalization / inclusion, the response is ``true``. """ # Decrypt keys, wallet.coldkey @@ -220,27 +215,24 @@ def unstake_multiple_extrinsic( wait_for_finalization: bool = False, prompt: bool = False, ) -> bool: - r"""Removes stake from each hotkey_ss58 in the list, using each amount, to a common coldkey. + r"""Removes stake from each ``hotkey_ss58`` in the list, using each amount, to a common coldkey. + Args: wallet (bittensor.wallet): The wallet with the coldkey to unstake to. hotkey_ss58s (List[str]): List of hotkeys to unstake from. amounts (List[Union[Balance, float]]): - List of amounts to unstake. If None, unstake all. + List of amounts to unstake. If ``None``, unstake all. wait_for_inclusion (bool): - if set, waits for the extrinsic to enter a block before returning true, - or returns false if the extrinsic fails to enter the block within the timeout. + If set, waits for the extrinsic to enter a block before returning ``true``, or returns ``false`` if the extrinsic fails to enter the block within the timeout. wait_for_finalization (bool): - if set, waits for the extrinsic to be finalized on the chain before returning true, - or returns false if the extrinsic fails to be finalized within the timeout. + If set, waits for the extrinsic to be finalized on the chain before returning ``true``, or returns ``false`` if the extrinsic fails to be finalized within the timeout. prompt (bool): - If true, the call waits for confirmation from the user before proceeding. + If ``true``, the call waits for confirmation from the user before proceeding. Returns: success (bool): - flag is true if extrinsic was finalized or included in the block. - flag is true if any wallet was unstaked. - If we did not wait for finalization / inclusion, the response is true. + Flag is ``true`` if extrinsic was finalized or included in the block. Flag is ``true`` if any wallet was unstaked. If we did not wait for finalization / inclusion, the response is ``true``. """ if not isinstance(hotkey_ss58s, list) or not all( isinstance(hotkey_ss58, str) for hotkey_ss58 in hotkey_ss58s diff --git a/bittensor/metagraph.py b/bittensor/metagraph.py index 3adca1f112..a1e8467adf 100644 --- a/bittensor/metagraph.py +++ b/bittensor/metagraph.py @@ -27,7 +27,7 @@ def get_save_dir(network: str, netuid: int) -> str: """ - Return directory path from network and netuid. + Return directory path from ``network`` and ``netuid``. Args: network (str): Network name. @@ -70,69 +70,59 @@ def latest_block_path(dir_path: str) -> int: class metagraph(torch.nn.Module): """ - The metagraph class is a core component of the Bittensor network, representing the neural graph - that forms the backbone of the decentralized machine learning system. It is a dynamic representation - of the network's state, capturing the interconnectedness and attributes of neurons (participants) - in the Bittensor ecosystem. This class is not just a static structure but a live reflection of the - network, and can should be constantly synchronized with the state of the blockchain. - - In Bittensor, neurons are akin to nodes in a distributed system, each contributing computational - resources and participating in the network's collective intelligence. The metagraph tracks various - attributes of these neurons, such as stake, trust, and consensus, which are crucial for the network's - incentive mechanisms and the Yuma Consensus algorithm as outlined in the NeurIPS paper. These attributes + The metagraph class is a core component of the Bittensor network, representing the neural graph that forms the backbone of the decentralized machine learning system. + + The metagraph is a dynamic representation of the network's state, capturing the interconnectedness and attributes of neurons (participants) in the Bittensor ecosystem. This class is not just a static structure but a live reflection of the network, constantly updated and synchronized with the state of the blockchain. + + In Bittensor, neurons are akin to nodes in a distributed system, each contributing computational resources and participating in the network's collective intelligence. The metagraph tracks various attributes of these neurons, such as stake, trust, and consensus, which are crucial for the network's incentive mechanisms and the Yuma Consensus algorithm as outlined in the `NeurIPS paper `_. These attributes govern how neurons interact, how they are incentivized, and their roles within the network's decision-making processes. - Attributes: - netuid (int): A unique identifier that distinguishes between different instances or versions - of the Bittensor network. - network (str): The name of the network, signifying specific configurations or iterations within - the Bittensor ecosystem. - version (torch.nn.Parameter): The version number of the network, formatted for compatibility with - PyTorch models, integral for tracking network updates. + Args: + netuid (int): A unique identifier that distinguishes between different instances or versions of the Bittensor network. + network (str): The name of the network, signifying specific configurations or iterations within the Bittensor ecosystem. + version (torch.nn.parameter.Parameter): The version number of the network, formatted for compatibility with PyTorch models, integral for tracking network updates. n (torch.nn.Parameter): The total number of neurons in the network, reflecting its size and complexity. - block (torch.nn.Parameter): The current block number in the blockchain, crucial for synchronizing - with the network's latest state. - stake, total_stake, ranks, trust, consensus, validator_trust, incentive, emission, dividends, - active, last_update, validator_permit, weights, bonds, uids (torch.nn.Parameter): - - Stake: Represents the amount of Tao staked by neurons, impacting their influence and - earnings within the network. - - Total Stake: The cumulative stake across all neurons. - - Ranks: Neuron rankings as per the Yuma Consensus algorithm, influencing their incentive - distribution and network authority. - - Trust: Scores indicating the reliability of neurons, mainly miners, within the network's - operational context. - - Consensus: Scores reflecting each neuron's alignment with the network's collective decisions. - - Validator Trust: Trust scores for validator neurons, crucial for network security and validation. - - Incentive: Rewards allocated to neurons, particularly miners, for their network contributions. - - Emission: The rate at which rewards are distributed to neurons. - - Dividends: Rewards received primarily by validators as part of the incentive mechanism. - - Active: Status indicating whether a neuron is actively participating in the network. - - Last Update: Timestamp of the latest update to a neuron's data. - - Validator Permit: Indicates if a neuron is authorized to act as a validator. - - Weights: Inter-neuronal weights set by each neuron, influencing network dynamics. - - Bonds: Represents speculative investments by neurons in others, part of the reward mechanism. - - UIDs: Unique identifiers for each neuron, essential for network operations. + block (torch.nn.Parameter): The current block number in the blockchain, crucial for synchronizing with the network's latest state. + stake: Represents the cryptocurrency staked by neurons, impacting their influence and earnings within the network. + total_stake: The cumulative stake across all neurons. + ranks: Neuron rankings as per the Yuma Consensus algorithm, influencing their incentive distribution and network authority. + trust: Scores indicating the reliability of neurons, mainly miners, within the network's operational context. + consensus: Scores reflecting each neuron's alignment with the network's collective decisions. + validator_trust: Trust scores for validator neurons, crucial for network security and validation. + incentive: Rewards allocated to neurons, particularly miners, for their network contributions. + emission: The rate at which rewards are distributed to neurons. + dividends: Rewards received primarily by validators as part of the incentive mechanism. + active: Status indicating whether a neuron is actively participating in the network. + last_update: Timestamp of the latest update to a neuron's data. + validator_permit: Indicates if a neuron is authorized to act as a validator. + weights: Inter-neuronal weights set by each neuron, influencing network dynamics. + bonds: Represents speculative investments by neurons in others, part of the reward mechanism. + uids: Unique identifiers for each neuron, essential for network operations. axons (List): Details about each neuron's axon, critical for facilitating network communication. - The metagraph plays a pivotal role in Bittensor's decentralized AI operations, influencing everything - from data propagation to reward distribution. It embodies the principles of decentralized governance + The metagraph plays a pivotal role in Bittensor's decentralized AI operations, influencing everything from data propagation to reward distribution. It embodies the principles of decentralized governance and collaborative intelligence, ensuring that the network remains adaptive, secure, and efficient. Example Usage: - # Initializing the metagraph to represent the current state of the Bittensor network. - metagraph = bt.metagraph(netuid=config.netuid, network=subtensor.network, sync=False) - - # Synchronizing the metagraph with the network to reflect the latest state and neuron data. - metagraph.sync(subtensor=subtensor) - - # Accessing metagraph properties to inform network interactions and decisions. - total_stake = metagraph.S - neuron_ranks = metagraph.R - neuron_incentives = metagraph.I - ... - # Maintaining a local copy of hotkeys for querying and interacting with network entities. - hotkeys = deepcopy(metagraph.hotkeys) + Initializing the metagraph to represent the current state of the Bittensor network:: + + metagraph = bt.metagraph(netuid=config.netuid, network=subtensor.network, sync=False) + + Synchronizing the metagraph with the network to reflect the latest state and neuron data:: + + metagraph.sync(subtensor=subtensor) + + Accessing metagraph properties to inform network interactions and decisions:: + + total_stake = metagraph.S + neuron_ranks = metagraph.R + neuron_incentives = metagraph.I + ... + + Maintaining a local copy of hotkeys for querying and interacting with network entities:: + + hotkeys = deepcopy(metagraph.hotkeys) """ @property @@ -144,8 +134,7 @@ def S(self) -> torch.FloatTensor: from the network, playing a crucial role in the distribution of incentives and decision-making processes. Returns: - torch.FloatTensor: A tensor representing the stake of each neuron in the network. Higher values - signify a greater stake held by the respective neuron. + torch.FloatTensor: A tensor representing the stake of each neuron in the network. Higher values signify a greater stake held by the respective neuron. """ return self.total_stake @@ -158,8 +147,7 @@ def R(self) -> torch.FloatTensor: incentives within the network, with higher-ranked neurons receiving more incentive. Returns: - torch.FloatTensor: A tensor where each element represents the rank of a neuron. Higher values - indicate higher ranks within the network. + torch.FloatTensor: A tensor where each element represents the rank of a neuron. Higher values indicate higher ranks within the network. """ return self.ranks @@ -172,8 +160,7 @@ def I(self) -> torch.FloatTensor: trusted contributions are incentivized. Returns: - torch.FloatTensor: A tensor of incentive values, indicating the rewards or benefits accrued by each - neuron based on their contributions and network consensus. + torch.FloatTensor: A tensor of incentive values, indicating the rewards or benefits accrued by each neuron based on their contributions and network consensus. """ return self.incentive @@ -181,13 +168,12 @@ def I(self) -> torch.FloatTensor: def E(self) -> torch.FloatTensor: """ Denotes the emission values of neurons in the Bittensor network. Emissions refer to the distribution or - release of rewards (often in the form of the Tao token) to neurons, typically based on their stake and + release of rewards (often in the form of cryptocurrency) to neurons, typically based on their stake and performance. This mechanism is central to the network's incentive model, ensuring that active and contributing neurons are appropriately rewarded. Returns: - torch.FloatTensor: A tensor where each element represents the emission value for a neuron, indicating - the amount of reward distributed to that neuron. + torch.FloatTensor: A tensor where each element represents the emission value for a neuron, indicating the amount of reward distributed to that neuron. """ return self.emission @@ -201,8 +187,7 @@ def C(self) -> torch.FloatTensor: are more widely trusted and valued across the network. Returns: - torch.FloatTensor: A tensor of consensus values, where each element reflects the level of trust and - agreement a neuron has achieved within the network. + torch.FloatTensor: A tensor of consensus values, where each element reflects the level of trust and agreement a neuron has achieved within the network. """ return self.consensus @@ -219,8 +204,7 @@ def T(self) -> torch.FloatTensor: has in others. A higher value in the trust matrix suggests a stronger trust relationship between neurons. Returns: - torch.FloatTensor: A tensor of trust values, where each element represents the trust level of a neuron. - Higher values denote a higher level of trust within the network. + torch.FloatTensor: A tensor of trust values, where each element represents the trust level of a neuron. Higher values denote a higher level of trust within the network. """ return self.trust @@ -236,8 +220,7 @@ def Tv(self) -> torch.FloatTensor: determining the validators' influence and responsibilities in these critical functions. Returns: - torch.FloatTensor: A tensor of validator trust values, specifically applicable to neurons serving as - validators, where higher values denote greater trustworthiness in their validation roles. + torch.FloatTensor: A tensor of validator trust values, specifically applicable to neurons serving as validators, where higher values denote greater trustworthiness in their validation roles. """ return self.validator_trust @@ -249,8 +232,7 @@ def D(self) -> torch.FloatTensor: They are an integral part of the network's incentive structure, encouraging active and beneficial participation. Returns: - torch.FloatTensor: A tensor of dividend values, where each element indicates the dividends received by - a neuron, reflecting their share of network rewards. + torch.FloatTensor: A tensor of dividend values, where each element indicates the dividends received by a neuron, reflecting their share of network rewards. """ return self.dividends @@ -263,8 +245,7 @@ def B(self) -> torch.FloatTensor: among neurons while providing an additional layer of incentive. Returns: - torch.FloatTensor: A tensor representing the bonds held by each neuron, where each value signifies - the proportion of bonds owned by one neuron in another. + torch.FloatTensor: A tensor representing the bonds held by each neuron, where each value signifies the proportion of bonds owned by one neuron in another. """ return self.bonds @@ -276,48 +257,43 @@ def W(self) -> torch.FloatTensor: for setting its weights, which are then recorded on a digital ledger. These weights are reflective of the neuron's assessment or judgment of other neurons in the network. - The weight matrix W = [w_ij] is a key component of the network's architecture, where the ith row is set by - neuron i and represents its weights towards other neurons. These weights influence the ranking and incentive + The weight matrix :math:`W = [w_{ij}]` is a key component of the network's architecture, where the :math:`i^{th}` row is set by + neuron :math:`i` and represents its weights towards other neurons. These weights influence the ranking and incentive mechanisms within the network. Higher weights from a neuron towards another can imply greater trust or value placed on that neuron's contributions. Returns: - torch.FloatTensor: A tensor of inter-peer weights, where each element wij represents the weight assigned - by neuron i to neuron j. This matrix is fundamental to the network's functioning, - influencing the distribution of incentives and the inter-neuronal dynamics. + torch.FloatTensor: A tensor of inter-peer weights, where each element :math:`w_{ij}` represents the weight assigned by neuron :math:`i` to neuron :math:`j`. This matrix is fundamental to the network's functioning, influencing the distribution of incentives and the inter-neuronal dynamics. """ return self.weights @property def hotkeys(self) -> List[str]: """ - Represents a list of 'hotkeys' for each neuron in the Bittensor network. Hotkeys are unique identifiers - used by neurons for active participation in the network, such as sending and receiving information or - transactions. They are akin to public keys in cryptographic systems and are essential for identifying - and authenticating neurons within the network's operations. + Represents a list of ``hotkeys`` for each neuron in the Bittensor network. + + Hotkeys are unique identifiers used by neurons for active participation in the network, such as sending and receiving information or + transactions. They are akin to public keys in cryptographic systems and are essential for identifying and authenticating neurons within the network's operations. Returns: List[str]: A list of hotkeys, with each string representing the hotkey of a corresponding neuron. - These keys are crucial for the network's security and integrity, ensuring proper - identification and authorization of network participants. + + These keys are crucial for the network's security and integrity, ensuring proper identification and authorization of network participants. Note: - While the NeurIPS paper may not explicitly detail the concept of hotkeys, they are a fundamental aspect - of decentralized networks for secure and authenticated interactions. + While the `NeurIPS paper `_ may not explicitly detail the concept of hotkeys, they are a fundamental of decentralized networks for secure and authenticated interactions. """ return [axon.hotkey for axon in self.axons] @property def coldkeys(self) -> List[str]: """ - Contains a list of 'coldkeys' for each neuron in the Bittensor network. Coldkeys are similar to hotkeys - but are typically used for more secure, offline activities such as storing assets or offline signing of - transactions. They are an important aspect of a neuron's security, providing an additional layer of - protection for sensitive operations and assets. + Contains a list of ``coldkeys`` for each neuron in the Bittensor network. + + Coldkeys are similar to hotkeys but are typically used for more secure, offline activities such as storing assets or offline signing of transactions. They are an important aspect of a neuron's security, providing an additional layer of protection for sensitive operations and assets. Returns: - List[str]: A list of coldkeys, each string representing the coldkey of a neuron. These keys play a - vital role in the secure management of assets and sensitive operations within the network. + List[str]: A list of coldkeys, each string representing the coldkey of a neuron. These keys play a vital role in the secure management of assets and sensitive operations within the network. Note: The concept of coldkeys, while not explicitly covered in the NeurIPS paper, is a standard practice in @@ -333,31 +309,27 @@ def addresses(self) -> List[str]: IP addresses are fundamental for the network's peer-to-peer communication infrastructure. Returns: - List[str]: A list of IP addresses, with each string representing the address of a neuron. These - addresses enable the decentralized, distributed nature of the network, facilitating - direct communication and data exchange among neurons. + List[str]: A list of IP addresses, with each string representing the address of a neuron. These addresses enable the decentralized, distributed nature of the network, facilitating direct communication and data exchange among neurons. Note: While IP addresses are a basic aspect of network communication, specific details about their use in - the Bittensor network may not be covered in the NeurIPS paper. They are, however, integral to the + the Bittensor network may not be covered in the `NeurIPS paper `_. They are, however, integral to the functioning of any distributed network. """ return [axon.ip_str() for axon in self.axons] def __str__(self) -> str: """ - Provides a human-readable string representation of the metagraph object. This representation - includes key identifiers and attributes of the metagraph, making it easier to quickly understand + Provides a human-readable string representation of the metagraph object. This representation includes key identifiers and attributes of the metagraph, making it easier to quickly understand the state and configuration of the metagraph in a simple format. Returns: - str: A string that succinctly represents the metagraph, including its network UID, the total - number of neurons (n), the current block number, and the network's name. This format is - particularly useful for logging, debugging, and displaying the metagraph in a concise manner. + str: A string that succinctly represents the metagraph, including its network UID, the total number of neurons (n), the current block number, and the network's name. This format is particularly useful for logging, debugging, and displaying the metagraph in a concise manner. Example: - # When printing the metagraph object or using it in a string context, this method is automatically invoked. - print(metagraph) # Output: "metagraph(netuid:1, n:100, block:500, network:finney)" + When printing the metagraph object or using it in a string context, this method is automatically invoked:: + + print(metagraph) # Output: "metagraph(netuid:1, n:100, block:500, network:finney)" """ return "metagraph(netuid:{}, n:{}, block:{}, network:{})".format( self.netuid, self.n.item(), self.block.item(), self.network @@ -365,39 +337,38 @@ def __str__(self) -> str: def __repr__(self) -> str: """ - Provides a detailed string representation of the metagraph object, intended for unambiguous - understanding and debugging purposes. This method simply calls the `__str__` method, ensuring + Provides a detailed string representation of the metagraph object, intended for unambiguous understanding and debugging purposes. This method simply calls the :func:`__str__` method, ensuring consistency between the informal and formal string representations of the metagraph. Returns: - str: The same string representation as provided by the `__str__` method, detailing the metagraph's - key attributes including network UID, number of neurons, block number, and network name. + str: The same string representation as provided by the :func:`__str__` method, detailing the metagraph's key attributes including network UID, number of neurons, block number, and network name. Example: - # The __repr__ output can be used in debugging to get a clear and concise description of the metagraph. - metagraph_repr = repr(metagraph) - print(metagraph_repr) # Output mirrors that of __str__ + The :func:`__repr__` output can be used in debugging to get a clear and concise description of the metagraph:: + + metagraph_repr = repr(metagraph) + print(metagraph_repr) # Output mirrors that of __str__ """ return self.__str__() def metadata(self) -> dict: """ Retrieves the metadata of the metagraph, providing key information about the current state of the - Bittensor network. This metadata includes details such as the network's unique identifier (netuid), - the total number of neurons (n), the current block number, the network's name, and the version of + Bittensor network. This metadata includes details such as the network's unique identifier (``netuid``), + the total number of neurons (``n``), the current block number, the network's name, and the version of the Bittensor network. Returns: dict: A dictionary containing essential metadata about the metagraph, including: - - 'netuid': The unique identifier for the network. - - 'n': The total number of neurons in the network. - - 'block': The current block number in the network's blockchain. - - 'network': The name of the Bittensor network. - - 'version': The version number of the Bittensor software. + + - ``netuid``: The unique identifier for the network. + - ``n``: The total number of neurons in the network. + - ``block``: The current block number in the network's blockchain. + - ``network``: The name of the Bittensor network. + - ``version``: The version number of the Bittensor software. Note: - This metadata is crucial for understanding the current state and configuration of the network, - as well as for tracking its evolution over time. + This metadata is crucial for understanding the current state and configuration of the network, as well as for tracking its evolution over time. """ return { "netuid": self.netuid, @@ -411,24 +382,21 @@ def __init__( self, netuid: int, network: str = "finney", lite: bool = True, sync: bool = True ) -> "metagraph": """ - Initializes a new instance of the metagraph object, setting up the basic structure and parameters - based on the provided arguments. This method is the entry point for creating a metagraph object, + Initializes a new instance of the metagraph object, setting up the basic structure and parameters based on the provided arguments. + + This method is the entry point for creating a metagraph object, which is a central component in representing the state of the Bittensor network. Args: - netuid (int): The unique identifier for the network, distinguishing this instance of the metagraph - within potentially multiple network configurations. - network (str): The name of the network, which can indicate specific configurations or versions - of the Bittensor network. - lite (bool): A flag indicating whether to use a lite version of the metagraph. The lite version - may contain less detailed information but can be quicker to initialize and sync. - sync (bool): A flag indicating whether to synchronize the metagraph with the network upon initialization. - Synchronization involves updating the metagraph's parameters to reflect the current state - of the network. + netuid (int): The unique identifier for the network, distinguishing this instance of the metagraph within potentially multiple network configurations. + network (str): The name of the network, which can indicate specific configurations or versions of the Bittensor network. + lite (bool): A flag indicating whether to use a lite version of the metagraph. The lite version may contain less detailed information but can be quicker to initialize and sync. + sync (bool): A flag indicating whether to synchronize the metagraph with the network upon initialization. Synchronization involves updating the metagraph's parameters to reflect the current state of the network. Example: - # Initializing a metagraph object for the Bittensor network with a specific network UID. - metagraph = metagraph(netuid=123, network="finney", lite=True, sync=True) + Initializing a metagraph object for the Bittensor network with a specific network UID:: + + metagraph = metagraph(netuid=123, network="finney", lite=True, sync=True) """ super(metagraph, self).__init__() self.netuid = netuid @@ -515,20 +483,21 @@ def sync( metagraph: The metagraph instance, updated to the state of the specified block or the latest network state. Example: - # Setup subtensor (ideally local) to sync the metagraph with the latest block from the subtensor. - subtensor = bittensor.subtensor(network='local') + Sync the metagraph with the latest block from the subtensor, using the lite version for efficiency:: - # Sync the metagraph with the latest block from the subtensor, using the lite version for efficiency. - metagraph.sync(subtensor=subtensor) + metagraph.sync(subtensor=subtensor) - # Sync with a specific block number for detailed analysis. - metagraph.sync(block=12345, lite=False, subtensor=subtensor) + Sync with a specific block number for detailed analysis:: - NOTE: If attempting to access data beyond the previous 300 blocks, you **must** use the `archive` network for subtensor. - Light nodes are configured only to store the previous 300 blocks if connecting to finney or test networks. + metagraph.sync(block=12345, lite=False, subtensor=subtensor) - For example: - subtensor = bittensor.subtensor(network='archive') + NOTE: + If attempting to access data beyond the previous 300 blocks, you **must** use the ``archive`` network for subtensor. + Light nodes are configured only to store the previous 300 blocks if connecting to finney or test networks. + + For example:: + + subtensor = bittensor.subtensor(network='archive') """ # Initialize subtensor subtensor = self._initialize_subtensor(subtensor) @@ -545,22 +514,22 @@ def sync( def _initialize_subtensor(self, subtensor): """ - Initializes the subtensor to be used for syncing the metagraph. This method ensures that a subtensor - instance is available and properly set up for data retrieval during the synchronization process. + Initializes the subtensor to be used for syncing the metagraph. + + This method ensures that a subtensor instance is available and properly set up for data retrieval during the synchronization process. - If no subtensor is provided, this method is responsible for creating a new instance of the subtensor, - configured according to the current network settings. + If no subtensor is provided, this method is responsible for creating a new instance of the subtensor, configured according to the current network settings. Args: - subtensor: The subtensor instance provided for initialization. If None, a new subtensor - instance is created using the current network configuration. + subtensor: The subtensor instance provided for initialization. If ``None``, a new subtensor instance is created using the current network configuration. Returns: subtensor: The initialized subtensor instance, ready to be used for syncing the metagraph. Internal Usage: - # Used internally during the sync process to ensure a valid subtensor instance is available. - subtensor = self._initialize_subtensor(subtensor) + Used internally during the sync process to ensure a valid subtensor instance is available:: + + subtensor = self._initialize_subtensor(subtensor) """ if not subtensor: # TODO: Check and test the initialization of the new subtensor @@ -569,20 +538,19 @@ def _initialize_subtensor(self, subtensor): def _assign_neurons(self, block, lite, subtensor): """ - Assigns neurons to the metagraph based on the provided block number and the lite flag. This method - is responsible for fetching and setting the neuron data in the metagraph, which includes neuron - attributes like UID, stake, trust, and other relevant information. + Assigns neurons to the metagraph based on the provided block number and the lite flag. + + This method is responsible for fetching and setting the neuron data in the metagraph, which includes neuron attributes like UID, stake, trust, and other relevant information. Args: - block: The block number for which the neuron data needs to be fetched. If None, the latest block - data is used. - lite: A boolean flag indicating whether to use a lite version of the neuron data. The lite version - typically includes essential information and is quicker to fetch and process. + block: The block number for which the neuron data needs to be fetched. If ``None``, the latest block data is used. + lite: A boolean flag indicating whether to use a lite version of the neuron data. The lite version typically includes essential information and is quicker to fetch and process. subtensor: The subtensor instance used for fetching neuron data from the network. Internal Usage: - # Used internally during the sync process to fetch and set neuron data. - self._assign_neurons(block, lite, subtensor) + Used internally during the sync process to fetch and set neuron data:: + + self._assign_neurons(block, lite, subtensor) """ # TODO: Check and test the conditions for assigning neurons if lite: @@ -594,17 +562,17 @@ def _assign_neurons(self, block, lite, subtensor): def _set_metagraph_attributes(self, block, subtensor): """ Sets various attributes of the metagraph based on the latest network data fetched from the subtensor. - This method updates parameters like the number of neurons, block number, stakes, trusts, ranks, and other - neuron-specific information. + + This method updates parameters like the number of neurons, block number, stakes, trusts, ranks, and other neuron-specific information. Args: - block: The block number for which the metagraph attributes need to be set. If None, the latest block - data is used. + block: The block number for which the metagraph attributes need to be set. If ``None``, the latest block data is used. subtensor: The subtensor instance used for fetching the latest network data. Internal Usage: - # Used internally during the sync process to update the metagraph's attributes. - self._set_metagraph_attributes(block, subtensor) + Used internally during the sync process to update the metagraph's attributes:: + + self._set_metagraph_attributes(block, subtensor) """ # TODO: Check and test the setting of each attribute self.n = self._create_tensor(len(self.neurons), dtype=torch.int64) @@ -657,37 +625,35 @@ def _set_metagraph_attributes(self, block, subtensor): def _create_tensor(self, data, dtype) -> torch.nn.Parameter: """ - Creates a tensor parameter with the given data and data type. This method is a utility function used - internally to encapsulate data into a PyTorch tensor, making it compatible with the metagraph's PyTorch + Creates a tensor parameter with the given data and data type. This method is a utility function used internally to encapsulate data into a PyTorch tensor, making it compatible with the metagraph's PyTorch model structure. Args: data: The data to be included in the tensor. This could be any numeric data, like stakes, ranks, etc. - dtype: The data type for the tensor, typically a PyTorch data type like torch.float32 or torch.int64. + dtype: The data type for the tensor, typically a PyTorch data type like ``torch.float32`` or ``torch.int64``. Returns: A tensor parameter encapsulating the provided data. Internal Usage: - # Used internally to create tensor parameters for various metagraph attributes. - self.stake = self._create_tensor(neuron_stakes, dtype=torch.float32) + Used internally to create tensor parameters for various metagraph attributes:: + + self.stake = self._create_tensor(neuron_stakes, dtype=torch.float32) """ # TODO: Check and test the creation of tensor return torch.nn.Parameter(torch.tensor(data, dtype=dtype), requires_grad=False) def _set_weights_and_bonds(self, subtensor: bittensor.subtensor = None): """ - Computes and sets the weights and bonds for each neuron in the metagraph. This method is responsible for - processing the raw weight and bond data obtained from the network and converting it into a structured format - suitable for the metagraph model. + Computes and sets the weights and bonds for each neuron in the metagraph. This method is responsible for processing the raw weight and bond data obtained from the network and converting it into a structured format suitable for the metagraph model. Args: - subtensor: The subtensor instance used for fetching weights and bonds data. If None, the weights and - bonds are not updated. + subtensor: The subtensor instance used for fetching weights and bonds data. If ``None``, the weights and bonds are not updated. Internal Usage: - # Used internally during the sync process to update the weights and bonds of the neurons. - self._set_weights_and_bonds(subtensor=subtensor) + Used internally during the sync process to update the weights and bonds of the neurons:: + + self._set_weights_and_bonds(subtensor=subtensor) """ # TODO: Check and test the computation of weights and bonds if self.netuid == 0: @@ -704,21 +670,19 @@ def _set_weights_and_bonds(self, subtensor: bittensor.subtensor = None): def _process_weights_or_bonds(self, data, attribute: str) -> torch.nn.Parameter: """ - Processes the raw weights or bonds data and converts it into a structured tensor format. This method handles - the transformation of neuron connection data (weights or bonds) from a list or other unstructured format - into a tensor that can be utilized within the metagraph model. + Processes the raw weights or bonds data and converts it into a structured tensor format. This method handles the transformation of neuron connection data (``weights`` or ``bonds``) from a list or other unstructured format into a tensor that can be utilized within the metagraph model. Args: data: The raw weights or bonds data to be processed. This data typically comes from the subtensor. - attribute: A string indicating whether the data is 'weights' or 'bonds', which determines the - specific processing steps to be applied. + attribute: A string indicating whether the data is ``weights`` or ``bonds``, which determines the specific processing steps to be applied. Returns: A tensor parameter encapsulating the processed weights or bonds data. Internal Usage: - # Used internally to process and set weights or bonds for the neurons. - self.weights = self._process_weights_or_bonds(raw_weights_data, "weights") + Used internally to process and set weights or bonds for the neurons:: + + self.weights = self._process_weights_or_bonds(raw_weights_data, "weights") """ data_array = [] for item in data: @@ -754,20 +718,23 @@ def _process_root_weights( self, data, attribute: str, subtensor: bittensor.subtensor ) -> torch.nn.Parameter: """ - Specifically processes the root weights data for the metagraph. This method is similar to _process_weights_or_bonds - but is tailored for processing root weights, which have a different structure and significance in the network. + Specifically processes the root weights data for the metagraph. This method is similar to :func:`_process_weights_or_bonds` but is tailored for processing root weights, which have a different structure and significance in the network. Args: data: The raw root weights data to be processed. - attribute: A string indicating the attribute type, here it's typically 'weights'. + attribute: A string indicating the attribute type, here it's typically ``weights``. subtensor: The subtensor instance used for additional data and context needed in processing. Returns: A tensor parameter encapsulating the processed root weights data. Internal Usage: - # Used internally to process and set root weights for the metagraph. - self.root_weights = self._process_root_weights(raw_root_weights_data, "weights", subtensor) + Used internally to process and set root weights for the metagraph:: + + self.root_weights = self._process_root_weights( + raw_root_weights_data, "weights", subtensor + ) + """ data_array = [] n_subnets = subtensor.get_total_subnets() @@ -797,24 +764,25 @@ def _process_root_weights( def save(self) -> "metagraph": """ - Saves the current state of the metagraph to a file on disk. This function is crucial for persisting the current - state of the network's metagraph, which can later be reloaded or analyzed. The save operation includes all neuron - attributes and parameters, ensuring a complete snapshot of the metagraph's state. + Saves the current state of the metagraph to a file on disk. This function is crucial for persisting the current state of the network's metagraph, which can later be reloaded or analyzed. The save operation includes all neuron attributes and parameters, ensuring a complete snapshot of the metagraph's state. Returns: metagraph: The metagraph instance after saving its state. Example: - # Save the current state of the metagraph to the default directory. - metagraph.save() + Save the current state of the metagraph to the default directory:: - # The saved state can later be loaded to restore or analyze the metagraph's state at this point. + metagraph.save() - # If using the default save path - metagraph.load() + The saved state can later be loaded to restore or analyze the metagraph's state at this point. - # If using a custom save path - metagraph.load_from_path(dir_path) + If using the default save path:: + + metagraph.load() + + If using a custom save path:: + + metagraph.load_from_path(dir_path) """ save_directory = get_save_dir(self.network, self.netuid) os.makedirs(save_directory, exist_ok=True) @@ -827,62 +795,50 @@ def save(self) -> "metagraph": def load(self) -> "metagraph": """ - Loads the state of the metagraph from the default save directory. This method is instrumental for restoring - the metagraph to its last saved state. It automatically identifies the save directory based on the network - and netuid properties of the metagraph, locates the latest block file in that directory, and loads all - metagraph parameters from it. + Loads the state of the metagraph from the default save directory. This method is instrumental for restoring the metagraph to its last saved state. It automatically identifies the save directory based on the ``network`` and ``netuid`` properties of the metagraph, locates the latest block file in that directory, and loads all metagraph parameters from it. This functionality is particularly beneficial when continuity in the state of the metagraph is necessary across different runtime sessions, or after a restart of the system. It ensures that the metagraph reflects the exact state it was in at the last save point, maintaining consistency in the network's representation. - The method delegates to `load_from_path`, supplying it with the directory path constructed from the metagraph's - current network and netuid properties. This abstraction simplifies the process of loading the metagraph's state - for the user, requiring no direct path specifications. + The method delegates to ``load_from_path``, supplying it with the directory path constructed from the metagraph's current ``network`` and ``netuid`` properties. This abstraction simplifies the process of loading the metagraph's state for the user, requiring no direct path specifications. Returns: metagraph: The metagraph instance after loading its state from the default directory. Example: - # Load the metagraph state from the last saved snapshot in the default directory. - metagraph.load() + Load the metagraph state from the last saved snapshot in the default directory:: - # After this operation, the metagraph's parameters and neuron data are restored to their state - # at the time of the last save in the default directory. + metagraph.load() + + After this operation, the metagraph's parameters and neuron data are restored to their state at the time of the last save in the default directory. Note: - The default save directory is determined based on the metagraph's network and netuid attributes. It is - important to ensure that these attributes are set correctly and that the default save directory contains - the appropriate state files for the metagraph. + The default save directory is determined based on the metagraph's ``network`` and ``netuid`` attributes. It is important to ensure that these attributes are set correctly and that the default save directory contains the appropriate state files for the metagraph. """ self.load_from_path(get_save_dir(self.network, self.netuid)) def load_from_path(self, dir_path: str) -> "metagraph": """ - Loads the state of the metagraph from a specified directory path. This method is crucial for restoring - the metagraph to a specific state based on saved data. It locates the latest block file in the given - directory and loads all metagraph parameters from it. This is particularly useful for analyses that - require historical states of the network or for restoring previous states of the metagraph in different + Loads the state of the metagraph from a specified directory path. This method is crucial for restoring the metagraph to a specific state based on saved data. It locates the latest block file in the given + directory and loads all metagraph parameters from it. This is particularly useful for analyses that require historical states of the network or for restoring previous states of the metagraph in different execution environments. - The method first identifies the latest block file in the specified directory, then loads the metagraph state - including neuron attributes and parameters from this file. This ensures that the metagraph is accurately - reconstituted to reflect the network state at the time of the saved block. + The method first identifies the latest block file in the specified directory, then loads the metagraph state including neuron attributes and parameters from this file. This ensures that the metagraph is accurately reconstituted to reflect the network state at the time of the saved block. Args: - dir_path (str): The directory path where the metagraph's state files are stored. This path should - contain one or more saved state files, typically named in a format that includes - the block number. + dir_path (str): The directory path where the metagraph's state files are stored. This path should contain one or more saved state files, typically named in a format that includes the block number. Returns: metagraph: The metagraph instance after loading its state from the specified directory path. Example: - # Load the metagraph state from a specific directory. - dir_path = "/path/to/saved/metagraph/states" - metagraph.load_from_path(dir_path) + Load the metagraph state from a specific directory:: + + dir_path = "/path/to/saved/metagraph/states" + metagraph.load_from_path(dir_path) - # The metagraph is now restored to the state it was in at the time of the latest saved block in the specified directory. + The metagraph is now restored to the state it was in at the time of the latest saved block in the specified directory. Note: This method assumes that the state files in the specified directory are correctly formatted and diff --git a/bittensor/subtensor.py b/bittensor/subtensor.py index 9137679185..2d3c3c464c 100644 --- a/bittensor/subtensor.py +++ b/bittensor/subtensor.py @@ -322,8 +322,10 @@ def __init__( 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'). - Defaults to the main Bittensor network if not specified. + 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. @@ -335,6 +337,18 @@ def __init__( # 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 == None: + bittensor.logging.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 == None: config = subtensor.config() self.config = copy.deepcopy(config) diff --git a/bittensor/wallet.py b/bittensor/wallet.py index 1a770bf230..29a6129ca2 100644 --- a/bittensor/wallet.py +++ b/bittensor/wallet.py @@ -54,9 +54,9 @@ def display_mnemonic_msg(keypair: Keypair, key_type: str): class wallet: """ - The wallet class in the Bittensor framework handles wallet functionality, crucial for participating in - the Bittensor network. It manages two types of keys: coldkey and hotkey, each serving different purposes - in network operations. Each wallet contains a coldkey and a hotkey. + The wallet class in the Bittensor framework handles wallet functionality, crucial for participating in the Bittensor network. + + It manages two types of keys: coldkey and hotkey, each serving different purposes in network operations. Each wallet contains a coldkey and a hotkey. The coldkey is the user's primary key for holding stake in their wallet and is the only way that users can access Tao. Coldkeys can hold tokens and should be encrypted on your device. @@ -69,7 +69,7 @@ class wallet: network. It's linked to the coldkey through the metagraph and does not directly hold tokens, thereby offering a safer way to interact with the network during regular operations. - Attributes: + Args: name (str): The name of the wallet, used to identify it among possibly multiple wallets. path (str): File system path where wallet keys are stored. hotkey_str (str): String identifier for the hotkey. @@ -83,10 +83,10 @@ class wallet: regenerate_coldkey, regenerate_hotkey, regenerate_coldkeypub: Methods to regenerate keys from different sources. config, help, add_args: Utility methods for configuration and assistance. - The wallet class is a fundamental component for users to interact securely with the Bittensor network, - facilitating both operational tasks and transactions involving value transfer across the network. + The wallet class is a fundamental component for users to interact securely with the Bittensor network, facilitating both operational tasks and transactions involving value transfer across the network. + + Example Usage:: - Example Usage: # Create a new wallet with default coldkey and hotkey names my_wallet = wallet() @@ -176,10 +176,10 @@ def __init__( Initialize the bittensor wallet object containing a hot and coldkey. Args: - name (str, optional): The name of the wallet to unlock for running bittensor. Defaults to 'default'. - hotkey (str, optional): The name of hotkey used to running the miner. Defaults to 'default'. - path (str, optional): The path to your bittensor wallets. Defaults to '~/.bittensor/wallets/'. - config (bittensor.config, optional): bittensor.wallet.config(). Defaults to None. + name (str, optional): The name of the wallet to unlock for running bittensor. Defaults to ``default``. + hotkey (str, optional): The name of hotkey used to running the miner. Defaults to ``default``. + path (str, optional): The path to your bittensor wallets. Defaults to ``~/.bittensor/wallets/``. + config (bittensor.config, optional): bittensor.wallet.config(). Defaults to ``None``. """ # Fill config from passed args using command line defaults. if config is None: @@ -214,7 +214,7 @@ def __str__(self): def __repr__(self): """ - Returns the string representation of the Wallet object. + Returns the string representation of the wallet object. Returns: str: The string representation. @@ -225,14 +225,14 @@ def create_if_non_existent( self, coldkey_use_password: bool = True, hotkey_use_password: bool = False ) -> "wallet": """ - Checks for existing coldkeypub and hotkeys and creates them if non-existent. + Checks for existing coldkeypub and hotkeys, and creates them if non-existent. Args: - coldkey_use_password (bool, optional): Whether to use a password for coldkey. Defaults to True. - hotkey_use_password (bool, optional): Whether to use a password for hotkey. Defaults to False. + coldkey_use_password (bool, optional): Whether to use a password for coldkey. Defaults to ``True``. + hotkey_use_password (bool, optional): Whether to use a password for hotkey. Defaults to ``False``. Returns: - wallet: The Wallet object. + wallet: The wallet object. """ return self.create(coldkey_use_password, hotkey_use_password) @@ -240,14 +240,14 @@ def create( self, coldkey_use_password: bool = True, hotkey_use_password: bool = False ) -> "wallet": """ - Checks for existing coldkeypub and hotkeys and creates them if non-existent. + Checks for existing coldkeypub and hotkeys, and creates them if non-existent. Args: - coldkey_use_password (bool, optional): Whether to use a password for coldkey. Defaults to True. - hotkey_use_password (bool, optional): Whether to use a password for hotkey. Defaults to False. + coldkey_use_password (bool, optional): Whether to use a password for coldkey. Defaults to ``True``. + hotkey_use_password (bool, optional): Whether to use a password for hotkey. Defaults to ``False``. Returns: - wallet: The Wallet object. + wallet: The wallet object. """ # ---- Setup Wallet. ---- if ( @@ -266,11 +266,11 @@ def recreate( Checks for existing coldkeypub and hotkeys and creates them if non-existent. Args: - coldkey_use_password (bool, optional): Whether to use a password for coldkey. Defaults to True. - hotkey_use_password (bool, optional): Whether to use a password for hotkey. Defaults to False. + coldkey_use_password (bool, optional): Whether to use a password for coldkey. Defaults to ``True``. + hotkey_use_password (bool, optional): Whether to use a password for hotkey. Defaults to ``False``. Returns: - wallet: The Wallet object. + wallet: The wallet object. """ # ---- Setup Wallet. ---- self.create_new_coldkey(n_words=12, use_password=coldkey_use_password) @@ -324,8 +324,8 @@ def set_hotkey( Args: keypair (bittensor.Keypair): The hotkey keypair. - encrypt (bool, optional): Whether to encrypt the hotkey. Defaults to False. - overwrite (bool, optional): Whether to overwrite an existing hotkey. Defaults to False. + encrypt (bool, optional): Whether to encrypt the hotkey. Defaults to ``False``. + overwrite (bool, optional): Whether to overwrite an existing hotkey. Defaults to ``False``. Returns: bittensor.keyfile: The hotkey file. @@ -344,8 +344,8 @@ def set_coldkeypub( Args: keypair (bittensor.Keypair): The coldkeypub keypair. - encrypt (bool, optional): Whether to encrypt the coldkeypub. Defaults to False. - overwrite (bool, optional): Whether to overwrite an existing coldkeypub. Defaults to False. + encrypt (bool, optional): Whether to encrypt the coldkeypub. Defaults to ``False``. + overwrite (bool, optional): Whether to overwrite an existing coldkeypub. Defaults to ``False``. Returns: bittensor.keyfile: The coldkeypub file. @@ -366,8 +366,8 @@ def set_coldkey( Args: keypair (bittensor.Keypair): The coldkey keypair. - encrypt (bool, optional): Whether to encrypt the coldkey. Defaults to True. - overwrite (bool, optional): Whether to overwrite an existing coldkey. Defaults to False. + encrypt (bool, optional): Whether to encrypt the coldkey. Defaults to ``True``. + overwrite (bool, optional): Whether to overwrite an existing coldkey. Defaults to ``False``. Returns: bittensor.keyfile: The coldkey file. @@ -382,7 +382,7 @@ def get_coldkey(self, password: str = None) -> "bittensor.Keypair": Gets the coldkey from the wallet. Args: - password (str, optional): The password to decrypt the coldkey. Defaults to None. + password (str, optional): The password to decrypt the coldkey. Defaults to ``None``. Returns: bittensor.Keypair: The coldkey keypair. @@ -394,7 +394,7 @@ def get_hotkey(self, password: str = None) -> "bittensor.Keypair": Gets the hotkey from the wallet. Args: - password (str, optional): The password to decrypt the hotkey. Defaults to None. + password (str, optional): The password to decrypt the hotkey. Defaults to ``None``. Returns: bittensor.Keypair: The hotkey keypair. @@ -406,7 +406,7 @@ def get_coldkeypub(self, password: str = None) -> "bittensor.Keypair": Gets the coldkeypub from the wallet. Args: - password (str, optional): The password to decrypt the coldkeypub. Defaults to None. + password (str, optional): The password to decrypt the coldkeypub. Defaults to ``None``. Returns: bittensor.Keypair: The coldkeypub keypair. @@ -416,6 +416,7 @@ def get_coldkeypub(self, password: str = None) -> "bittensor.Keypair": @property def hotkey(self) -> "bittensor.Keypair": r"""Loads the hotkey from wallet.path/wallet.name/hotkeys/wallet.hotkey or raises an error. + Returns: hotkey (Keypair): hotkey loaded from config arguments. @@ -430,9 +431,9 @@ def hotkey(self) -> "bittensor.Keypair": @property def coldkey(self) -> "bittensor.Keypair": r"""Loads the hotkey from wallet.path/wallet.name/coldkey or raises an error. + Returns: - coldkey (Keypair): - colkey loaded from config arguments. + coldkey (Keypair): coldkey loaded from config arguments. Raises: KeyFileError: Raised if the file is corrupt of non-existent. CryptoKeyError: Raised if the user enters an incorrec password for an encrypted keyfile. @@ -444,9 +445,9 @@ def coldkey(self) -> "bittensor.Keypair": @property def coldkeypub(self) -> "bittensor.Keypair": r"""Loads the coldkeypub from wallet.path/wallet.name/coldkeypub.txt or raises an error. + Returns: - coldkeypub (Keypair): - colkeypub loaded from config arguments. + coldkeypub (Keypair): coldkeypub loaded from config arguments. Raises: KeyFileError: Raised if the file is corrupt of non-existent. CryptoKeyError: Raised if the user enters an incorrect password for an encrypted keyfile. @@ -462,17 +463,18 @@ def create_coldkey_from_uri( overwrite: bool = False, suppress: bool = False, ) -> "wallet": - """Creates coldkey from suri string, optionally encrypts it with the user's inputed password. + """Creates coldkey from suri string, optionally encrypts it with the user-provided password. + Args: uri: (str, required): - URI string to use i.e. /Alice or /Bob + URI string to use i.e., ``/Alice`` or ``/Bob``. use_password (bool, optional): Is the created key password protected. overwrite (bool, optional): - Will this operation overwrite the coldkey under the same path //coldkey + Determines if this operation overwrites the coldkey under the same path ``//coldkey``. Returns: wallet (bittensor.wallet): - this object with newly created coldkey. + This object with newly created coldkey. """ keypair = Keypair.create_from_uri(uri) if not suppress: @@ -488,17 +490,18 @@ def create_hotkey_from_uri( overwrite: bool = False, suppress: bool = False, ) -> "wallet": - """Creates hotkey from suri string, optionally encrypts it with the user's inputed password. + """Creates hotkey from suri string, optionally encrypts it with the user-provided password. + Args: uri: (str, required): - URI string to use i.e. /Alice or /Bob + URI string to use i.e., ``/Alice`` or ``/Bob`` use_password (bool, optional): Is the created key password protected. overwrite (bool, optional): - Will this operation overwrite the hotkey under the same path //hotkeys/ + Determines if this operation overwrites the hotkey under the same path ``//hotkeys/``. Returns: wallet (bittensor.wallet): - this object with newly created hotkey. + This object with newly created hotkey. """ keypair = Keypair.create_from_uri(uri) if not suppress: @@ -513,17 +516,18 @@ def new_coldkey( overwrite: bool = False, suppress: bool = False, ) -> "wallet": - """Creates a new coldkey, optionally encrypts it with the user's inputed password and saves to disk. + """Creates a new coldkey, optionally encrypts it with the user-provided password and saves to disk. + Args: n_words: (int, optional): Number of mnemonic words to use. use_password (bool, optional): Is the created key password protected. overwrite (bool, optional): - Will this operation overwrite the coldkey under the same path //coldkey + Determines if this operation overwrites the coldkey under the same path ``//coldkey``. Returns: wallet (bittensor.wallet): - this object with newly created coldkey. + This object with newly created coldkey. """ self.create_new_coldkey(n_words, use_password, overwrite, suppress) @@ -534,17 +538,18 @@ def create_new_coldkey( overwrite: bool = False, suppress: bool = False, ) -> "wallet": - """Creates a new coldkey, optionally encrypts it with the user's inputed password and saves to disk. + """Creates a new coldkey, optionally encrypts it with the user-provided password and saves to disk. + Args: n_words: (int, optional): Number of mnemonic words to use. use_password (bool, optional): Is the created key password protected. overwrite (bool, optional): - Will this operation overwrite the coldkey under the same path //coldkey + Determines if this operation overwrites the coldkey under the same path ``//coldkey``. Returns: wallet (bittensor.wallet): - this object with newly created coldkey. + This object with newly created coldkey. """ mnemonic = Keypair.generate_mnemonic(n_words) keypair = Keypair.create_from_mnemonic(mnemonic) @@ -561,17 +566,18 @@ def new_hotkey( overwrite: bool = False, suppress: bool = False, ) -> "wallet": - """Creates a new hotkey, optionally encrypts it with the user's inputed password and saves to disk. + """Creates a new hotkey, optionally encrypts it with the user-provided password and saves to disk. + Args: n_words: (int, optional): Number of mnemonic words to use. use_password (bool, optional): Is the created key password protected. overwrite (bool, optional): - Will this operation overwrite the hotkey under the same path //hotkeys/ + Determines if this operation overwrites the hotkey under the same path ``//hotkeys/``. Returns: wallet (bittensor.wallet): - this object with newly created hotkey. + This object with newly created hotkey. """ self.create_new_hotkey(n_words, use_password, overwrite, suppress) @@ -582,7 +588,8 @@ def create_new_hotkey( overwrite: bool = False, suppress: bool = False, ) -> "wallet": - """Creates a new hotkey, optionally encrypts it with the user's inputed password and saves to disk. + """Creates a new hotkey, optionally encrypts it with the user-provided password and saves to disk. + Args: n_words: (int, optional): Number of mnemonic words to use. @@ -592,7 +599,7 @@ def create_new_hotkey( Will this operation overwrite the hotkey under the same path //hotkeys/ Returns: wallet (bittensor.wallet): - this object with newly created hotkey. + This object with newly created hotkey. """ mnemonic = Keypair.generate_mnemonic(n_words) keypair = Keypair.create_from_mnemonic(mnemonic) @@ -608,18 +615,18 @@ def regenerate_coldkeypub( overwrite: bool = False, suppress: bool = False, ) -> "wallet": - """Regenerates the coldkeypub from passed ss58_address or public_key and saves the file - Requires either ss58_address or public_key to be passed. + """Regenerates the coldkeypub from the passed ``ss58_address`` or public_key and saves the file. Requires either ``ss58_address`` or public_key to be passed. + Args: ss58_address: (str, optional): - Address as ss58 string. + Address as ``ss58`` string. public_key: (str | bytes, optional): Public key as hex string or bytes. overwrite (bool, optional) (default: False): - Will this operation overwrite the coldkeypub (if exists) under the same path //coldkeypub + Determins if this operation overwrites the coldkeypub (if exists) under the same path ``//coldkeypub``. Returns: wallet (bittensor.wallet): - newly re-generated Wallet with coldkeypub. + Newly re-generated wallet with coldkeypub. """ if ss58_address is None and public_key is None: @@ -691,23 +698,26 @@ def regenerate_coldkey( suppress: bool = False, **kwargs, ) -> "wallet": - """Regenerates the coldkey from passed mnemonic, seed, or json encrypts it with the user's password and saves the file + """Regenerates the coldkey from the passed mnemonic or seed, or JSON encrypts it with the user's password and saves the file. + Args: mnemonic: (Union[list, str], optional): Key mnemonic as list of words or string space separated words. seed: (str, optional): Seed as hex string. json: (Tuple[Union[str, Dict], str], optional): - Restore from encrypted JSON backup as (json_data: Union[str, Dict], passphrase: str) + Restore from encrypted JSON backup as ``(json_data: Union[str, Dict], passphrase: str)`` use_password (bool, optional): Is the created key password protected. overwrite (bool, optional): - Will this operation overwrite the coldkey under the same path //coldkey + Determines if this operation overwrites the coldkey under the same path ``//coldkey``. Returns: wallet (bittensor.wallet): - this object with newly created coldkey. + This object with newly created coldkey. + + Note: + Uses priority order: ``mnemonic > seed > json``. - Note: uses priority order: mnemonic > seed > json """ if len(kwargs) == 0: raise ValueError("Must pass either mnemonic, seed, or json") @@ -796,21 +806,22 @@ def regenerate_hotkey( suppress: bool = False, **kwargs, ) -> "wallet": - """Regenerates the hotkey from passed mnemonic, encrypts it with the user's password and save the file + """Regenerates the hotkey from passed mnemonic or seed, encrypts it with the user's password and saves the file. + Args: mnemonic: (Union[list, str], optional): Key mnemonic as list of words or string space separated words. seed: (str, optional): Seed as hex string. json: (Tuple[Union[str, Dict], str], optional): - Restore from encrypted JSON backup as (json_data: Union[str, Dict], passphrase: str) + Restore from encrypted JSON backup as ``(json_data: Union[str, Dict], passphrase: str)``. use_password (bool, optional): Is the created key password protected. overwrite (bool, optional): - Will this operation overwrite the hotkey under the same path //hotkeys/ + Determies if this operation overwrites the hotkey under the same path ``//hotkeys/``. Returns: wallet (bittensor.wallet): - this object with newly created hotkey. + This object with newly created hotkey. """ if len(kwargs) == 0: raise ValueError("Must pass either mnemonic, seed, or json") diff --git a/contrib/CONTRIBUTING.md b/contrib/CONTRIBUTING.md index 628c52614a..443f6d2dc6 100644 --- a/contrib/CONTRIBUTING.md +++ b/contrib/CONTRIBUTING.md @@ -35,7 +35,7 @@ Bittensor is still in the Alpha stages, and as such you will likely run into som Additionally, note that the core implementation of Bittensor consists of two separate repositories: [The core Bittensor code](https://github.com/opentensor/bittensor) and the Bittensor Blockchain [subtensor](https://github.com/opentensor/subtensor). -Supplemental, yet necessary repositories are [openvalidators](https://github.com/opentensor/validators) and [openminers](https://github.com/opentensor/miners) which contain Bittensor Validators and Miners (respectively) designed by the OpenTensor Foundation team and open-sourced for the community to use. +Supplemental repository for the Bittensor subnet template can be found [here](https://github.com/opentensor/bittensor-subnet-template). This is a great first place to look for getting your hands dirty and started learning and building on Bittensor. See the subnet links [page](https://github.com/opentensor/bittensor-subnet-template/blob/main/subnet_links.json) for a list of all the repositories for the active registered subnets. ## Getting Started New contributors are very welcome and needed. @@ -43,7 +43,8 @@ Reviewing and testing is highly valued and the most effective way you can contri Before you start contributing, familiarize yourself with the Bittensor Core build system and tests. Refer to the documentation in the repository on how to build Bittensor core and how to run the unit tests, functional tests. -There are many open issues of varying difficulty waiting to be fixed. If you're looking for somewhere to start contributing, check out the [good first issue](https://github.com/opentensor/bittensor/labels/good%20first%20issue) list or changes that are up for grabs. Some of them might no longer be applicable. So if you are interested, but unsure, you might want to leave a comment on the issue first. +There are many open issues of varying difficulty waiting to be fixed. If you're looking for somewhere to start contributing, check out the [good first issue](https://github.com/opentensor/bittensor/labels/good%20first%20issue) list or changes that are up for grabs. Some of them might no longer be applicable. So if you are interested, but unsure, you might want to leave a comment on the issue first. Also peruse the [issues](https://github.com/opentensor/bittensor/issues) tab for all open issues. + ### Good First Issue Label The purpose of the good first issue label is to highlight which issues are suitable for a new contributor without a deep understanding of the codebase. @@ -67,10 +68,9 @@ And also here. ## How Can I Contribute? -You can contribute to Bittensor in one of three main ways (as well as many others): +You can contribute to Bittensor in one of two main ways (as well as many others): 1. [Bug](#reporting-bugs) reporting and fixes 2. New features and Bittensor [enhancements](#suggesting-enhancements) -3. [Documentation](https://github.com/opentensor/docs) fixes and updates > Please follow the Bittensor [style guide](./STYLE.md) regardless of your contribution type. @@ -100,6 +100,7 @@ If you're looking to contribute to Bittensor but unsure where to start, please j Patchsets and enhancements should always be focused. A pull request could add a feature, fix a bug, or refactor code, but it should not contain a mixture of these. Please also avoid 'super' pull requests which attempt to do too much, are overly large, or overly complex as this makes review difficult. Specifically, pull requests must adhere to the following criteria: +- **Must** branch off from `staging`. Make sure that all your PRs are using `staging` branch as a base or will be closed. - Contain fewer than 50 files. PRs with more than 50 files will be closed. - Use the specific [template](./.github/pull_request_template.md) appropriate to your contribution. - If a PR introduces a new feature, it *must* include corresponding tests. diff --git a/scripts/environments/apple_m1_environment.yml b/scripts/environments/apple_m1_environment.yml index 9d226d1259..3c2c6a5826 100644 --- a/scripts/environments/apple_m1_environment.yml +++ b/scripts/environments/apple_m1_environment.yml @@ -117,7 +117,7 @@ dependencies: - zlib=1.2.13=h03a7124_4 - pip: - addict==2.4.0 - - aiohttp==3.8.5 + - aiohttp==3.9.0 - aiosignal==1.3.1 - altair==4.2.2 - ansible==6.7.0 @@ -228,7 +228,7 @@ dependencies: - retry==0.9.2 - rich==12.5.1 - rsa==4.9 - - scalecodec==1.2.0 + - scalecodec==1.2.7 - scikit-learn==1.2.2 - scipy==1.10.1 - sentencepiece==0.1.99 @@ -241,7 +241,7 @@ dependencies: - sqlalchemy==2.0.19 - starlette==0.27.0 - streamlit==1.22.0 - - substrate-interface==1.5.0 + - substrate-interface==1.5.2 - tenacity==8.2.2 - termcolor==2.1.1 - threadpoolctl==3.1.0