From 8f3331e06492148b9c6b0ae1c8f61d27a2906451 Mon Sep 17 00:00:00 2001 From: michael trestman Date: Tue, 8 Jul 2025 08:18:05 -0700 Subject: [PATCH 01/21] edit docstrings --- bittensor/core/async_subtensor.py | 752 ++++++++++++++++++++++-------- 1 file changed, 564 insertions(+), 188 deletions(-) diff --git a/bittensor/core/async_subtensor.py b/bittensor/core/async_subtensor.py index 788a48cb93..e29362dfb7 100644 --- a/bittensor/core/async_subtensor.py +++ b/bittensor/core/async_subtensor.py @@ -127,7 +127,13 @@ class AsyncSubtensor(SubtensorMixin): - """Thin layer for interacting with Substrate Interface. Mostly a collection of frequently-used calls.""" + """Asynchronous interface for interacting with the Bittensor blockchain. + + This class provides a thin layer over the Substrate Interface, offering a collection of frequently-used calls for + querying blockchain data, managing stakes, registering neurons, and interacting with the Bittensor network. + + + """ def __init__( self, @@ -185,11 +191,51 @@ def __init__( ) async def close(self): - """Close the connection.""" + """Closes the connection to the blockchain. + + Use this to explicitly clean up resources and close the network connection instead of waiting for garbage + collection. + + Returns: + None + + Example: + subtensor = AsyncSubtensor(network="finney") + await subtensor.initialize() + + # Use the subtensor... + balance = await subtensor.get_balance("5F...") + + # Close when done + await subtensor.close() + """ if self.substrate: await self.substrate.close() async def initialize(self): + """Initializes the connection to the blockchain. + + This method establishes the connection to the Bittensor blockchain and should be called after creating an + AsyncSubtensor instance before making any queries. + + Returns: + AsyncSubtensor: The initialized instance (self) for method chaining. + + Raises: + ConnectionError: If unable to connect to the blockchain due to timeout or connection refusal. + + Example: + subtensor = AsyncSubtensor(network="finney") + + # Initialize the connection + await subtensor.initialize() + + # Now you can make queries + balance = await subtensor.get_balance("5F...") + + # Or chain the initialization + subtensor = await AsyncSubtensor(network="finney").initialize() + """ logging.info( f"[magenta]Connecting to Substrate:[/magenta] [blue]{self}[/blue][magenta]...[/magenta]" ) @@ -238,6 +284,32 @@ async def determine_block_hash( block_hash: Optional[str] = None, reuse_block: bool = False, ) -> Optional[str]: + """Determine the appropriate block hash based on the provided parameters. + + Ensures that only one of the block specification parameters is used and returns the appropriate block hash for + blockchain queries. + + Args: + block: The block number to get the hash for. Do not specify if using block_hash or reuse_block. + block_hash: The hash of the blockchain block. Do not specify if using block or reuse_block. + reuse_block: Whether to reuse the last-used block hash. Do not set if using block or block_hash. + + Returns: + Optional[str]: The block hash if one can be determined, None otherwise. + + Raises: + ValueError: If more than one of block, block_hash, or reuse_block is specified. + + Example: + # Get hash for specific block + block_hash = await subtensor.determine_block_hash(block=1000000) + + # Use provided block hash + hash = await subtensor.determine_block_hash(block_hash="0x1234...") + + # Reuse last block hash + hash = await subtensor.determine_block_hash(reuse_block=True) + """ # Ensure that only one of the parameters is specified. if sum(bool(x) for x in [block, block_hash, reuse_block]) > 1: raise ValueError( @@ -256,7 +328,43 @@ async def encode_params( call_definition: dict[str, list["ParamWithTypes"]], params: Union[list[Any], dict[str, Any]], ) -> str: - """Returns a hex-encoded string of the params using their types.""" + """Encodes parameters into a hex string using their type definitions. + + This method takes a call definition (which specifies parameter types) and actual parameter values, then encodes + them into a hex string that can be used for blockchain transactions. + + Args: + call_definition: A dictionary containing parameter type definitions. Should have a "params" key with a list of + parameter definitions. + params: The actual parameter values to encode. Can be either a list (for positional parameters) or a + dictionary (for named parameters). + + Returns: + str: A hex-encoded string representation of the parameters. + + Raises: + ValueError: If a required parameter is missing from the params dictionary. + + Example: + # Define parameter types + call_def = { + "params": [ + {"name": "amount", "type": "u64"}, + {"name": "coldkey_ss58", "type": "str"} + ] + } + + # Encode parameters as a dictionary + params_dict = { + "amount": 1000000, + "coldkey_ss58": "5F..." + } + encoded = await subtensor.encode_params(call_def, params_dict) + + # Or encode as a list (positional) + params_list = [1000000, "5F..."] + encoded = await subtensor.encode_params(call_def, params_list) + """ param_data = scalecodec.ScaleBytes(b"") for i, param in enumerate(call_definition["params"]): @@ -279,20 +387,41 @@ async def get_hyperparameter( block_hash: Optional[str] = None, reuse_block: bool = False, ) -> Optional[Any]: - """ - Retrieves a specified hyperparameter for a specific subnet. + """Retrieves a specified hyperparameter for a specific subnet. - Arguments: - param_name (str): The name of the hyperparameter to retrieve. + This method queries the blockchain for subnet-specific hyperparameters such as difficulty, tempo, immunity + period, and other network configuration values. + + Args: + param_name (str): The name of the hyperparameter to retrieve (e.g., "Difficulty", "Tempo", + "ImmunityPeriod"). netuid (int): The unique identifier of the subnet. - block: the block number at which to retrieve the hyperparameter. Do not specify if using block_hash or - reuse_block - block_hash (Optional[str]): The hash of blockchain block number for the query. Do not specify if using - block or reuse_block - reuse_block (bool): Whether to reuse the last-used block hash. Do not set if using block_hash or block. + block (Optional[int]): The block number at which to retrieve the hyperparameter. Do not specify if using + block_hash or reuse_block. + block_hash (Optional[str]): The hash of the blockchain block for the query. Do not specify if using block or + reuse_block. + reuse_block: Whether to reuse the last-used block hash. Do not set if using block_hash or block. Returns: - The value of the specified hyperparameter if the subnet exists, or None + The value of the specified hyperparameter if the subnet exists, None otherwise. + + Example: + # Get difficulty for subnet 1 + difficulty = await subtensor.get_hyperparameter("Difficulty", netuid=1) + + # Get tempo at a specific block + tempo = await subtensor.get_hyperparameter( + "Tempo", + netuid=1, + block=1000000 + ) + + # Get immunity period using block hash + immunity = await subtensor.get_hyperparameter( + "ImmunityPeriod", + netuid=1, + block_hash="0x1234..." + ) """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) if not await self.subnet_exists( @@ -321,11 +450,14 @@ def _get_substrate( ) -> Union[AsyncSubstrateInterface, RetryAsyncSubstrate]: """Creates the Substrate instance based on provided arguments. - Arguments: - fallback_endpoints: List of fallback endpoints to use if default or provided network is not available. - Defaults to `None`. + This internal method creates either a standard AsyncSubstrateInterface or a + RetryAsyncSubstrate depending on the configuration parameters. + + Args: + fallback_endpoints: List of fallback endpoints to use if default or provided network is not available. + Defaults to None. retry_forever: Whether to retry forever on connection errors. Defaults to `False`. - _mock: Whether this is a mock instance. Mainly just for use in testing. + _mock: Whether this is a mock instance. Mainly for testing purposes. Defaults to False. archive_endpoints: Similar to fallback_endpoints, but specifically only archive nodes. Will be used in cases where you are requesting a block that is too old for your current (presumably lite) node. Defaults to `None` @@ -333,7 +465,7 @@ def _get_substrate( connection. Returns: - the instance of the SubstrateInterface or RetrySyncSubstrate class. + Either AsyncSubstrateInterface or RetryAsyncSubstrate. """ if fallback_endpoints or retry_forever or archive_endpoints: return RetryAsyncSubstrate( @@ -368,26 +500,41 @@ async def query_constant( block_hash: Optional[str] = None, reuse_block: bool = False, ) -> Optional["ScaleObj"]: - """ - Retrieves a constant from the specified module on the Bittensor blockchain. This function is used to access - fixed parameters or values defined within the blockchain's modules, which are essential for understanding - the network's configuration and rules. + """Retrieves a constant from the specified module on the Bittensor blockchain. + + This function is used to access fixed values defined within the + blockchain's modules, which are essential for understanding the network's + configuration and rules. These include include critical network parameters such as inflation rates, + consensus rules, or validation thresholds, providing a deeper understanding of the Bittensor network's + operational parameters. Args: - module_name: The name of the module containing the constant. - constant_name: The name of the constant to retrieve. - block: The blockchain block number at which to query the constant. Do not specify if using block_hash or - reuse_block - block_hash: the hash of th blockchain block at which to query the constant. Do not specify if using block - or reuse_block - reuse_block: Whether to reuse the blockchain block at which to query the constant. + module_name: The name of the module containing the constant (e.g., "Balances", + "SubtensorModule"). + constant_name: The name of the constant to retrieve (e.g., "ExistentialDeposit"). + block (Optional[int]): The blockchain block number at which to query the constant. Do not + specify if using block_hash or reuse_block. + block_hash (Optional[str]): The hash of the blockchain block at which to query the constant. + Do not specify if using block or reuse_block. + reuse_block (bool): Whether to reuse the blockchain block at which to query the + constant. Defaults to False. Returns: Optional[async_substrate_interface.types.ScaleObj]: The value of the constant if found, `None` otherwise. - Constants queried through this function can include critical network parameters such as inflation rates, - consensus rules, or validation thresholds, providing a deeper understanding of the Bittensor network's - operational parameters. + Example: + # Get existential deposit constant + existential_deposit = await subtensor.query_constant( + "Balances", + "ExistentialDeposit" + ) + + # Get constant at specific block + constant = await subtensor.query_constant( + "SubtensorModule", + "SomeConstant", + block=1000000 + ) """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) return await self.substrate.get_constant( @@ -406,25 +553,45 @@ async def query_map( reuse_block: bool = False, params: Optional[list] = None, ) -> "AsyncQueryMapResult": - """ - Queries map storage from any module on the Bittensor blockchain. This function retrieves data structures that - represent key-value mappings, essential for accessing complex and structured data within the blockchain - modules. + """Queries map storage from any module on the Bittensor blockchain. + + This function retrieves data structures that represent key-value mappings, + essential for accessing complex and structured data within the blockchain + modules. Args: - module: The name of the module from which to query the map storage. - name: The specific storage function within the module to query. - block: The blockchain block number at which to perform the query. - block_hash: The hash of the block to retrieve the parameter from. Do not specify if using block or - reuse_block - reuse_block: Whether to use the last-used block. Do not set if using block_hash or block. - params: Parameters to be passed to the query. + module: The name of the module from which to query the map storage + (e.g., "SubtensorModule", "System"). + name: The specific storage function within the module to query + (e.g., "Bonds", "Weights"). + block (Optional[int]): The blockchain block number at which to perform the query. + Defaults to None (latest block). + block_hash (Optional[str]): The hash of the block to retrieve the parameter from. Do not + specify if using block or reuse_block. + reuse_block (bool): Whether to use the last-used block. Do not set if using + block_hash or block. Defaults to False. + params (Optional[list]): Parameters to be passed to the query. Defaults to None. Returns: - result: A data structure representing the map storage if found, `None` otherwise. + AsyncQueryMapResult: A data structure representing the map storage if found, + None otherwise. - This function is particularly useful for retrieving detailed and structured data from various blockchain - modules, offering insights into the network's state and the relationships between its different components. + Example: + # Query bonds for subnet 1 + bonds = await subtensor.query_map( + "SubtensorModule", + "Bonds", + params=[1] + ) + + # Query weights at specific block + weights = await subtensor.query_map( + "SubtensorModule", + "Weights", + params=[1], + block=1000000 + ) + """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) result = await self.substrate.query_map( @@ -627,18 +794,24 @@ async def all_subnets( block_hash: Optional[str] = None, reuse_block: bool = False, ) -> Optional[list[DynamicInfo]]: - """ - Retrieves the subnet information for all subnets in the network. + """Queries the blockchain for comprehensive information about all + subnets, including their dynamic parameters and operational status. Args: - block_number (Optional[int]): The block number to query the subnet information from. Do not specify if using - block_hash or reuse_block - block_hash: The hash of the blockchain block number for the query. Do not specify if using reuse_block or - block. - reuse_block: Whether to reuse the last-used blockchain block hash. Do not set if using block_hash or block. + block_number (Optional[int]): The block number to query the subnet information from. Do not + specify if using block_hash or reuse_block. + block_hash (Optional[str]): The hash of the blockchain block number for the query. Do not + specify if using reuse_block or block. + reuse_block (bool): Whether to reuse the last-used blockchain block hash. Do not + set if using block_hash or block. Returns: - Optional[DynamicInfo]: A list of DynamicInfo objects, each containing detailed information about a subnet. + Optional[list[DynamicInfo]]: A list of DynamicInfo objects, each containing + detailed information about a subnet, or None if the query fails. + + Example: + # Get all subnets at current block + subnets = await subtensor.all_subnets() """ block_hash = await self.determine_block_hash( @@ -661,18 +834,31 @@ async def blocks_since_last_step( block_hash: Optional[str] = None, reuse_block: bool = False, ) -> Optional[int]: - """Returns number of blocks since the last epoch of the subnet. + """Queries the blockchain to determine how many blocks have passed + since the last epoch step for a specific subnet. - Arguments: + Args: netuid (int): The unique identifier of the subnetwork. - block: the block number for this query. - block_hash: The hash of the blockchain block number for the query. Do not specify if using reuse_block or - block. - reuse_block: Whether to reuse the last-used blockchain block hash. Do not set if using block_hash or block. - + block (Optional[int]): The block number for this query. Do not specify if using + block_hash or reuse_block. + block_hash (Optional[str]): The hash of the blockchain block number for the query. Do not + specify if using reuse_block or block. + reuse_block (bool): Whether to reuse the last-used blockchain block hash. Do not + set if using block_hash or block. Returns: - block number of the last step in the subnet. + The number of blocks since the last step in the subnet, + or None if the query fails. + + Example: + # Get blocks since last step for subnet 1 + blocks = await subtensor.blocks_since_last_step(netuid=1) + + # Get blocks since last step at specific block + blocks = await subtensor.blocks_since_last_step( + netuid=1, + block=1000000 + ) """ query = await self.query_subtensor( name="BlocksSinceLastStep", @@ -684,16 +870,24 @@ async def blocks_since_last_step( return query.value if query is not None and hasattr(query, "value") else query async def blocks_since_last_update(self, netuid: int, uid: int) -> Optional[int]: - """ - Returns the number of blocks since the last update for a specific UID in the subnetwork. + """Returns the number of blocks since the last update, or ``None`` if the subnetwork or UID does not + exist. - Arguments: + Args: netuid (int): The unique identifier of the subnetwork. uid (int): The unique identifier of the neuron. Returns: - Optional[int]: The number of blocks since the last update, or ``None`` if the subnetwork or UID does not - exist. + Optional[int]: The number of blocks since the last update, or None if the + subnetwork or UID does not exist. + + Example: + # Get blocks since last update for UID 5 in subnet 1 + blocks = await subtensor.blocks_since_last_update(netuid=1, uid=5) + + # Check if neuron needs updating + blocks_since_update = await subtensor.blocks_since_last_update(netuid=1, uid=10) + """ call = await self.get_hyperparameter(param_name="LastUpdate", netuid=netuid) return None if call is None else await self.get_current_block() - int(call[uid]) @@ -705,25 +899,32 @@ async def bonds( block_hash: Optional[str] = None, reuse_block: bool = False, ) -> list[tuple[int, list[tuple[int, int]]]]: - """ - Retrieves the bond distribution set by neurons within a specific subnet of the Bittensor network. - Bonds represent the investments or commitments made by neurons in one another, indicating a level of trust - and perceived value. This bonding mechanism is integral to the network's market-based approach to - measuring and rewarding machine intelligence. + """Retrieves the bond distribution set by subnet validators within a specific subnet. + + Bonds represent the "investment" a subnet validator has made in evaluating a specific + subnet miner. This bonding mechanism is integral to the Yuma Consensus' design intent + of incentivizing high-quality performance by subnet miners, and honest evaluation by + subnet validators. Args: - netuid: The network UID of the subnet to query. - block: the block number for this query. Do not specify if using block_hash or reuse_block - block_hash: The hash of the blockchain block number for the query. Do not specify if using reuse_block or - block. - reuse_block: Whether to reuse the last-used blockchain block hash. Do not set if using block_hash or block. + netuid (int): The unique identifier of the subnet. + block (Optional[int]): The block number for this query. Do not specify if using + block_hash or reuse_block. + block_hash (Optional[str]): The hash of the block for the query. Do not specify + if using reuse_block or block. + reuse_block: Whether to reuse the last-used block hash. Do not set if using + block_hash or block. Returns: List of tuples mapping each neuron's UID to its bonds with other neurons. - Understanding bond distributions is crucial for analyzing the trust dynamics and market behavior within the - subnet. It reflects how neurons recognize and invest in each other's intelligence and contributions, - supporting diverse and niche systems within the Bittensor ecosystem. + Example: + # Get bonds for subnet 1 at block 1000000 + bonds = await subtensor.bonds(netuid=1, block=1000000) + + Notes: + - See + - See """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) b_map_encoded = await self.substrate.query_map( @@ -743,19 +944,39 @@ async def bonds( async def commit( self, wallet: "Wallet", netuid: int, data: str, period: Optional[int] = None ) -> bool: - """ - Commits arbitrary data to the Bittensor network by publishing metadata. + """Commits arbitrary data to the Bittensor network by publishing metadata. - Arguments: - wallet (bittensor_wallet.Wallet): The wallet associated with the neuron committing the data. - netuid (int): The unique identifier of the subnetwork. - data (str): The data to be committed to the network. - period (Optional[int]): The number of blocks during which the transaction will remain valid after it's - submitted. If the transaction is not included in a block within that number of blocks, it will expire - and be rejected. You can think of it as an expiration date for the transaction. + This method allows neurons to publish arbitrary data to the blockchain, which can be used for various purposes + such as sharing model updates, configuration data, or other network-relevant information. + + Args: + wallet: The wallet associated with the neuron committing the data. + netuid: The unique identifier of the subnet. + data: The data to be committed to the network. + period: The number of blocks during which the transaction will remain valid after it's submitted. + If the transaction is not included in a block within that number of blocks, it will expire and be + rejected. You can think of it as an expiration date for the transaction. - Return: - bool: `True` if the commit was successful, `False` otherwise. + Returns: + bool: True if the commit was successful, False otherwise. + + Example: + # Commit some data to subnet 1 + success = await subtensor.commit( + wallet=my_wallet, + netuid=1, + data="Hello Bittensor!" + ) + + # Commit with custom period + success = await subtensor.commit( + wallet=my_wallet, + netuid=1, + data="Model update v2.0", + period=100 + ) + + Note: See """ return await publish_metadata( subtensor=self, @@ -775,19 +996,33 @@ async def commit_reveal_enabled( block_hash: Optional[str] = None, reuse_block: bool = False, ) -> bool: - """ - Check if commit-reveal mechanism is enabled for a given network at a specific block. + """Check if commit-reveal mechanism is enabled for a given subnet at a specific block. - Arguments: - netuid: The network identifier for which to check the commit-reveal mechanism. + The commit reveal feature is designed to solve the weight-copying problem by giving would-be weight-copiers + access only to stale weights. Copying stale weights should result in subnet validators departing from consensus. + + Args: + netuid: The unique identifier of the subnet for which to check the commit-reveal mechanism. block: The block number to query. Do not specify if using block_hash or reuse_block. - block_hash: The block hash of block at which to check the parameter. Do not set if using block or + block_hash: The block hash at which to check the parameter. Do not set if using block or reuse_block. - reuse_block: Whether to reuse the last-used blockchain block hash. Do not set if using block_hash or + reuse_block: Whether to reuse the last-used block hash. Do not set if using block_hash or block. Returns: - Returns the integer value of the hyperparameter if available; otherwise, returns None. + bool: True if commit-reveal mechanism is enabled, False otherwise. + + Example: + # Check if commit-reveal is enabled for subnet 1 + enabled = await subtensor.commit_reveal_enabled(netuid=1) + + # Check at specific block + enabled = await subtensor.commit_reveal_enabled( + netuid=1, + block=1000000 + ) + + See also: See """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) call = await self.get_hyperparameter( @@ -805,24 +1040,34 @@ async def difficulty( block_hash: Optional[str] = None, reuse_block: bool = False, ) -> Optional[int]: - """ - Retrieves the 'Difficulty' hyperparameter for a specified subnet in the Bittensor network. + """Retrieves the 'Difficulty' hyperparameter for a specified subnet in the Bittensor network. - This parameter is instrumental in determining the computational challenge required for neurons to participate in - consensus and validation processes. + This parameter determines the computational challenge required for neurons to participate in + consensus and validation processes. The difficulty directly impacts the network's security and integrity by + setting the computational effort required for validating transactions and participating in the network's + consensus mechanism. - Arguments: + Args: netuid: The unique identifier of the subnet. - block: The blockchain block number for the query. Do not specify if using block_hash or reuse_block + block: The block number for the query. Do not specify if using block_hash or reuse_block. block_hash: The hash of the block to retrieve the parameter from. Do not specify if using block or - reuse_block + reuse_block. reuse_block: Whether to use the last-used block. Do not set if using block_hash or block. Returns: - Optional[int]: The value of the 'Difficulty' hyperparameter if the subnet exists, ``None`` otherwise. + Optional[int]: The value of the 'Difficulty' hyperparameter if the subnet exists, None otherwise. + + Example: + # Get difficulty for subnet 1 + difficulty = await subtensor.difficulty(netuid=1) + + # Get difficulty at specific block + difficulty = await subtensor.difficulty( + netuid=1, + block=1000000 + ) - The 'Difficulty' parameter directly impacts the network's security and integrity by setting the computational - effort required for validating transactions and participating in the network's consensus mechanism. + See also: See """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) call = await self.get_hyperparameter( @@ -842,18 +1087,29 @@ async def does_hotkey_exist( block_hash: Optional[str] = None, reuse_block: bool = False, ) -> bool: - """ - Returns true if the hotkey is known by the chain and there are accounts. + """Returns true if the hotkey is known by the chain and there are accounts. + + This method queries the SubtensorModule's Owner storage function to determine if the hotkey is registered. Args: hotkey_ss58: The SS58 address of the hotkey. - block: the block number for this query. Do not specify if using block_hash or reuse_block + block: The block number for this query. Do not specify if using block_hash or reuse_block. block_hash: The hash of the block number to check the hotkey against. Do not specify if using reuse_block or block. reuse_block: Whether to reuse the last-used blockchain hash. Do not set if using block_hash or block. Returns: - `True` if the hotkey is known by the chain and there are accounts, `False` otherwise. + bool: True if the hotkey is known by the chain and there are accounts, False otherwise. + + Example: + # Check if hotkey exists + exists = await subtensor.does_hotkey_exist("5F...") + + # Check at specific block + exists = await subtensor.does_hotkey_exist( + "5F...", + block=1000000 + ) """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) result = await self.substrate.query( @@ -877,20 +1133,35 @@ async def get_all_subnets_info( block_hash: Optional[str] = None, reuse_block: bool = False, ) -> list["SubnetInfo"]: - """ - Retrieves detailed information about all subnets within the Bittensor network. This function provides - comprehensive data on each subnet, including its characteristics and operational parameters. + """Retrieves detailed information about all subnets within the Bittensor network. - Arguments: - block (Optional[int]): The blockchain block number for the query. - block_hash (Optional[str]): The blockchain block_hash for the query. - reuse_block (bool): Whether to reuse the last-used blockchain block hash. + This function provides comprehensive data on each subnet, including its characteristics and operational + parameters. + + Args: + block: The block number for the query. + block_hash: The block hash for the query. + reuse_block: Whether to reuse the last-used block hash. Returns: list[SubnetInfo]: A list of SubnetInfo objects, each containing detailed information about a subnet. - Gaining insights into the subnets' details assists in understanding the network's composition, the roles of - different subnets, and their unique features. + Example: + # Get all subnet information + subnets = await subtensor.get_all_subnets_info() + + # Get at specific block + subnets = await subtensor.get_all_subnets_info(block=1000000) + + # Iterate over subnet information + for subnet in subnets: + print(f"Subnet {subnet.netuid}: {subnet.name}") + + Note: + Gaining insights into the subnets' details assists in understanding the network's composition, + the roles of different subnets, and their unique features. + + See also: See """ result = await self.query_runtime_api( runtime_api="SubnetInfoRuntimeApi", @@ -912,17 +1183,33 @@ async def get_balance( block_hash: Optional[str] = None, reuse_block: bool = False, ) -> Balance: - """ - Retrieves the balance for given coldkey. + """Retrieves the balance for given coldkey. - Arguments: - address (str): coldkey address. - block (Optional[int]): The blockchain block number for the query. - block_hash (Optional[str]): The blockchain block_hash for the query. - reuse_block (bool): Whether to reuse the last-used blockchain block hash. + This method queries the System module's Account storage to get the current balance of a coldkey address. + The balance represents the amount of TAO tokens held by the specified address. + + Args: + address: The coldkey address in SS58 format. + block: The block number for the query. + block_hash: The block hash for the query. + reuse_block: Whether to reuse the last-used block hash. Returns: - Balance object. + Balance: The balance object containing the account's TAO balance. + + Example: + # Get balance for an address + balance = await subtensor.get_balance("5F...") + print(f"Balance: {balance.tao} TAO") + + # Get balance at specific block + balance = await subtensor.get_balance( + "5F...", + block=1000000 + ) + + See also: See , + See """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) balance = await self.substrate.query( @@ -941,17 +1228,31 @@ async def get_balances( block_hash: Optional[str] = None, reuse_block: bool = False, ) -> dict[str, Balance]: - """ - Retrieves the balance for given coldkey(s) + """Retrieves the balance for given coldkey(s). - Arguments: - addresses (str): coldkey addresses(s). - block (Optional[int]): The blockchain block number for the query. - block_hash (Optional[str]): the block hash, optional. - reuse_block (Optional[bool]): whether to reuse the last-used block hash. + This method efficiently queries multiple coldkey addresses in a single batch operation, returning a + dictionary mapping each address to its corresponding balance. This is more efficient than calling + get_balance multiple times. + + Args: + *addresses: Variable number of coldkey addresses in SS58 format. + block: The block number for the query. + block_hash: The block hash for the query. + reuse_block: Whether to reuse the last-used block hash. Returns: - Dict of {address: Balance objects}. + dict[str, Balance]: A dictionary mapping each address to its Balance object. + + Example: + # Get balances for multiple addresses + balances = await subtensor.get_balances( + "5F...", + "5G...", + "5H..." + ) + + See also: See , + See """ if reuse_block: block_hash = self.substrate.last_block_hash @@ -975,16 +1276,27 @@ async def get_balances( return results async def get_current_block(self) -> int: - """ - Returns the current block number on the Bittensor blockchain. This function provides the latest block number, - indicating the most recent state of the blockchain. + """Returns the current block number on the Bittensor blockchain. + + This function provides the latest block number, indicating the most recent state of the blockchain. + Knowing the current block number is essential for querying real-time data and performing time-sensitive + operations on the blockchain. It serves as a reference point for network activities and data + synchronization. Returns: int: The current chain block number. - Knowing the current block number is essential for querying real-time data and performing time-sensitive - operations on the blockchain. It serves as a reference point for network activities and data - synchronization. + Example: + # Get current block number + current_block = await subtensor.get_current_block() + print(f"Current block: {current_block}") + + + block = await subtensor.get_current_block() + if block > 1000000: + print("Network has progressed past block 1M") + + See also: See """ return await self.substrate.get_block_number(None) @@ -993,19 +1305,29 @@ async def _get_block_hash(self, block_id: int): return await self.substrate.get_block_hash(block_id) async def get_block_hash(self, block: Optional[int] = None) -> str: - """ - Retrieves the hash of a specific block on the Bittensor blockchain. The block hash is a unique identifier - representing the cryptographic hash of the block's content, ensuring its integrity and immutability. + """Retrieves the hash of a specific block on the Bittensor blockchain. - Arguments: - block (int): The block number for which the hash is to be retrieved. + The block hash is a unique identifier representing the cryptographic hash of the block's content, + ensuring its integrity and immutability. It is a fundamental aspect of blockchain technology, + providing a secure reference to each block's data. It is crucial for verifying transactions, + ensuring data consistency, and maintaining the trustworthiness of the blockchain. + + Args: + block: The block number for which the hash is to be retrieved. If None, returns the latest block hash. Returns: str: The cryptographic hash of the specified block. - The block hash is a fundamental aspect of blockchain technology, providing a secure reference to each block's - data. It is crucial for verifying transactions, ensuring data consistency, and maintaining the - trustworthiness of the blockchain. + Example: + # Get hash for specific block + block_hash = await subtensor.get_block_hash(1000000) + print(f"Block 1000000 hash: {block_hash}") + + # Get latest block hash + latest_hash = await subtensor.get_block_hash() + print(f"Latest block hash: {latest_hash}") + + See also: See """ if block: return await self._get_block_hash(block) @@ -1061,20 +1383,33 @@ async def get_children( block_hash: Optional[str] = None, reuse_block: bool = False, ) -> tuple[bool, list[tuple[float, str]], str]: - """ - This method retrieves the children of a given hotkey and netuid. It queries the SubtensorModule's ChildKeys - storage function to get the children and formats them before returning as a tuple. + """Retrieves the children of a given hotkey and netuid. - Arguments: - hotkey (str): The hotkey value. - netuid (int): The netuid value. - block (Optional[int]): The block number for which the children are to be retrieved. - block_hash (Optional[str]): The hash of the block to retrieve the subnet unique identifiers from. - reuse_block (bool): Whether to reuse the last-used block hash. + This method queries the SubtensorModule's ChildKeys storage function to get the children and formats them + before returning as a tuple. It provides information about the child neurons that a validator has set + for weight distribution. + + Args: + hotkey: The hotkey value. + netuid: The netuid value. + block: The block number for which the children are to be retrieved. + block_hash: The hash of the block to retrieve the subnet unique identifiers from. + reuse_block: Whether to reuse the last-used block hash. Returns: - A tuple containing a boolean indicating success or failure, a list of formatted children, and an error - message (if applicable) + tuple[bool, list[tuple[float, str]], str]: A tuple containing a boolean indicating success or failure, + a list of formatted children with their proportions, and an error message (if applicable). + + Example: + # Get children for a hotkey in subnet 1 + success, children, error = await subtensor.get_children( + hotkey="5F...", + netuid=1 + ) + + if success: + for proportion, child_hotkey in children: + print(f"Child {child_hotkey}: {proportion}") """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) try: @@ -1157,19 +1492,33 @@ async def get_commitment( block_hash: Optional[str] = None, reuse_block: bool = False, ) -> str: - """ - Retrieves the on-chain commitment for a specific neuron in the Bittensor network. + """Retrieves the on-chain commitment for a specific neuron in the Bittensor network. - Arguments: + This method retrieves the commitment data that a neuron has published to the blockchain. Commitments + are used in the commit-reveal mechanism for secure weight setting and other network operations. + + Args: netuid (int): The unique identifier of the subnetwork. uid (int): The unique identifier of the neuron. block (Optional[int]): The block number to retrieve the commitment from. If None, the latest block is used. - Default is ``None``. + Default is None. block_hash (Optional[str]): The hash of the block to retrieve the subnet unique identifiers from. reuse_block (bool): Whether to reuse the last-used block hash. Returns: str: The commitment data as a string. + + Example: + # Get commitment for UID 5 in subnet 1 + commitment = await subtensor.get_commitment(netuid=1, uid=5) + print(f"Commitment: {commitment}") + + # Get commitment at specific block + commitment = await subtensor.get_commitment( + netuid=1, + uid=5, + block=1000000 + ) """ metagraph = await self.metagraph(netuid) try: @@ -1223,18 +1572,28 @@ async def get_all_commitments( block_hash: Optional[str] = None, reuse_block: bool = False, ) -> dict[str, str]: - """ - Retrieves the on-chain commitments for a specific subnet in the Bittensor network. + """Retrieves the on-chain commitments for a specific subnet in the Bittensor network. - Arguments: + This method retrieves all commitment data for all neurons in a specific subnet. This is useful for + analyzing the commit-reveal patterns across an entire subnet. + + Args: netuid (int): The unique identifier of the subnetwork. block (Optional[int]): The block number to retrieve the commitment from. If None, the latest block is used. - Default is ``None``. + Default is None. block_hash (Optional[str]): The hash of the block to retrieve the subnet unique identifiers from. reuse_block (bool): Whether to reuse the last-used block hash. Returns: - dict[str, str]: A mapping of the ss58:commitment with the commitment as a string + dict[str, str]: A mapping of the ss58:commitment with the commitment as a string. + + Example: + # Get all commitments for subnet 1 + commitments = await subtensor.get_all_commitments(netuid=1) + + # Iterate over all commitments + for hotkey, commitment in commitments.items(): + print(f"Hotkey {hotkey}: {commitment}") """ query = await self.query_map( module="Commitments", @@ -1584,6 +1943,8 @@ async def get_existential_deposit( The existential deposit is a fundamental economic parameter in the Bittensor network, ensuring efficient use of storage and preventing the proliferation of dust accounts. + + See also: See """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) result = await self.substrate.get_constant( @@ -1618,6 +1979,9 @@ async def get_hotkey_owner( Returns: Optional[str]: The SS58 address of the owner if the hotkey exists, or None if it doesn't. + + See also: See , + See """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) hk_owner_query = await self.substrate.query( @@ -1661,8 +2025,12 @@ async def get_metagraph_info( """ Retrieves full or partial metagraph information for the specified subnet (netuid). + A metagraph is a data structure that contains comprehensive information about the current state of a subnet, + including detailed information on all the nodes (neurons) such as subnet validator stakes and subnet weights + in the subnet. Metagraph aids in calculating emissions. + Arguments: - netuid: The NetUID of the subnet to query. + netuid: The unique identifier of the subnet to query. field_indices: An optional list of SelectiveMetagraphIndex or int values specifying which fields to retrieve. If not provided, all available fields will be returned. block: the block number at which to retrieve the hyperparameter. Do not specify if using block_hash or @@ -1682,6 +2050,9 @@ async def get_metagraph_info( netuid=2, field_indices=[SelectiveMetagraphIndex.Name, SelectiveMetagraphIndex.OwnerHotkeys] ) + + See also: See , + See """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) if not block_hash and reuse_block: @@ -1737,6 +2108,8 @@ async def get_all_metagraphs_info( Returns: MetagraphInfo dataclass + + See also: See """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) if not block_hash and reuse_block: @@ -3924,14 +4297,14 @@ async def commit_weights( period: Optional[int] = 16, ) -> tuple[bool, str]: """ - Commits a hash of the neuron's weights to the Bittensor blockchain using the provided wallet. - This action serves as a commitment or snapshot of the neuron's current weight distribution. + Commits a hash of the subnet validator's weight vector to the Bittensor blockchain using the provided wallet. + This action serves as a commitment or snapshot of the validator's current weight distribution. Arguments: - wallet (bittensor_wallet.Wallet): The wallet associated with the neuron committing the weights. + wallet (bittensor_wallet.Wallet): The wallet associated with the subnet validator committing the weights. netuid (int): The unique identifier of the subnet. salt (list[int]): list of randomly generated integers as salt to generated weighted hash. - uids (np.ndarray): NumPy array of neuron UIDs for which weights are being committed. + uids (np.ndarray): NumPy array of subnet miner neuron UIDs for which weights are being committed. weights (np.ndarray): NumPy array of weight values corresponding to each UID. version_key (int): Version key for compatibility with the network. Default is ``int representation of a Bittensor version.``. @@ -3948,8 +4321,11 @@ async def commit_weights( `True` if the weight commitment is successful, False otherwise. `msg` is a string value describing the success or potential error. - This function allows neurons to create a tamper-proof record of their weight distribution at a specific point - in time, enhancing transparency and accountability within the Bittensor network. + This function allows subnet validators to create a tamper-proof record of their weight vector at a specific point + in time, creating a foundation of transparency and accountability for the Bittensor network. + + See also: See , + See """ retries = 0 success = False @@ -4262,13 +4638,13 @@ async def reveal_weights( period: Optional[int] = None, ) -> tuple[bool, str]: """ - Reveals the weights for a specific subnet on the Bittensor blockchain using the provided wallet. - This action serves as a revelation of the neuron's previously committed weight distribution. + Reveals the weight vector for a specific subnet on the Bittensor blockchain using the provided wallet. + This action serves as a revelation of the subnet validator's previously committed weight distribution as part of the commit-reveal mechanism. Args: - wallet (bittensor_wallet.Wallet): The wallet associated with the neuron revealing the weights. + wallet (bittensor_wallet.Wallet): The wallet associated with the subnet validator revealing the weights. netuid (int): The unique identifier of the subnet. - uids (np.ndarray): NumPy array of neuron UIDs for which weights are being revealed. + uids (np.ndarray): NumPy array of subnet miner neuron UIDs for which weights are being revealed. weights (np.ndarray): NumPy array of weight values corresponding to each UID. salt (np.ndarray): NumPy array of salt values corresponding to the hash function. version_key (int): Version key for compatibility with the network. Default is ``int representation of @@ -4624,17 +5000,17 @@ async def set_weights( period: Optional[int] = 8, ): """ - Sets the interneuronal weights for the specified neuron. This process involves specifying the influence or - trust a neuron places on other neurons in the network, which is a fundamental aspect of Bittensor's - decentralized learning architecture. + Sets the weight vector for a neuron acting as a validator, specifying the weights assigned to subnet miners based on their performance evaluation. + + This method allows subnet validators to submit their weight vectors, which rank the value of each subnet miner's work. These weight vectors are used by the Yuma Consensus algorithm to compute emissions for both validators and miners. Arguments: - wallet (bittensor_wallet.Wallet): The wallet associated with the neuron setting the weights. + wallet (bittensor_wallet.Wallet): The wallet associated with the subnet validator setting the weights. netuid (int): The unique identifier of the subnet. - uids (Union[NDArray[np.int64], torch.LongTensor, list]): The list of neuron UIDs that the weights are being + uids (Union[NDArray[np.int64], torch.LongTensor, list]): The list of subnet miner neuron UIDs that the weights are being set for. weights (Union[NDArray[np.float32], torch.FloatTensor, list]): The corresponding weights to be set for each - UID. + UID, representing the validator's evaluation of each miner's performance. version_key (int): Version key for compatibility with the network. Default is int representation of the Bittensor version. wait_for_inclusion (bool): Waits for the transaction to be included in a block. Default is ``False``. From d93124d0ed22ff89bf94b4aeff5cb8becf7fc46b Mon Sep 17 00:00:00 2001 From: michael trestman Date: Tue, 8 Jul 2025 08:28:45 -0700 Subject: [PATCH 02/21] edit docstrings --- bittensor/core/async_subtensor.py | 38 +++++++++++++++++++++++-------- 1 file changed, 28 insertions(+), 10 deletions(-) diff --git a/bittensor/core/async_subtensor.py b/bittensor/core/async_subtensor.py index e29362dfb7..6f38dc52d5 100644 --- a/bittensor/core/async_subtensor.py +++ b/bittensor/core/async_subtensor.py @@ -146,23 +146,41 @@ def __init__( archive_endpoints: Optional[list[str]] = None, websocket_shutdown_timer: float = 5.0, ): - """ - Initializes an instance of the AsyncSubtensor class. + """Initializes an AsyncSubtensor instance for blockchain interaction. - Arguments: - network: The network name or type to connect to. - config: Configuration object for the AsyncSubtensor instance. - log_verbose: Enables or disables verbose logging. + + Args: + network: The network name or type to connect to (e.g., "finney", "test"). If None, uses the default network + from config. + config: Configuration object for the AsyncSubtensor instance. If None, uses the default configuration. + log_verbose: Enables or disables verbose logging. Defaults to False. fallback_endpoints: List of fallback endpoints to use if default or provided network is not available. - Defaults to `None`. - retry_forever: Whether to retry forever on connection errors. Defaults to `False`. - _mock: Whether this is a mock instance. Mainly just for use in testing. + Defaults to None. + retry_forever: Whether to retry forever on connection errors. Defaults to False. + _mock: Whether this is a mock instance. Mainly for testing purposes. Defaults to False. archive_endpoints: Similar to fallback_endpoints, but specifically only archive nodes. Will be used in cases where you are requesting a block that is too old for your current (presumably lite) node. Defaults to `None` + websocket_shutdown_timer: Amount of time, in seconds, to wait after the last response from the chain to close + the connection. Defaults to 5.0. + Returns: + None Raises: - Any exceptions raised during the setup, configuration, or connection process. + ConnectionError: If unable to connect to the specified network. + ValueError: If invalid network or configuration parameters are provided. + Exception: Any other exceptions raised during setup or configuration. + + Typical usage example: + + import bittensor as bt + import asyncio + + async def main(): + async with bt.AsyncSubtensor("finney") as subtensor: + block_hash = await subtensor.get_block_hash() + + asyncio.run(main()) """ if config is None: config = AsyncSubtensor.config() From 0f4632f0b41b25030f604a01f2a3d2c0ff976991 Mon Sep 17 00:00:00 2001 From: michael trestman Date: Tue, 8 Jul 2025 08:36:33 -0700 Subject: [PATCH 03/21] edit docstrings --- bittensor/core/async_subtensor.py | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/bittensor/core/async_subtensor.py b/bittensor/core/async_subtensor.py index 6f38dc52d5..85b858833a 100644 --- a/bittensor/core/async_subtensor.py +++ b/bittensor/core/async_subtensor.py @@ -1085,7 +1085,7 @@ async def difficulty( block=1000000 ) - See also: See + See also: """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) call = await self.get_hyperparameter( @@ -1998,8 +1998,10 @@ async def get_hotkey_owner( Returns: Optional[str]: The SS58 address of the owner if the hotkey exists, or None if it doesn't. - See also: See , - See + See also: + - + - + - """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) hk_owner_query = await self.substrate.query( @@ -2069,8 +2071,9 @@ async def get_metagraph_info( field_indices=[SelectiveMetagraphIndex.Name, SelectiveMetagraphIndex.OwnerHotkeys] ) - See also: See , - See + See also: + - + - """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) if not block_hash and reuse_block: From dadd03b6424b671f9d666eb4ce03f739d3098fad Mon Sep 17 00:00:00 2001 From: michael trestman Date: Tue, 8 Jul 2025 09:47:29 -0700 Subject: [PATCH 04/21] edit docstrings --- bittensor/core/async_subtensor.py | 35 ++++++++++++++++++------------- 1 file changed, 21 insertions(+), 14 deletions(-) diff --git a/bittensor/core/async_subtensor.py b/bittensor/core/async_subtensor.py index 85b858833a..af9173478d 100644 --- a/bittensor/core/async_subtensor.py +++ b/bittensor/core/async_subtensor.py @@ -1040,7 +1040,7 @@ async def commit_reveal_enabled( block=1000000 ) - See also: See + See also: """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) call = await self.get_hyperparameter( @@ -1462,16 +1462,18 @@ async def get_children_pending( list[tuple[float, str]], int, ]: - """ - This method retrieves the pending children of a given hotkey and netuid. - It queries the SubtensorModule's PendingChildKeys storage function. + """Retrieves the pending children of a given hotkey and netuid. - Arguments: - hotkey (str): The hotkey value. - netuid (int): The netuid value. - block (Optional[int]): The block number for which the children are to be retrieved. - block_hash (Optional[str]): The hash of the block to retrieve the subnet unique identifiers from. - reuse_block (bool): Whether to reuse the last-used block hash. + This method queries the SubtensorModule's PendingChildKeys storage function to get children that are + pending approval or in a cooldown period. These are children that have been proposed but not yet + finalized. + + Args: + hotkey: The hotkey value. + netuid: The netuid value. + block: The block number for which the children are to be retrieved. + block_hash: The hash of the block to retrieve the subnet unique identifiers from. + reuse_block: Whether to reuse the last-used block hash. Returns: list[tuple[float, str]]: A list of children with their proportions. @@ -1963,6 +1965,7 @@ async def get_existential_deposit( storage and preventing the proliferation of dust accounts. See also: See + See also: """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) result = await self.substrate.get_constant( @@ -2491,6 +2494,8 @@ async def get_next_epoch_start_block( Returns: int: The block number at which the next epoch will start. + + See also: """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) blocks_since_last_step = await self.blocks_since_last_step( @@ -4682,8 +4687,9 @@ async def reveal_weights( tuple[bool, str]: ``True`` if the weight revelation is successful, False otherwise. And `msg`, a string value describing the success or potential error. - This function allows neurons to reveal their previously committed weight distribution, ensuring transparency - and accountability within the Bittensor network. + This function allows subnet validators to reveal their previously committed weight vector. + + See also: , """ retries = 0 success = False @@ -5047,8 +5053,9 @@ async def set_weights( tuple[bool, str]: ``True`` if the setting of weights is successful, False otherwise. And `msg`, a string value describing the success or potential error. - This function is crucial in shaping the network's collective intelligence, where each neuron's learning and - contribution are influenced by the weights it sets towards others【81†source】. + This function is crucial in the Yuma Consensus mechanism, where each validator's weight vector contributes to the overall weight matrix used to calculate emissions and maintain network consensus. + + See """ async def _blocks_weight_limit() -> bool: From 4cfe086666c2b67814c703dce2d17508c94303fd Mon Sep 17 00:00:00 2001 From: Roman Date: Tue, 8 Jul 2025 10:27:43 -0700 Subject: [PATCH 05/21] ruff --- bittensor/core/async_subtensor.py | 102 +++++++++++++++--------------- 1 file changed, 51 insertions(+), 51 deletions(-) diff --git a/bittensor/core/async_subtensor.py b/bittensor/core/async_subtensor.py index af9173478d..92d3ae0259 100644 --- a/bittensor/core/async_subtensor.py +++ b/bittensor/core/async_subtensor.py @@ -179,7 +179,7 @@ def __init__( async def main(): async with bt.AsyncSubtensor("finney") as subtensor: block_hash = await subtensor.get_block_hash() - + asyncio.run(main()) """ if config is None: @@ -220,10 +220,10 @@ async def close(self): Example: subtensor = AsyncSubtensor(network="finney") await subtensor.initialize() - + # Use the subtensor... balance = await subtensor.get_balance("5F...") - + # Close when done await subtensor.close() """ @@ -244,13 +244,13 @@ async def initialize(self): Example: subtensor = AsyncSubtensor(network="finney") - + # Initialize the connection await subtensor.initialize() - + # Now you can make queries balance = await subtensor.get_balance("5F...") - + # Or chain the initialization subtensor = await AsyncSubtensor(network="finney").initialize() """ @@ -321,10 +321,10 @@ async def determine_block_hash( Example: # Get hash for specific block block_hash = await subtensor.determine_block_hash(block=1000000) - + # Use provided block hash hash = await subtensor.determine_block_hash(block_hash="0x1234...") - + # Reuse last block hash hash = await subtensor.determine_block_hash(reuse_block=True) """ @@ -371,14 +371,14 @@ async def encode_params( {"name": "coldkey_ss58", "type": "str"} ] } - + # Encode parameters as a dictionary params_dict = { "amount": 1000000, "coldkey_ss58": "5F..." } encoded = await subtensor.encode_params(call_def, params_dict) - + # Or encode as a list (positional) params_list = [1000000, "5F..."] encoded = await subtensor.encode_params(call_def, params_list) @@ -426,14 +426,14 @@ async def get_hyperparameter( Example: # Get difficulty for subnet 1 difficulty = await subtensor.get_hyperparameter("Difficulty", netuid=1) - + # Get tempo at a specific block tempo = await subtensor.get_hyperparameter( - "Tempo", - netuid=1, + "Tempo", + netuid=1, block=1000000 ) - + # Get immunity period using block hash immunity = await subtensor.get_hyperparameter( "ImmunityPeriod", @@ -472,7 +472,7 @@ def _get_substrate( RetryAsyncSubstrate depending on the configuration parameters. Args: - fallback_endpoints: List of fallback endpoints to use if default or provided network is not available. + fallback_endpoints: List of fallback endpoints to use if default or provided network is not available. Defaults to None. retry_forever: Whether to retry forever on connection errors. Defaults to `False`. _mock: Whether this is a mock instance. Mainly for testing purposes. Defaults to False. @@ -543,10 +543,10 @@ async def query_constant( Example: # Get existential deposit constant existential_deposit = await subtensor.query_constant( - "Balances", + "Balances", "ExistentialDeposit" ) - + # Get constant at specific block constant = await subtensor.query_constant( "SubtensorModule", @@ -601,7 +601,7 @@ async def query_map( "Bonds", params=[1] ) - + # Query weights at specific block weights = await subtensor.query_map( "SubtensorModule", @@ -609,7 +609,7 @@ async def query_map( params=[1], block=1000000 ) - + """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) result = await self.substrate.query_map( @@ -871,10 +871,10 @@ async def blocks_since_last_step( Example: # Get blocks since last step for subnet 1 blocks = await subtensor.blocks_since_last_step(netuid=1) - + # Get blocks since last step at specific block blocks = await subtensor.blocks_since_last_step( - netuid=1, + netuid=1, block=1000000 ) """ @@ -902,7 +902,7 @@ async def blocks_since_last_update(self, netuid: int, uid: int) -> Optional[int] Example: # Get blocks since last update for UID 5 in subnet 1 blocks = await subtensor.blocks_since_last_update(netuid=1, uid=5) - + # Check if neuron needs updating blocks_since_update = await subtensor.blocks_since_last_update(netuid=1, uid=10) @@ -985,7 +985,7 @@ async def commit( netuid=1, data="Hello Bittensor!" ) - + # Commit with custom period success = await subtensor.commit( wallet=my_wallet, @@ -1016,9 +1016,9 @@ async def commit_reveal_enabled( ) -> bool: """Check if commit-reveal mechanism is enabled for a given subnet at a specific block. - The commit reveal feature is designed to solve the weight-copying problem by giving would-be weight-copiers + The commit reveal feature is designed to solve the weight-copying problem by giving would-be weight-copiers access only to stale weights. Copying stale weights should result in subnet validators departing from consensus. - + Args: netuid: The unique identifier of the subnet for which to check the commit-reveal mechanism. block: The block number to query. Do not specify if using block_hash or reuse_block. @@ -1033,10 +1033,10 @@ async def commit_reveal_enabled( Example: # Check if commit-reveal is enabled for subnet 1 enabled = await subtensor.commit_reveal_enabled(netuid=1) - + # Check at specific block enabled = await subtensor.commit_reveal_enabled( - netuid=1, + netuid=1, block=1000000 ) @@ -1078,10 +1078,10 @@ async def difficulty( Example: # Get difficulty for subnet 1 difficulty = await subtensor.difficulty(netuid=1) - + # Get difficulty at specific block difficulty = await subtensor.difficulty( - netuid=1, + netuid=1, block=1000000 ) @@ -1122,10 +1122,10 @@ async def does_hotkey_exist( Example: # Check if hotkey exists exists = await subtensor.does_hotkey_exist("5F...") - + # Check at specific block exists = await subtensor.does_hotkey_exist( - "5F...", + "5F...", block=1000000 ) """ @@ -1154,7 +1154,7 @@ async def get_all_subnets_info( """Retrieves detailed information about all subnets within the Bittensor network. This function provides comprehensive data on each subnet, including its characteristics and operational - parameters. + parameters. Args: block: The block number for the query. @@ -1167,10 +1167,10 @@ async def get_all_subnets_info( Example: # Get all subnet information subnets = await subtensor.get_all_subnets_info() - + # Get at specific block subnets = await subtensor.get_all_subnets_info(block=1000000) - + # Iterate over subnet information for subnet in subnets: print(f"Subnet {subnet.netuid}: {subnet.name}") @@ -1219,14 +1219,14 @@ async def get_balance( # Get balance for an address balance = await subtensor.get_balance("5F...") print(f"Balance: {balance.tao} TAO") - + # Get balance at specific block balance = await subtensor.get_balance( - "5F...", + "5F...", block=1000000 ) - See also: See , + See also: See , See """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) @@ -1264,12 +1264,12 @@ async def get_balances( Example: # Get balances for multiple addresses balances = await subtensor.get_balances( - "5F...", - "5G...", + "5F...", + "5G...", "5H..." ) - See also: See , + See also: See , See """ if reuse_block: @@ -1308,7 +1308,7 @@ async def get_current_block(self) -> int: # Get current block number current_block = await subtensor.get_current_block() print(f"Current block: {current_block}") - + block = await subtensor.get_current_block() if block > 1000000: @@ -1340,7 +1340,7 @@ async def get_block_hash(self, block: Optional[int] = None) -> str: # Get hash for specific block block_hash = await subtensor.get_block_hash(1000000) print(f"Block 1000000 hash: {block_hash}") - + # Get latest block hash latest_hash = await subtensor.get_block_hash() print(f"Latest block hash: {latest_hash}") @@ -1424,7 +1424,7 @@ async def get_children( hotkey="5F...", netuid=1 ) - + if success: for proportion, child_hotkey in children: print(f"Child {child_hotkey}: {proportion}") @@ -1532,11 +1532,11 @@ async def get_commitment( # Get commitment for UID 5 in subnet 1 commitment = await subtensor.get_commitment(netuid=1, uid=5) print(f"Commitment: {commitment}") - + # Get commitment at specific block commitment = await subtensor.get_commitment( - netuid=1, - uid=5, + netuid=1, + uid=5, block=1000000 ) """ @@ -1610,7 +1610,7 @@ async def get_all_commitments( Example: # Get all commitments for subnet 1 commitments = await subtensor.get_all_commitments(netuid=1) - + # Iterate over all commitments for hotkey, commitment in commitments.items(): print(f"Hotkey {hotkey}: {commitment}") @@ -2048,8 +2048,8 @@ async def get_metagraph_info( """ Retrieves full or partial metagraph information for the specified subnet (netuid). - A metagraph is a data structure that contains comprehensive information about the current state of a subnet, - including detailed information on all the nodes (neurons) such as subnet validator stakes and subnet weights + A metagraph is a data structure that contains comprehensive information about the current state of a subnet, + including detailed information on all the nodes (neurons) such as subnet validator stakes and subnet weights in the subnet. Metagraph aids in calculating emissions. Arguments: @@ -4350,7 +4350,7 @@ async def commit_weights( This function allows subnet validators to create a tamper-proof record of their weight vector at a specific point in time, creating a foundation of transparency and accountability for the Bittensor network. - See also: See , + See also: See , See """ retries = 0 @@ -4689,7 +4689,7 @@ async def reveal_weights( This function allows subnet validators to reveal their previously committed weight vector. - See also: , + See also: , """ retries = 0 success = False From dfa477e55d0f73676dd1fd6094110d2aec9b28e1 Mon Sep 17 00:00:00 2001 From: michael trestman Date: Tue, 8 Jul 2025 11:08:02 -0700 Subject: [PATCH 06/21] edit docstrings --- bittensor/core/async_subtensor.py | 16 +++++----------- 1 file changed, 5 insertions(+), 11 deletions(-) diff --git a/bittensor/core/async_subtensor.py b/bittensor/core/async_subtensor.py index 92d3ae0259..a63e0a439d 100644 --- a/bittensor/core/async_subtensor.py +++ b/bittensor/core/async_subtensor.py @@ -1179,7 +1179,7 @@ async def get_all_subnets_info( Gaining insights into the subnets' details assists in understanding the network's composition, the roles of different subnets, and their unique features. - See also: See + See also: """ result = await self.query_runtime_api( runtime_api="SubnetInfoRuntimeApi", @@ -1226,8 +1226,6 @@ async def get_balance( block=1000000 ) - See also: See , - See """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) balance = await self.substrate.query( @@ -1269,8 +1267,6 @@ async def get_balances( "5H..." ) - See also: See , - See """ if reuse_block: block_hash = self.substrate.last_block_hash @@ -1314,7 +1310,7 @@ async def get_current_block(self) -> int: if block > 1000000: print("Network has progressed past block 1M") - See also: See + See also: """ return await self.substrate.get_block_number(None) @@ -1345,7 +1341,7 @@ async def get_block_hash(self, block: Optional[int] = None) -> str: latest_hash = await subtensor.get_block_hash() print(f"Latest block hash: {latest_hash}") - See also: See + See also: """ if block: return await self._get_block_hash(block) @@ -1964,8 +1960,6 @@ async def get_existential_deposit( The existential deposit is a fundamental economic parameter in the Bittensor network, ensuring efficient use of storage and preventing the proliferation of dust accounts. - See also: See - See also: """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) result = await self.substrate.get_constant( @@ -4350,8 +4344,8 @@ async def commit_weights( This function allows subnet validators to create a tamper-proof record of their weight vector at a specific point in time, creating a foundation of transparency and accountability for the Bittensor network. - See also: See , - See + See also: See , + """ retries = 0 success = False From 3170994ba523adc22421c486d8a1d7238f856df3 Mon Sep 17 00:00:00 2001 From: michael trestman Date: Tue, 8 Jul 2025 11:22:25 -0700 Subject: [PATCH 07/21] edit docstrings --- bittensor/core/async_subtensor.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/bittensor/core/async_subtensor.py b/bittensor/core/async_subtensor.py index a63e0a439d..ff10f1917d 100644 --- a/bittensor/core/async_subtensor.py +++ b/bittensor/core/async_subtensor.py @@ -4344,8 +4344,8 @@ async def commit_weights( This function allows subnet validators to create a tamper-proof record of their weight vector at a specific point in time, creating a foundation of transparency and accountability for the Bittensor network. - See also: See , - + See also: , + """ retries = 0 success = False From 76a9784142248616ba4edc3e8ec79e2262c59697 Mon Sep 17 00:00:00 2001 From: michael trestman Date: Tue, 8 Jul 2025 12:48:22 -0700 Subject: [PATCH 08/21] docstrings edits --- bittensor/core/async_subtensor.py | 251 +++++++++++++++--------------- 1 file changed, 125 insertions(+), 126 deletions(-) diff --git a/bittensor/core/async_subtensor.py b/bittensor/core/async_subtensor.py index ff10f1917d..d0c53ffc74 100644 --- a/bittensor/core/async_subtensor.py +++ b/bittensor/core/async_subtensor.py @@ -149,20 +149,20 @@ def __init__( """Initializes an AsyncSubtensor instance for blockchain interaction. - Args: + Arguments: network: The network name or type to connect to (e.g., "finney", "test"). If None, uses the default network from config. config: Configuration object for the AsyncSubtensor instance. If None, uses the default configuration. - log_verbose: Enables or disables verbose logging. Defaults to False. + log_verbose: Enables or disables verbose logging. Defaults to `False`. fallback_endpoints: List of fallback endpoints to use if default or provided network is not available. - Defaults to None. - retry_forever: Whether to retry forever on connection errors. Defaults to False. - _mock: Whether this is a mock instance. Mainly for testing purposes. Defaults to False. + Defaults to `None`. + retry_forever: Whether to retry forever on connection errors. Defaults to `False`. + _mock: Whether this is a mock instance. Mainly for testing purposes. Defaults to `False`. archive_endpoints: Similar to fallback_endpoints, but specifically only archive nodes. Will be used in cases where you are requesting a block that is too old for your current (presumably lite) node. Defaults to - `None` + `None`. websocket_shutdown_timer: Amount of time, in seconds, to wait after the last response from the chain to close - the connection. Defaults to 5.0. + the connection. Defaults to `5.0`. Returns: None @@ -307,7 +307,7 @@ async def determine_block_hash( Ensures that only one of the block specification parameters is used and returns the appropriate block hash for blockchain queries. - Args: + Arguments: block: The block number to get the hash for. Do not specify if using block_hash or reuse_block. block_hash: The hash of the blockchain block. Do not specify if using block or reuse_block. reuse_block: Whether to reuse the last-used block hash. Do not set if using block or block_hash. @@ -351,7 +351,7 @@ async def encode_params( This method takes a call definition (which specifies parameter types) and actual parameter values, then encodes them into a hex string that can be used for blockchain transactions. - Args: + Arguments: call_definition: A dictionary containing parameter type definitions. Should have a "params" key with a list of parameter definitions. params: The actual parameter values to encode. Can be either a list (for positional parameters) or a @@ -377,11 +377,11 @@ async def encode_params( "amount": 1000000, "coldkey_ss58": "5F..." } - encoded = await subtensor.encode_params(call_def, params_dict) + encoded = await subtensor.encode_params(call_definition=call_def, params=params_dict) # Or encode as a list (positional) params_list = [1000000, "5F..."] - encoded = await subtensor.encode_params(call_def, params_list) + encoded = await subtensor.encode_params(call_definition=call_def, params=params_list) """ param_data = scalecodec.ScaleBytes(b"") @@ -410,13 +410,13 @@ async def get_hyperparameter( This method queries the blockchain for subnet-specific hyperparameters such as difficulty, tempo, immunity period, and other network configuration values. - Args: - param_name (str): The name of the hyperparameter to retrieve (e.g., "Difficulty", "Tempo", + Arguments: + param_name: The name of the hyperparameter to retrieve (e.g., "Difficulty", "Tempo", "ImmunityPeriod"). - netuid (int): The unique identifier of the subnet. - block (Optional[int]): The block number at which to retrieve the hyperparameter. Do not specify if using + netuid: The unique identifier of the subnet. + block: The block number at which to retrieve the hyperparameter. Do not specify if using block_hash or reuse_block. - block_hash (Optional[str]): The hash of the blockchain block for the query. Do not specify if using block or + block_hash: The hash of the blockchain block for the query. Do not specify if using block or reuse_block. reuse_block: Whether to reuse the last-used block hash. Do not set if using block_hash or block. @@ -425,18 +425,18 @@ async def get_hyperparameter( Example: # Get difficulty for subnet 1 - difficulty = await subtensor.get_hyperparameter("Difficulty", netuid=1) + difficulty = await subtensor.get_hyperparameter(param_name="Difficulty", netuid=1) # Get tempo at a specific block tempo = await subtensor.get_hyperparameter( - "Tempo", + param_name="Tempo", netuid=1, block=1000000 ) # Get immunity period using block hash immunity = await subtensor.get_hyperparameter( - "ImmunityPeriod", + param_name="ImmunityPeriod", netuid=1, block_hash="0x1234..." ) @@ -471,14 +471,14 @@ def _get_substrate( This internal method creates either a standard AsyncSubstrateInterface or a RetryAsyncSubstrate depending on the configuration parameters. - Args: + Arguments: fallback_endpoints: List of fallback endpoints to use if default or provided network is not available. - Defaults to None. + Defaults to `None`. retry_forever: Whether to retry forever on connection errors. Defaults to `False`. - _mock: Whether this is a mock instance. Mainly for testing purposes. Defaults to False. + _mock: Whether this is a mock instance. Mainly for testing purposes. Defaults to `False`. archive_endpoints: Similar to fallback_endpoints, but specifically only archive nodes. Will be used in cases where you are requesting a block that is too old for your current (presumably lite) node. Defaults to - `None` + `None`. ws_shutdown_timer: Amount of time, in seconds, to wait after the last response from the chain to close the connection. @@ -526,16 +526,16 @@ async def query_constant( consensus rules, or validation thresholds, providing a deeper understanding of the Bittensor network's operational parameters. - Args: + Arguments: module_name: The name of the module containing the constant (e.g., "Balances", "SubtensorModule"). constant_name: The name of the constant to retrieve (e.g., "ExistentialDeposit"). - block (Optional[int]): The blockchain block number at which to query the constant. Do not + block: The blockchain block number at which to query the constant. Do not specify if using block_hash or reuse_block. - block_hash (Optional[str]): The hash of the blockchain block at which to query the constant. + block_hash: The hash of the blockchain block at which to query the constant. Do not specify if using block or reuse_block. - reuse_block (bool): Whether to reuse the blockchain block at which to query the - constant. Defaults to False. + reuse_block: Whether to reuse the blockchain block at which to query the + constant. Defaults to `False`. Returns: Optional[async_substrate_interface.types.ScaleObj]: The value of the constant if found, `None` otherwise. @@ -549,8 +549,8 @@ async def query_constant( # Get constant at specific block constant = await subtensor.query_constant( - "SubtensorModule", - "SomeConstant", + module_name="SubtensorModule", + constant_name="SomeConstant", block=1000000 ) """ @@ -577,18 +577,18 @@ async def query_map( essential for accessing complex and structured data within the blockchain modules. - Args: + Arguments: module: The name of the module from which to query the map storage (e.g., "SubtensorModule", "System"). name: The specific storage function within the module to query (e.g., "Bonds", "Weights"). - block (Optional[int]): The blockchain block number at which to perform the query. - Defaults to None (latest block). - block_hash (Optional[str]): The hash of the block to retrieve the parameter from. Do not + block: The blockchain block number at which to perform the query. + Defaults to `None` (latest block). + block_hash: The hash of the block to retrieve the parameter from. Do not specify if using block or reuse_block. - reuse_block (bool): Whether to use the last-used block. Do not set if using - block_hash or block. Defaults to False. - params (Optional[list]): Parameters to be passed to the query. Defaults to None. + reuse_block: Whether to use the last-used block. Do not set if using + block_hash or block. Defaults to `False`. + params: Parameters to be passed to the query. Defaults to `None`. Returns: AsyncQueryMapResult: A data structure representing the map storage if found, @@ -597,15 +597,15 @@ async def query_map( Example: # Query bonds for subnet 1 bonds = await subtensor.query_map( - "SubtensorModule", - "Bonds", + module="SubtensorModule", + name="Bonds", params=[1] ) # Query weights at specific block weights = await subtensor.query_map( - "SubtensorModule", - "Weights", + module="SubtensorModule", + name="Weights", params=[1], block=1000000 ) @@ -633,11 +633,11 @@ async def query_map_subtensor( Queries map storage from the Subtensor module on the Bittensor blockchain. This function is designed to retrieve a map-like data structure, which can include various neuron-specific details or network-wide attributes. - Args: + Arguments: name: The name of the map storage function to query. block: The blockchain block number at which to perform the query. block_hash: The hash of the block to retrieve the parameter from. Do not specify if using block or - reuse_block + reuse_block. reuse_block: Whether to use the last-used block. Do not set if using block_hash or block. params: A list of parameters to pass to the query function. @@ -670,14 +670,14 @@ async def query_module( function is a generic query interface that allows for flexible and diverse data retrieval from various blockchain modules. - Args: - module (str): The name of the module from which to query data. - name (str): The name of the storage function within the module. - block (Optional[int]): The blockchain block number at which to perform the query. + Arguments: + module: The name of the module from which to query data. + name: The name of the storage function within the module. + block: The blockchain block number at which to perform the query. block_hash: The hash of the block to retrieve the parameter from. Do not specify if using block or - reuse_block + reuse_block. reuse_block: Whether to use the last-used block. Do not set if using block_hash or block. - params (Optional[list[object]]): A list of parameters to pass to the query function. + params: A list of parameters to pass to the query function. Returns: An object containing the requested data if found, `None` otherwise. @@ -708,14 +708,14 @@ async def query_runtime_api( retrieve data encoded in Scale Bytes format. This function is essential for advanced users who need to interact with specific runtime methods and decode complex data types. - Args: + Arguments: runtime_api: The name of the runtime API to query. method: The specific method within the runtime API to call. params: The parameters to pass to the method call. - block: the block number for this query. Do not specify if using block_hash or reuse_block + block: the block number for this query. Do not specify if using block_hash or reuse_block. block_hash: The hash of the blockchain block number at which to perform the query. Do not specify if - using block or reuse_block - reuse_block: Whether to reuse the last-used block hash. Do not set if using block_hash or block + using block or reuse_block. + reuse_block: Whether to reuse the last-used block hash. Do not set if using block_hash or block. Returns: The decoded result from the runtime API call, or `None` if the call fails. @@ -743,11 +743,11 @@ async def query_subtensor( Queries named storage from the Subtensor module on the Bittensor blockchain. This function is used to retrieve specific data or parameters from the blockchain, such as stake, rank, or other neuron-specific attributes. - Args: + Arguments: name: The name of the storage function to query. block: The blockchain block number at which to perform the query. block_hash: The hash of the block to retrieve the parameter from. Do not specify if using block or - reuse_block + reuse_block. reuse_block: Whether to use the last-used block. Do not set if using block_hash or block. params: A list of parameters to pass to the query function. @@ -778,12 +778,12 @@ async def state_call( Makes a state call to the Bittensor blockchain, allowing for direct queries of the blockchain's state. This function is typically used for advanced queries that require specific method calls and data inputs. - Args: + Arguments: method: The method name for the state call. data: The data to be passed to the method. block: The blockchain block number at which to perform the state call. block_hash: The hash of the block to retrieve the parameter from. Do not specify if using block or - reuse_block + reuse_block. reuse_block: Whether to use the last-used block. Do not set if using block_hash or block. Returns: @@ -815,12 +815,12 @@ async def all_subnets( """Queries the blockchain for comprehensive information about all subnets, including their dynamic parameters and operational status. - Args: - block_number (Optional[int]): The block number to query the subnet information from. Do not + Arguments: + block_number: The block number to query the subnet information from. Do not specify if using block_hash or reuse_block. - block_hash (Optional[str]): The hash of the blockchain block number for the query. Do not + block_hash: The hash of the blockchain block number for the query. Do not specify if using reuse_block or block. - reuse_block (bool): Whether to reuse the last-used blockchain block hash. Do not + reuse_block: Whether to reuse the last-used blockchain block hash. Do not set if using block_hash or block. Returns: @@ -855,13 +855,13 @@ async def blocks_since_last_step( """Queries the blockchain to determine how many blocks have passed since the last epoch step for a specific subnet. - Args: - netuid (int): The unique identifier of the subnetwork. - block (Optional[int]): The block number for this query. Do not specify if using + Arguments: + netuid: The unique identifier of the subnetwork. + block: The block number for this query. Do not specify if using block_hash or reuse_block. - block_hash (Optional[str]): The hash of the blockchain block number for the query. Do not + block_hash: The hash of the blockchain block number for the query. Do not specify if using reuse_block or block. - reuse_block (bool): Whether to reuse the last-used blockchain block hash. Do not + reuse_block: Whether to reuse the last-used blockchain block hash. Do not set if using block_hash or block. Returns: @@ -891,9 +891,9 @@ async def blocks_since_last_update(self, netuid: int, uid: int) -> Optional[int] """Returns the number of blocks since the last update, or ``None`` if the subnetwork or UID does not exist. - Args: - netuid (int): The unique identifier of the subnetwork. - uid (int): The unique identifier of the neuron. + Arguments: + netuid: The unique identifier of the subnetwork. + uid: The unique identifier of the neuron. Returns: Optional[int]: The number of blocks since the last update, or None if the @@ -924,7 +924,7 @@ async def bonds( of incentivizing high-quality performance by subnet miners, and honest evaluation by subnet validators. - Args: + Arguments: netuid (int): The unique identifier of the subnet. block (Optional[int]): The block number for this query. Do not specify if using block_hash or reuse_block. @@ -967,7 +967,7 @@ async def commit( This method allows neurons to publish arbitrary data to the blockchain, which can be used for various purposes such as sharing model updates, configuration data, or other network-relevant information. - Args: + Arguments: wallet: The wallet associated with the neuron committing the data. netuid: The unique identifier of the subnet. data: The data to be committed to the network. @@ -1019,7 +1019,7 @@ async def commit_reveal_enabled( The commit reveal feature is designed to solve the weight-copying problem by giving would-be weight-copiers access only to stale weights. Copying stale weights should result in subnet validators departing from consensus. - Args: + Arguments: netuid: The unique identifier of the subnet for which to check the commit-reveal mechanism. block: The block number to query. Do not specify if using block_hash or reuse_block. block_hash: The block hash at which to check the parameter. Do not set if using block or @@ -1065,7 +1065,7 @@ async def difficulty( setting the computational effort required for validating transactions and participating in the network's consensus mechanism. - Args: + Arguments: netuid: The unique identifier of the subnet. block: The block number for the query. Do not specify if using block_hash or reuse_block. block_hash: The hash of the block to retrieve the parameter from. Do not specify if using block or @@ -1109,7 +1109,7 @@ async def does_hotkey_exist( This method queries the SubtensorModule's Owner storage function to determine if the hotkey is registered. - Args: + Arguments: hotkey_ss58: The SS58 address of the hotkey. block: The block number for this query. Do not specify if using block_hash or reuse_block. block_hash: The hash of the block number to check the hotkey against. Do not specify if using reuse_block @@ -1156,7 +1156,7 @@ async def get_all_subnets_info( This function provides comprehensive data on each subnet, including its characteristics and operational parameters. - Args: + Arguments: block: The block number for the query. block_hash: The block hash for the query. reuse_block: Whether to reuse the last-used block hash. @@ -1206,7 +1206,7 @@ async def get_balance( This method queries the System module's Account storage to get the current balance of a coldkey address. The balance represents the amount of TAO tokens held by the specified address. - Args: + Arguments: address: The coldkey address in SS58 format. block: The block number for the query. block_hash: The block hash for the query. @@ -1250,7 +1250,7 @@ async def get_balances( dictionary mapping each address to its corresponding balance. This is more efficient than calling get_balance multiple times. - Args: + Arguments: *addresses: Variable number of coldkey addresses in SS58 format. block: The block number for the query. block_hash: The block hash for the query. @@ -1326,7 +1326,7 @@ async def get_block_hash(self, block: Optional[int] = None) -> str: providing a secure reference to each block's data. It is crucial for verifying transactions, ensuring data consistency, and maintaining the trustworthiness of the blockchain. - Args: + Arguments: block: The block number for which the hash is to be retrieved. If None, returns the latest block hash. Returns: @@ -1403,7 +1403,7 @@ async def get_children( before returning as a tuple. It provides information about the child neurons that a validator has set for weight distribution. - Args: + Arguments: hotkey: The hotkey value. netuid: The netuid value. block: The block number for which the children are to be retrieved. @@ -1464,7 +1464,7 @@ async def get_children_pending( pending approval or in a cooldown period. These are children that have been proposed but not yet finalized. - Args: + Arguments: hotkey: The hotkey value. netuid: The netuid value. block: The block number for which the children are to be retrieved. @@ -1513,7 +1513,7 @@ async def get_commitment( This method retrieves the commitment data that a neuron has published to the blockchain. Commitments are used in the commit-reveal mechanism for secure weight setting and other network operations. - Args: + Arguments: netuid (int): The unique identifier of the subnetwork. uid (int): The unique identifier of the neuron. block (Optional[int]): The block number to retrieve the commitment from. If None, the latest block is used. @@ -1593,7 +1593,7 @@ async def get_all_commitments( This method retrieves all commitment data for all neurons in a specific subnet. This is useful for analyzing the commit-reveal patterns across an entire subnet. - Args: + Arguments: netuid (int): The unique identifier of the subnetwork. block (Optional[int]): The block number to retrieve the commitment from. If None, the latest block is used. Default is None. @@ -2262,7 +2262,7 @@ async def get_liquidity_list( Retrieves all liquidity positions for the given wallet on a specified subnet (netuid). Calculates associated fee rewards based on current global and tick-level fee data. - Args: + Arguments: wallet: Wallet instance to fetch positions for. netuid: Subnet unique id. block: The blockchain block number for the query. @@ -2431,12 +2431,11 @@ async def get_neuron_for_pubkey_and_subnet( (netuid). This function provides detailed neuron information for a particular subnet within the Bittensor network. - Arguments: - hotkey_ss58 (str): The ``SS58`` address of the neuron's hotkey. + Arguments:(str): The ``SS58`` address of the neuron's hotkey. netuid (int): The unique identifier of the subnet. block (Optional[int]): The blockchain block number for the query. - block_hash (Optional[int]): The blockchain block number at which to perform the query. - reuse_block (bool): Whether to reuse the last-used blockchain block hash. + block_hash: The blockchain block number at which to perform the query. + reuse_block: Whether to reuse the last-used blockchain block hash. Returns: Optional[bittensor.core.chain_data.neuron_info.NeuronInfo]: Detailed information about the neuron if found, @@ -2478,12 +2477,12 @@ async def get_next_epoch_start_block( determined based on the subnet's tempo (i.e., blocks per epoch). The result is the block number at which the next epoch will begin. - Args: - netuid (int): The unique identifier of the subnet. - block (Optional[int], optional): The reference block to calculate from. + Arguments: + netuid: The unique identifier of the subnet. + block: The reference block to calculate from. If None, uses the current chain block height. - block_hash (Optional[int]): The blockchain block number at which to perform the query. - reuse_block (bool): Whether to reuse the last-used blockchain block hash. + block_hash: The blockchain block number at which to perform the query. + reuse_block: Whether to reuse the last-used blockchain block hash. Returns: @@ -2513,7 +2512,7 @@ async def get_owned_hotkeys( """ Retrieves all hotkeys owned by a specific coldkey address. - Args: + Arguments: coldkey_ss58 (str): The SS58 address of the coldkey to query. block (int): The blockchain block number for the query. block_hash (str): The hash of the blockchain block number for the query. @@ -2545,7 +2544,7 @@ async def get_stake( """ Returns the stake under a coldkey - hotkey pairing. - Args: + Arguments: hotkey_ss58 (str): The SS58 address of the hotkey. coldkey_ss58 (str): The SS58 address of the coldkey. netuid (int): The subnet ID. @@ -2600,7 +2599,7 @@ async def get_stake_add_fee( """ Calculates the fee for adding new stake to a hotkey. - Args: + Arguments: amount: Amount of stake to add in TAO netuid: Netuid of subnet coldkey_ss58: SS58 address of source coldkey @@ -2671,7 +2670,7 @@ async def get_unstake_fee( """ Calculates the fee for unstaking from a hotkey. - Args: + Arguments: amount: Amount of stake to unstake in TAO netuid: Netuid of subnet coldkey_ss58: SS58 address of source coldkey @@ -2709,7 +2708,7 @@ async def get_stake_movement_fee( """ Calculates the fee for moving stake between hotkeys/subnets/coldkeys. - Args: + Arguments: amount: Amount of stake to move in TAO origin_netuid: Netuid of source subnet origin_hotkey_ss58: SS58 address of source hotkey @@ -2795,7 +2794,7 @@ async def get_stake_for_coldkey( """ Retrieves the stake information for a given coldkey. - Args: + Arguments: coldkey_ss58 (str): The SS58 address of the coldkey. block (Optional[int]): The block number at which to query the stake information. block_hash (Optional[str]): The hash of the blockchain block number for the query. @@ -2832,7 +2831,7 @@ async def get_stake_for_hotkey( """ Retrieves the stake information for a given hotkey. - Args: + Arguments: hotkey_ss58: The SS58 address of the hotkey. netuid: The subnet ID to query for. block: The block number at which to query the stake information. Do not specify if also specifying @@ -2863,12 +2862,12 @@ async def get_subnet_burn_cost( ) -> Optional[Balance]: """ Retrieves the burn cost for registering a new subnet within the Bittensor network. This cost represents the - amount of Tao that needs to be locked or burned to establish a new subnet. + amount of Tao that needs to be locked or burned to establish a new Arguments: block (Optional[int]): The blockchain block number for the query. - block_hash (Optional[int]): The blockchain block_hash of the block id. - reuse_block (bool): Whether to reuse the last-used block hash. + block_hash: The blockchain block_hash of the block id. + reuse_block: Whether to reuse the last-used block hash. Returns: int: The burn cost for subnet registration. @@ -3179,7 +3178,7 @@ async def immunity_period( Retrieves the 'ImmunityPeriod' hyperparameter for a specific subnet. This parameter defines the duration during which new neurons are protected from certain network penalties or restrictions. - Args: + Arguments: netuid (int): The unique identifier of the subnet. block (Optional[int]): The blockchain block number for the query. block_hash (Optional[str]): The blockchain block_hash representation of the block id. @@ -3250,7 +3249,7 @@ async def is_hotkey_registered( identified by its hotkey, which is crucial for validating its participation and activities within the network. - Args: + Arguments: hotkey_ss58: The SS58 address of the neuron's hotkey. netuid: The unique identifier of the subnet to check the registration. If `None`, the registration is checked across all subnets. @@ -3332,7 +3331,7 @@ async def is_subnet_active( ) -> bool: """Verify if subnet with provided netuid is active. - Args: + Arguments: netuid (int): The unique identifier of the subnet. block (Optional[int]): The blockchain block number for the query. block_hash (Optional[str]): The blockchain block_hash representation of block id. @@ -3374,7 +3373,7 @@ async def max_weight_limit( """ Returns network MaxWeightsLimit hyperparameter. - Args: + Arguments: netuid (int): The unique identifier of the subnetwork. block (Optional[int]): The blockchain block number for the query. block_hash (Optional[str]): The blockchain block_hash representation of block id. @@ -3434,7 +3433,7 @@ async def min_allowed_weights( """ Returns network MinAllowedWeights hyperparameter. - Args: + Arguments: netuid (int): The unique identifier of the subnetwork. block (Optional[int]): The blockchain block number for the query. block_hash (Optional[str]): The blockchain block_hash representation of block id. @@ -3631,7 +3630,7 @@ async def recycle( Retrieves the 'Burn' hyperparameter for a specified subnet. The 'Burn' parameter represents the amount of Tao that is effectively recycled within the Bittensor network. - Args: + Arguments: netuid (int): The unique identifier of the subnet. block (Optional[int]): The blockchain block number for the query. block_hash (str): The hash of the blockchain block number for the query. @@ -3707,7 +3706,7 @@ async def subnet( """ Retrieves the subnet information for a single subnet in the Bittensor network. - Args: + Arguments: netuid (int): The unique identifier of the subnet. block (Optional[int]): The block number to get the subnets at. block_hash (Optional[str]): The hash of the blockchain block number for the query. @@ -3774,7 +3773,7 @@ async def subnetwork_n( """ Returns network SubnetworkN hyperparameter. - Args: + Arguments: netuid (int): The unique identifier of the subnetwork. block (Optional[int]): The blockchain block number for the query. block_hash (Optional[str]): The hash of the blockchain block number at which to check the subnet existence. @@ -3803,7 +3802,7 @@ async def tempo( """ Returns network Tempo hyperparameter. - Args: + Arguments: netuid (int): The unique identifier of the subnetwork. block (Optional[int]): The blockchain block number for the query. block_hash (Optional[str]): The hash of the blockchain block number at which to check the subnet existence. @@ -3832,7 +3831,7 @@ async def tx_rate_limit( Retrieves the transaction rate limit for the Bittensor network as of a specific blockchain block. This rate limit sets the maximum number of transactions that can be processed within a given time frame. - Args: + Arguments: block (Optional[int]): The blockchain block number for the query. block_hash (Optional[str]): The hash of the blockchain block number at which to check the subnet existence. reuse_block (bool): Whether to reuse the last-used block hash. @@ -3855,7 +3854,7 @@ async def wait_for_block(self, block: Optional[int] = None): Waits until a specific block is reached on the chain. If no block is specified, waits for the next block. - Args: + Arguments: block (Optional[int]): The block number to wait for. If None, waits for the next block. Returns: @@ -4130,7 +4129,7 @@ async def add_stake( subnet. Staking is a fundamental process in the Bittensor network that enables neurons to participate actively and earn incentives. - Args: + Arguments: wallet: The wallet to be used for staking. hotkey_ss58: The SS58 address of the hotkey associated with the neuron to which you intend to delegate your stake. If not specified, the wallet's hotkey will be used. Defaults to ``None``. @@ -4234,7 +4233,7 @@ async def add_stake_multiple( Adds stakes to multiple neurons identified by their hotkey SS58 addresses. This bulk operation allows for efficient staking across different neurons from a single wallet. - Args: + Arguments: wallet (bittensor_wallet.Wallet): The wallet used for staking. hotkey_ss58s (list[str]): List of ``SS58`` addresses of hotkeys to stake to. netuids: list of subnet UIDs @@ -4270,7 +4269,7 @@ async def burned_register( Registers a neuron on the Bittensor network by recycling TAO. This method of registration involves recycling TAO tokens, allowing them to be re-mined by performing work on the network. - Args: + Arguments: wallet (bittensor_wallet.Wallet): The wallet associated with the neuron to be registered. netuid (int): The unique identifier of the subnet. wait_for_inclusion (bool, optional): Waits for the transaction to be included in a block. Defaults to @@ -4473,7 +4472,7 @@ async def move_stake( """ Moves stake to a different hotkey and/or subnet. - Args: + Arguments: wallet (bittensor.wallet): The wallet to move stake from. origin_hotkey (str): The SS58 address of the source hotkey. origin_netuid (int): The netuid of the source subnet. @@ -4525,7 +4524,7 @@ async def register( Registration is a critical step for a neuron to become an active participant in the network, enabling it to stake, set weights, and receive incentives. - Args: + Arguments: wallet (bittensor_wallet.Wallet): The wallet associated with the neuron to be registered. netuid (int): The unique identifier of the subnet. wait_for_inclusion (bool): Waits for the transaction to be included in a block. Defaults to `False`. @@ -4577,7 +4576,7 @@ async def register_subnet( """ Registers a new subnetwork on the Bittensor network. - Args: + Arguments: wallet (bittensor_wallet.Wallet): The wallet to be used for subnet registration. 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. Default is `False`. @@ -4661,7 +4660,7 @@ async def reveal_weights( Reveals the weight vector for a specific subnet on the Bittensor blockchain using the provided wallet. This action serves as a revelation of the subnet validator's previously committed weight distribution as part of the commit-reveal mechanism. - Args: + Arguments: wallet (bittensor_wallet.Wallet): The wallet associated with the subnet validator revealing the weights. netuid (int): The unique identifier of the subnet. uids (np.ndarray): NumPy array of subnet miner neuron UIDs for which weights are being revealed. @@ -5140,7 +5139,7 @@ async def serve_axon( Registers an ``Axon`` serving endpoint on the Bittensor network for a specific neuron. This function is used to set up the Axon, a key component of a neuron that handles incoming queries and data processing tasks. - Args: + Arguments: netuid (int): The unique identifier of the subnetwork. axon (bittensor.core.axon.Axon): The Axon instance to be registered for serving. wait_for_inclusion (bool): Waits for the transaction to be included in a block. Default is ``False``. @@ -5180,7 +5179,7 @@ async def start_call( Submits a start_call extrinsic to the blockchain, to trigger the start call process for a subnet (used to start a new subnet's emission mechanism). - Args: + Arguments: wallet (Wallet): The wallet used to sign the extrinsic (must be unlocked). netuid (int): The UID of the target subnet for which the call is being initiated. wait_for_inclusion (bool, optional): Whether to wait for the extrinsic to be included in a block. @@ -5223,7 +5222,7 @@ async def swap_stake( Moves stake between subnets while keeping the same coldkey-hotkey pair ownership. Like subnet hopping - same owner, same hotkey, just changing which subnet the stake is in. - Args: + Arguments: wallet (bittensor.wallet): The wallet to swap stake from. hotkey_ss58 (str): The SS58 address of the hotkey whose stake is being swapped. origin_netuid (int): The netuid from which stake is removed. @@ -5365,7 +5364,7 @@ async def transfer_stake( """ Transfers stake from one subnet to another while changing the coldkey owner. - Args: + Arguments: wallet (bittensor.wallet): The wallet to transfer stake from. destination_coldkey_ss58 (str): The destination coldkey SS58 address. hotkey_ss58 (str): The hotkey SS58 address associated with the stake. @@ -5413,7 +5412,7 @@ async def unstake( Removes a specified amount of stake from a single hotkey account. This function is critical for adjusting individual neuron stakes within the Bittensor network. - Args: + Arguments: wallet (bittensor_wallet.wallet): The wallet associated with the neuron from which the stake is being removed. hotkey_ss58 (Optional[str]): The ``SS58`` address of the hotkey account to unstake from. @@ -5554,7 +5553,7 @@ async def unstake_multiple( Performs batch unstaking from multiple hotkey accounts, allowing a neuron to reduce its staked amounts efficiently. This function is useful for managing the distribution of stakes across multiple neurons. - Args: + Arguments: wallet (bittensor_wallet.Wallet): The wallet linked to the coldkey from which the stakes are being withdrawn. hotkey_ss58s (List[str]): A list of hotkey ``SS58`` addresses to unstake from. From f1fc036e1ee3e991cf24aa7e3cfa30a2f3f7d140 Mon Sep 17 00:00:00 2001 From: michael trestman Date: Tue, 8 Jul 2025 12:58:04 -0700 Subject: [PATCH 09/21] edit docstrings --- bittensor/core/async_subtensor.py | 64 ++++++++++--------------------- 1 file changed, 20 insertions(+), 44 deletions(-) diff --git a/bittensor/core/async_subtensor.py b/bittensor/core/async_subtensor.py index d0c53ffc74..d49be863bf 100644 --- a/bittensor/core/async_subtensor.py +++ b/bittensor/core/async_subtensor.py @@ -148,21 +148,15 @@ def __init__( ): """Initializes an AsyncSubtensor instance for blockchain interaction. - Arguments: - network: The network name or type to connect to (e.g., "finney", "test"). If None, uses the default network - from config. - config: Configuration object for the AsyncSubtensor instance. If None, uses the default configuration. + network: The network name or type to connect to (e.g., "finney", "test"). If `None`, uses the default network from config. + config: Configuration object for the AsyncSubtensor instance. If `None`, uses the default configuration. log_verbose: Enables or disables verbose logging. Defaults to `False`. - fallback_endpoints: List of fallback endpoints to use if default or provided network is not available. - Defaults to `None`. + fallback_endpoints: List of fallback endpoints to use if default or provided network is not available. Defaults to `None`. retry_forever: Whether to retry forever on connection errors. Defaults to `False`. _mock: Whether this is a mock instance. Mainly for testing purposes. Defaults to `False`. - archive_endpoints: Similar to fallback_endpoints, but specifically only archive nodes. Will be used in cases - where you are requesting a block that is too old for your current (presumably lite) node. Defaults to - `None`. - websocket_shutdown_timer: Amount of time, in seconds, to wait after the last response from the chain to close - the connection. Defaults to `5.0`. + archive_endpoints: Similar to fallback_endpoints, but specifically only archive nodes. Will be used in cases where you are requesting a block that is too old for your current (presumably lite) node. Defaults to `None`. + websocket_shutdown_timer: Amount of time, in seconds, to wait after the last response from the chain to close the connection. Defaults to `5.0`. Returns: None @@ -177,7 +171,7 @@ def __init__( import asyncio async def main(): - async with bt.AsyncSubtensor("finney") as subtensor: + async with bt.AsyncSubtensor(network="finney") as subtensor: block_hash = await subtensor.get_block_hash() asyncio.run(main()) @@ -211,8 +205,7 @@ async def main(): async def close(self): """Closes the connection to the blockchain. - Use this to explicitly clean up resources and close the network connection instead of waiting for garbage - collection. + Use this to explicitly clean up resources and close the network connection instead of waiting for garbage collection. Returns: None @@ -222,7 +215,7 @@ async def close(self): await subtensor.initialize() # Use the subtensor... - balance = await subtensor.get_balance("5F...") + balance = await subtensor.get_balance(address="5F...") # Close when done await subtensor.close() @@ -233,8 +226,7 @@ async def close(self): async def initialize(self): """Initializes the connection to the blockchain. - This method establishes the connection to the Bittensor blockchain and should be called after creating an - AsyncSubtensor instance before making any queries. + This method establishes the connection to the Bittensor blockchain and should be called after creating an AsyncSubtensor instance before making any queries. Returns: AsyncSubtensor: The initialized instance (self) for method chaining. @@ -249,7 +241,7 @@ async def initialize(self): await subtensor.initialize() # Now you can make queries - balance = await subtensor.get_balance("5F...") + balance = await subtensor.get_balance(address="5F...") # Or chain the initialization subtensor = await AsyncSubtensor(network="finney").initialize() @@ -304,8 +296,7 @@ async def determine_block_hash( ) -> Optional[str]: """Determine the appropriate block hash based on the provided parameters. - Ensures that only one of the block specification parameters is used and returns the appropriate block hash for - blockchain queries. + Ensures that only one of the block specification parameters is used and returns the appropriate block hash for blockchain queries. Arguments: block: The block number to get the hash for. Do not specify if using block_hash or reuse_block. @@ -348,14 +339,11 @@ async def encode_params( ) -> str: """Encodes parameters into a hex string using their type definitions. - This method takes a call definition (which specifies parameter types) and actual parameter values, then encodes - them into a hex string that can be used for blockchain transactions. + This method takes a call definition (which specifies parameter types) and actual parameter values, then encodes them into a hex string that can be used for blockchain transactions. Arguments: - call_definition: A dictionary containing parameter type definitions. Should have a "params" key with a list of - parameter definitions. - params: The actual parameter values to encode. Can be either a list (for positional parameters) or a - dictionary (for named parameters). + call_definition: A dictionary containing parameter type definitions. Should have a "params" key with a list of parameter definitions. + params: The actual parameter values to encode. Can be either a list (for positional parameters) or a dictionary (for named parameters). Returns: str: A hex-encoded string representation of the parameters. @@ -407,17 +395,13 @@ async def get_hyperparameter( ) -> Optional[Any]: """Retrieves a specified hyperparameter for a specific subnet. - This method queries the blockchain for subnet-specific hyperparameters such as difficulty, tempo, immunity - period, and other network configuration values. + This method queries the blockchain for subnet-specific hyperparameters such as difficulty, tempo, immunity period, and other network configuration values. Arguments: - param_name: The name of the hyperparameter to retrieve (e.g., "Difficulty", "Tempo", - "ImmunityPeriod"). + param_name: The name of the hyperparameter to retrieve (e.g., "Difficulty", "Tempo", "ImmunityPeriod"). netuid: The unique identifier of the subnet. - block: The block number at which to retrieve the hyperparameter. Do not specify if using - block_hash or reuse_block. - block_hash: The hash of the blockchain block for the query. Do not specify if using block or - reuse_block. + block: The block number at which to retrieve the hyperparameter. Do not specify if using block_hash or reuse_block. + block_hash: The hash of the blockchain block for the query. Do not specify if using block or reuse_block. reuse_block: Whether to reuse the last-used block hash. Do not set if using block_hash or block. Returns: @@ -428,18 +412,10 @@ async def get_hyperparameter( difficulty = await subtensor.get_hyperparameter(param_name="Difficulty", netuid=1) # Get tempo at a specific block - tempo = await subtensor.get_hyperparameter( - param_name="Tempo", - netuid=1, - block=1000000 - ) + tempo = await subtensor.get_hyperparameter(param_name="Tempo", netuid=1, block=1000000) # Get immunity period using block hash - immunity = await subtensor.get_hyperparameter( - param_name="ImmunityPeriod", - netuid=1, - block_hash="0x1234..." - ) + immunity = await subtensor.get_hyperparameter(param_name="ImmunityPeriod", netuid=1, block_hash="0x1234...") """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) if not await self.subnet_exists( From 7374e2b654f3e5cc328354b39c380b02084ab2bd Mon Sep 17 00:00:00 2001 From: michael trestman Date: Tue, 8 Jul 2025 15:03:46 -0700 Subject: [PATCH 10/21] edit docstrings --- bittensor/core/async_subtensor.py | 401 +++++++++++++----------------- 1 file changed, 175 insertions(+), 226 deletions(-) diff --git a/bittensor/core/async_subtensor.py b/bittensor/core/async_subtensor.py index d49be863bf..a0dda4f988 100644 --- a/bittensor/core/async_subtensor.py +++ b/bittensor/core/async_subtensor.py @@ -149,14 +149,19 @@ def __init__( """Initializes an AsyncSubtensor instance for blockchain interaction. Arguments: - network: The network name or type to connect to (e.g., "finney", "test"). If `None`, uses the default network from config. + network: The network name or type to connect to (e.g., "finney", "test"). If `None`, uses the default + network from config. config: Configuration object for the AsyncSubtensor instance. If `None`, uses the default configuration. log_verbose: Enables or disables verbose logging. Defaults to `False`. - fallback_endpoints: List of fallback endpoints to use if default or provided network is not available. Defaults to `None`. + fallback_endpoints: List of fallback endpoints to use if default or provided network is not available. + Defaults to `None`. retry_forever: Whether to retry forever on connection errors. Defaults to `False`. _mock: Whether this is a mock instance. Mainly for testing purposes. Defaults to `False`. - archive_endpoints: Similar to fallback_endpoints, but specifically only archive nodes. Will be used in cases where you are requesting a block that is too old for your current (presumably lite) node. Defaults to `None`. - websocket_shutdown_timer: Amount of time, in seconds, to wait after the last response from the chain to close the connection. Defaults to `5.0`. + archive_endpoints: Similar to fallback_endpoints, but specifically only archive nodes. Will be used in + cases where you are requesting a block that is too old for your current (presumably lite) node. + Defaults to `None`. + websocket_shutdown_timer: Amount of time, in seconds, to wait after the last response from the chain to + close the connection. Defaults to `5.0`. Returns: None @@ -205,7 +210,8 @@ async def main(): async def close(self): """Closes the connection to the blockchain. - Use this to explicitly clean up resources and close the network connection instead of waiting for garbage collection. + Use this to explicitly clean up resources and close the network connection instead of waiting for garbage + collection. Returns: None @@ -226,7 +232,8 @@ async def close(self): async def initialize(self): """Initializes the connection to the blockchain. - This method establishes the connection to the Bittensor blockchain and should be called after creating an AsyncSubtensor instance before making any queries. + This method establishes the connection to the Bittensor blockchain and should be called after creating an + AsyncSubtensor instance before making any queries. Returns: AsyncSubtensor: The initialized instance (self) for method chaining. @@ -296,12 +303,13 @@ async def determine_block_hash( ) -> Optional[str]: """Determine the appropriate block hash based on the provided parameters. - Ensures that only one of the block specification parameters is used and returns the appropriate block hash for blockchain queries. + Ensures that only one of the block specification parameters is used and returns the appropriate block hash for + blockchain queries. Arguments: block: The block number to get the hash for. Do not specify if using block_hash or reuse_block. block_hash: The hash of the blockchain block. Do not specify if using block or reuse_block. - reuse_block: Whether to reuse the last-used block hash. Do not set if using block or block_hash. + reuse_block: Whether to reuse the last-used block hash. Do not set if using block or reuse_block. Returns: Optional[str]: The block hash if one can be determined, None otherwise. @@ -339,11 +347,14 @@ async def encode_params( ) -> str: """Encodes parameters into a hex string using their type definitions. - This method takes a call definition (which specifies parameter types) and actual parameter values, then encodes them into a hex string that can be used for blockchain transactions. + This method takes a call definition (which specifies parameter types) and actual parameter values, then encodes + them into a hex string that can be used for blockchain transactions. Arguments: - call_definition: A dictionary containing parameter type definitions. Should have a "params" key with a list of parameter definitions. - params: The actual parameter values to encode. Can be either a list (for positional parameters) or a dictionary (for named parameters). + call_definition: A dictionary containing parameter type definitions. Should have a "params" key with a list + of parameter definitions. + params: The actual parameter values to encode. Can be either a list (for positional parameters) or a + dictionary (for named parameters). Returns: str: A hex-encoded string representation of the parameters. @@ -395,12 +406,14 @@ async def get_hyperparameter( ) -> Optional[Any]: """Retrieves a specified hyperparameter for a specific subnet. - This method queries the blockchain for subnet-specific hyperparameters such as difficulty, tempo, immunity period, and other network configuration values. + This method queries the blockchain for subnet-specific hyperparameters such as difficulty, tempo, immunity + period, and other network configuration values. Arguments: param_name: The name of the hyperparameter to retrieve (e.g., "Difficulty", "Tempo", "ImmunityPeriod"). netuid: The unique identifier of the subnet. - block: The block number at which to retrieve the hyperparameter. Do not specify if using block_hash or reuse_block. + block: The block number at which to retrieve the hyperparameter. Do not specify if using block_hash or + reuse_block. block_hash: The hash of the blockchain block for the query. Do not specify if using block or reuse_block. reuse_block: Whether to reuse the last-used block hash. Do not set if using block_hash or block. @@ -444,19 +457,19 @@ def _get_substrate( ) -> Union[AsyncSubstrateInterface, RetryAsyncSubstrate]: """Creates the Substrate instance based on provided arguments. - This internal method creates either a standard AsyncSubstrateInterface or a - RetryAsyncSubstrate depending on the configuration parameters. + This internal method creates either a standard AsyncSubstrateInterface or a RetryAsyncSubstrate depending on + the configuration parameters. Arguments: - fallback_endpoints: List of fallback endpoints to use if default or provided network is not available. - Defaults to `None`. + fallback_endpoints: List of fallback endpoints to use if default or provided network is not available. + Defaults to `None`. retry_forever: Whether to retry forever on connection errors. Defaults to `False`. _mock: Whether this is a mock instance. Mainly for testing purposes. Defaults to `False`. - archive_endpoints: Similar to fallback_endpoints, but specifically only archive nodes. Will be used in cases - where you are requesting a block that is too old for your current (presumably lite) node. Defaults to - `None`. - ws_shutdown_timer: Amount of time, in seconds, to wait after the last response from the chain to close the - connection. + archive_endpoints: Similar to fallback_endpoints, but specifically only archive nodes. Will be used in + cases where you are requesting a block that is too old for your current (presumably lite) node. Defaults + to `None`. + ws_shutdown_timer: Amount of time, in seconds, to wait after the last response from the chain to close + the connection. Returns: Either AsyncSubstrateInterface or RetryAsyncSubstrate. @@ -496,22 +509,19 @@ async def query_constant( ) -> Optional["ScaleObj"]: """Retrieves a constant from the specified module on the Bittensor blockchain. - This function is used to access fixed values defined within the - blockchain's modules, which are essential for understanding the network's - configuration and rules. These include include critical network parameters such as inflation rates, - consensus rules, or validation thresholds, providing a deeper understanding of the Bittensor network's - operational parameters. + This function is used to access fixed values defined within the blockchain's modules, which are essential for + understanding the network's configuration and rules. These include include critical network parameters such as + inflation rates, consensus rules, or validation thresholds, providing a deeper understanding of the Bittensor + network's operational parameters. Arguments: - module_name: The name of the module containing the constant (e.g., "Balances", - "SubtensorModule"). + module_name: The name of the module containing the constant (e.g., "Balances", "SubtensorModule"). constant_name: The name of the constant to retrieve (e.g., "ExistentialDeposit"). - block: The blockchain block number at which to query the constant. Do not - specify if using block_hash or reuse_block. - block_hash: The hash of the blockchain block at which to query the constant. - Do not specify if using block or reuse_block. - reuse_block: Whether to reuse the blockchain block at which to query the - constant. Defaults to `False`. + block: The blockchain block number at which to query the constant. Do not specify if using block_hash or + reuse_block. + block_hash: The hash of the blockchain block at which to query the constant. Do not specify if using + block or reuse_block. + reuse_block: Whether to reuse the blockchain block at which to query the constant. Defaults to `False`. Returns: Optional[async_substrate_interface.types.ScaleObj]: The value of the constant if found, `None` otherwise. @@ -519,8 +529,8 @@ async def query_constant( Example: # Get existential deposit constant existential_deposit = await subtensor.query_constant( - "Balances", - "ExistentialDeposit" + module_name="Balances", + constant_name="ExistentialDeposit" ) # Get constant at specific block @@ -549,43 +559,28 @@ async def query_map( ) -> "AsyncQueryMapResult": """Queries map storage from any module on the Bittensor blockchain. - This function retrieves data structures that represent key-value mappings, - essential for accessing complex and structured data within the blockchain - modules. + This function retrieves data structures that represent key-value mappings, essential for accessing complex and + structured data within the blockchain modules. Arguments: - module: The name of the module from which to query the map storage - (e.g., "SubtensorModule", "System"). - name: The specific storage function within the module to query - (e.g., "Bonds", "Weights"). - block: The blockchain block number at which to perform the query. - Defaults to `None` (latest block). - block_hash: The hash of the block to retrieve the parameter from. Do not - specify if using block or reuse_block. - reuse_block: Whether to use the last-used block. Do not set if using - block_hash or block. Defaults to `False`. + module: The name of the module from which to query the map storage (e.g., "SubtensorModule", "System"). + name: The specific storage function within the module to query (e.g., "Bonds", "Weights"). + block: The blockchain block number at which to perform the query. Defaults to `None` (latest block). + block_hash: The hash of the block to retrieve the parameter from. Do not specify if using block or + reuse_block. + reuse_block: Whether to use the last-used block. Do not set if using block_hash or block. Defaults to + `False`. params: Parameters to be passed to the query. Defaults to `None`. Returns: - AsyncQueryMapResult: A data structure representing the map storage if found, - None otherwise. + AsyncQueryMapResult: A data structure representing the map storage if found, None otherwise. Example: # Query bonds for subnet 1 - bonds = await subtensor.query_map( - module="SubtensorModule", - name="Bonds", - params=[1] - ) + bonds = await subtensor.query_map(module="SubtensorModule", name="Bonds", params=[1]) # Query weights at specific block - weights = await subtensor.query_map( - module="SubtensorModule", - name="Weights", - params=[1], - block=1000000 - ) - + weights = await subtensor.query_map(module="SubtensorModule", name="Weights", params=[1], block=1000000) """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) result = await self.substrate.query_map( @@ -605,23 +600,23 @@ async def query_map_subtensor( reuse_block: bool = False, params: Optional[list] = None, ) -> "AsyncQueryMapResult": - """ - Queries map storage from the Subtensor module on the Bittensor blockchain. This function is designed to retrieve - a map-like data structure, which can include various neuron-specific details or network-wide attributes. + """Queries map storage from the Subtensor module on the Bittensor blockchain. This function is designed to + retrieve a map-like data structure, which can include various neuron-specific details or network-wide + attributes. Arguments: name: The name of the map storage function to query. block: The blockchain block number at which to perform the query. - block_hash: The hash of the block to retrieve the parameter from. Do not specify if using block or - reuse_block. + block_hash: The hash of the block to retrieve the parameter from. Do not specify if using block or + reuse_block. reuse_block: Whether to use the last-used block. Do not set if using block_hash or block. params: A list of parameters to pass to the query function. Returns: An object containing the map-like data structure, or `None` if not found. - This function is particularly useful for analyzing and understanding complex network structures and - relationships within the Bittensor ecosystem, such as interneuronal connections and stake distributions. + This function is particularly useful for analyzing and understanding complex network structures and + relationships within the Bittensor ecosystem, such as interneuronal connections and stake distributions. """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) return await self.substrate.query_map( @@ -641,10 +636,9 @@ async def query_module( reuse_block: bool = False, params: Optional[list] = None, ) -> Optional[Union["ScaleObj", Any]]: - """ - Queries any module storage on the Bittensor blockchain with the specified parameters and block number. This - function is a generic query interface that allows for flexible and diverse data retrieval from various - blockchain modules. + """Queries any module storage on the Bittensor blockchain with the specified parameters and block number. + This function is a generic query interface that allows for flexible and diverse data retrieval from various + blockchain modules. Arguments: module: The name of the module from which to query data. @@ -659,7 +653,7 @@ async def query_module( An object containing the requested data if found, `None` otherwise. This versatile query function is key to accessing a wide range of data and insights from different parts of the - Bittensor blockchain, enhancing the understanding and analysis of the network's state and dynamics. + Bittensor blockchain, enhancing the understanding and analysis of the network's state and dynamics. """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) return await self.substrate.query( @@ -679,25 +673,24 @@ async def query_runtime_api( block_hash: Optional[str] = None, reuse_block: bool = False, ) -> Optional[Any]: - """ - Queries the runtime API of the Bittensor blockchain, providing a way to interact with the underlying runtime and - retrieve data encoded in Scale Bytes format. This function is essential for advanced users who need to - interact with specific runtime methods and decode complex data types. + """Queries the runtime API of the Bittensor blockchain, providing a way to interact with the underlying runtime + and retrieve data encoded in Scale Bytes format. This function is essential for advanced users who need to + interact with specific runtime methods and decode complex data types. Arguments: runtime_api: The name of the runtime API to query. method: The specific method within the runtime API to call. params: The parameters to pass to the method call. block: the block number for this query. Do not specify if using block_hash or reuse_block. - block_hash: The hash of the blockchain block number at which to perform the query. Do not specify if - using block or reuse_block. + block_hash: The hash of the blockchain block number at which to perform the query. Do not specify if using + block or reuse_block. reuse_block: Whether to reuse the last-used block hash. Do not set if using block_hash or block. Returns: The decoded result from the runtime API call, or `None` if the call fails. This function enables access to the deeper layers of the Bittensor blockchain, allowing for detailed and - specific interactions with the network's runtime environment. + specific interactions with the network's runtime environment. """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) if not block_hash and reuse_block: @@ -715,9 +708,9 @@ async def query_subtensor( reuse_block: bool = False, params: Optional[list] = None, ) -> Optional[Union["ScaleObj", Any]]: - """ - Queries named storage from the Subtensor module on the Bittensor blockchain. This function is used to retrieve - specific data or parameters from the blockchain, such as stake, rank, or other neuron-specific attributes. + """Queries named storage from the Subtensor module on the Bittensor blockchain. This function is used to + retrieve specific data or parameters from the blockchain, such as stake, rank, or other neuron-specific + attributes. Arguments: name: The name of the storage function to query. @@ -730,8 +723,8 @@ async def query_subtensor( Returns: query_response: An object containing the requested data. - This query function is essential for accessing detailed information about the network and its neurons, providing - valuable insights into the state and dynamics of the Bittensor ecosystem. + This query function is essential for accessing detailed information about the network and its neurons, + providing valuable insights into the state and dynamics of the Bittensor ecosystem. """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) return await self.substrate.query( @@ -750,9 +743,8 @@ async def state_call( block_hash: Optional[str] = None, reuse_block: bool = False, ) -> dict[Any, Any]: - """ - Makes a state call to the Bittensor blockchain, allowing for direct queries of the blockchain's state. This - function is typically used for advanced queries that require specific method calls and data inputs. + """Makes a state call to the Bittensor blockchain, allowing for direct queries of the blockchain's state. + This function is typically used for advanced queries that require specific method calls and data inputs. Arguments: method: The method name for the state call. @@ -765,8 +757,8 @@ async def state_call( Returns: result (dict[Any, Any]): The result of the rpc call. - The state call function provides a more direct and flexible way of querying blockchain data, useful for specific - use cases where standard queries are insufficient. + The state call function provides a more direct and flexible way of querying blockchain data, useful for + specific use cases where standard queries are insufficient. """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) return await self.substrate.rpc_request( @@ -788,25 +780,23 @@ async def all_subnets( block_hash: Optional[str] = None, reuse_block: bool = False, ) -> Optional[list[DynamicInfo]]: - """Queries the blockchain for comprehensive information about all - subnets, including their dynamic parameters and operational status. + """Queries the blockchain for comprehensive information about all subnets, including their dynamic parameters + and operational status. Arguments: - block_number: The block number to query the subnet information from. Do not - specify if using block_hash or reuse_block. - block_hash: The hash of the blockchain block number for the query. Do not - specify if using reuse_block or block. - reuse_block: Whether to reuse the last-used blockchain block hash. Do not - set if using block_hash or block. + block_number: The block number to query the subnet information from. Do not specify if using block_hash or + reuse_block. + block_hash: The hash of the blockchain block number for the query. Do not specify if using reuse_block or + block. + reuse_block: Whether to reuse the last-used blockchain block hash. Do not set if using block_hash or block. Returns: - Optional[list[DynamicInfo]]: A list of DynamicInfo objects, each containing - detailed information about a subnet, or None if the query fails. + Optional[list[DynamicInfo]]: A list of DynamicInfo objects, each containing detailed information about a + subnet, or None if the query fails. Example: # Get all subnets at current block subnets = await subtensor.all_subnets() - """ block_hash = await self.determine_block_hash( block_number, block_hash, reuse_block @@ -828,31 +818,25 @@ async def blocks_since_last_step( block_hash: Optional[str] = None, reuse_block: bool = False, ) -> Optional[int]: - """Queries the blockchain to determine how many blocks have passed - since the last epoch step for a specific subnet. + """Queries the blockchain to determine how many blocks have passed since the last epoch step for a specific + subnet. Arguments: netuid: The unique identifier of the subnetwork. - block: The block number for this query. Do not specify if using - block_hash or reuse_block. - block_hash: The hash of the blockchain block number for the query. Do not - specify if using reuse_block or block. - reuse_block: Whether to reuse the last-used blockchain block hash. Do not - set if using block_hash or block. + block: The block number for this query. Do not specify if using block_hash or reuse_block. + block_hash: The hash of the blockchain block number for the query. Do not specify if using reuse_block or + block. + reuse_block: Whether to reuse the last-used blockchain block hash. Do not set if using block_hash or block. Returns: - The number of blocks since the last step in the subnet, - or None if the query fails. + The number of blocks since the last step in the subnet, or None if the query fails. Example: # Get blocks since last step for subnet 1 blocks = await subtensor.blocks_since_last_step(netuid=1) # Get blocks since last step at specific block - blocks = await subtensor.blocks_since_last_step( - netuid=1, - block=1000000 - ) + blocks = await subtensor.blocks_since_last_step(netuid=1, block=1000000) """ query = await self.query_subtensor( name="BlocksSinceLastStep", @@ -864,16 +848,14 @@ async def blocks_since_last_step( return query.value if query is not None and hasattr(query, "value") else query async def blocks_since_last_update(self, netuid: int, uid: int) -> Optional[int]: - """Returns the number of blocks since the last update, or ``None`` if the subnetwork or UID does not - exist. + """Returns the number of blocks since the last update, or ``None`` if the subnetwork or UID does not exist. Arguments: netuid: The unique identifier of the subnetwork. uid: The unique identifier of the neuron. Returns: - Optional[int]: The number of blocks since the last update, or None if the - subnetwork or UID does not exist. + Optional[int]: The number of blocks since the last update, or None if the subnetwork or UID does not exist. Example: # Get blocks since last update for UID 5 in subnet 1 @@ -881,7 +863,6 @@ async def blocks_since_last_update(self, netuid: int, uid: int) -> Optional[int] # Check if neuron needs updating blocks_since_update = await subtensor.blocks_since_last_update(netuid=1, uid=10) - """ call = await self.get_hyperparameter(param_name="LastUpdate", netuid=netuid) return None if call is None else await self.get_current_block() - int(call[uid]) @@ -895,19 +876,15 @@ async def bonds( ) -> list[tuple[int, list[tuple[int, int]]]]: """Retrieves the bond distribution set by subnet validators within a specific subnet. - Bonds represent the "investment" a subnet validator has made in evaluating a specific - subnet miner. This bonding mechanism is integral to the Yuma Consensus' design intent - of incentivizing high-quality performance by subnet miners, and honest evaluation by - subnet validators. + Bonds represent the "investment" a subnet validator has made in evaluating a specific subnet miner. This + bonding mechanism is integral to the Yuma Consensus' design intent of incentivizing high-quality performance + by subnet miners, and honest evaluation by subnet validators. Arguments: - netuid (int): The unique identifier of the subnet. - block (Optional[int]): The block number for this query. Do not specify if using - block_hash or reuse_block. - block_hash (Optional[str]): The hash of the block for the query. Do not specify - if using reuse_block or block. - reuse_block: Whether to reuse the last-used block hash. Do not set if using - block_hash or block. + netuid: The unique identifier of the subnet. + block: The block number for this query. Do not specify if using block_hash or reuse_block. + block_hash: The hash of the block for the query. Do not specify if using reuse_block or block. + reuse_block: Whether to reuse the last-used block hash. Do not set if using block_hash or block. Returns: List of tuples mapping each neuron's UID to its bonds with other neurons. @@ -941,34 +918,25 @@ async def commit( """Commits arbitrary data to the Bittensor network by publishing metadata. This method allows neurons to publish arbitrary data to the blockchain, which can be used for various purposes - such as sharing model updates, configuration data, or other network-relevant information. + such as sharing model updates, configuration data, or other network-relevant information. Arguments: wallet: The wallet associated with the neuron committing the data. netuid: The unique identifier of the subnet. data: The data to be committed to the network. - period: The number of blocks during which the transaction will remain valid after it's submitted. - If the transaction is not included in a block within that number of blocks, it will expire and be - rejected. You can think of it as an expiration date for the transaction. + period: The number of blocks during which the transaction will remain valid after it's submitted. If the + transaction is not included in a block within that number of blocks, it will expire and be rejected. You + can think of it as an expiration date for the transaction. Returns: bool: True if the commit was successful, False otherwise. Example: # Commit some data to subnet 1 - success = await subtensor.commit( - wallet=my_wallet, - netuid=1, - data="Hello Bittensor!" - ) + success = await subtensor.commit(wallet=my_wallet, netuid=1, data="Hello Bittensor!") # Commit with custom period - success = await subtensor.commit( - wallet=my_wallet, - netuid=1, - data="Model update v2.0", - period=100 - ) + success = await subtensor.commit(wallet=my_wallet, netuid=1, data="Model update v2.0", period=100) Note: See """ @@ -993,15 +961,14 @@ async def commit_reveal_enabled( """Check if commit-reveal mechanism is enabled for a given subnet at a specific block. The commit reveal feature is designed to solve the weight-copying problem by giving would-be weight-copiers - access only to stale weights. Copying stale weights should result in subnet validators departing from consensus. + access only to stale weights. Copying stale weights should result in subnet validators departing from + consensus. Arguments: netuid: The unique identifier of the subnet for which to check the commit-reveal mechanism. block: The block number to query. Do not specify if using block_hash or reuse_block. - block_hash: The block hash at which to check the parameter. Do not set if using block or - reuse_block. - reuse_block: Whether to reuse the last-used block hash. Do not set if using block_hash or - block. + block_hash: The block hash at which to check the parameter. Do not set if using block or reuse_block. + reuse_block: Whether to reuse the last-used block hash. Do not set if using block_hash or block. Returns: bool: True if commit-reveal mechanism is enabled, False otherwise. @@ -1011,10 +978,7 @@ async def commit_reveal_enabled( enabled = await subtensor.commit_reveal_enabled(netuid=1) # Check at specific block - enabled = await subtensor.commit_reveal_enabled( - netuid=1, - block=1000000 - ) + enabled = await subtensor.commit_reveal_enabled(netuid=1, block=1000000) See also: """ @@ -1036,16 +1000,16 @@ async def difficulty( ) -> Optional[int]: """Retrieves the 'Difficulty' hyperparameter for a specified subnet in the Bittensor network. - This parameter determines the computational challenge required for neurons to participate in - consensus and validation processes. The difficulty directly impacts the network's security and integrity by - setting the computational effort required for validating transactions and participating in the network's - consensus mechanism. + This parameter determines the computational challenge required for neurons to participate in consensus and + validation processes. The difficulty directly impacts the network's security and integrity by setting the + computational effort required for validating transactions and participating in the network's consensus + mechanism. Arguments: netuid: The unique identifier of the subnet. block: The block number for the query. Do not specify if using block_hash or reuse_block. - block_hash: The hash of the block to retrieve the parameter from. Do not specify if using block or - reuse_block. + block_hash: The hash of the block to retrieve the parameter from. Do not specify if using block or + reuse_block. reuse_block: Whether to use the last-used block. Do not set if using block_hash or block. Returns: @@ -1056,10 +1020,7 @@ async def difficulty( difficulty = await subtensor.difficulty(netuid=1) # Get difficulty at specific block - difficulty = await subtensor.difficulty( - netuid=1, - block=1000000 - ) + difficulty = await subtensor.difficulty(netuid=1, block=1000000) See also: """ @@ -1097,13 +1058,10 @@ async def does_hotkey_exist( Example: # Check if hotkey exists - exists = await subtensor.does_hotkey_exist("5F...") + exists = await subtensor.does_hotkey_exist(hotkey_ss58="5F...") # Check at specific block - exists = await subtensor.does_hotkey_exist( - "5F...", - block=1000000 - ) + exists = await subtensor.does_hotkey_exist(hotkey_ss58="5F...", block=1000000) """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) result = await self.substrate.query( @@ -1152,8 +1110,8 @@ async def get_all_subnets_info( print(f"Subnet {subnet.netuid}: {subnet.name}") Note: - Gaining insights into the subnets' details assists in understanding the network's composition, - the roles of different subnets, and their unique features. + Gaining insights into the subnets' details assists in understanding the network's composition, the roles + of different subnets, and their unique features. See also: """ @@ -1179,8 +1137,8 @@ async def get_balance( ) -> Balance: """Retrieves the balance for given coldkey. - This method queries the System module's Account storage to get the current balance of a coldkey address. - The balance represents the amount of TAO tokens held by the specified address. + This method queries the System module's Account storage to get the current balance of a coldkey address. The + balance represents the amount of TAO tokens held by the specified address. Arguments: address: The coldkey address in SS58 format. @@ -1193,15 +1151,11 @@ async def get_balance( Example: # Get balance for an address - balance = await subtensor.get_balance("5F...") + balance = await subtensor.get_balance(address="5F...") print(f"Balance: {balance.tao} TAO") # Get balance at specific block - balance = await subtensor.get_balance( - "5F...", - block=1000000 - ) - + balance = await subtensor.get_balance(address="5F...", block=1000000) """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) balance = await self.substrate.query( @@ -1223,8 +1177,8 @@ async def get_balances( """Retrieves the balance for given coldkey(s). This method efficiently queries multiple coldkey addresses in a single batch operation, returning a - dictionary mapping each address to its corresponding balance. This is more efficient than calling - get_balance multiple times. + dictionary mapping each address to its corresponding balance. This is more efficient than calling get_balance + multiple times. Arguments: *addresses: Variable number of coldkey addresses in SS58 format. @@ -1237,12 +1191,7 @@ async def get_balances( Example: # Get balances for multiple addresses - balances = await subtensor.get_balances( - "5F...", - "5G...", - "5H..." - ) - + balances = await subtensor.get_balances("5F...", "5G...", "5H...") """ if reuse_block: block_hash = self.substrate.last_block_hash @@ -1268,10 +1217,9 @@ async def get_balances( async def get_current_block(self) -> int: """Returns the current block number on the Bittensor blockchain. - This function provides the latest block number, indicating the most recent state of the blockchain. - Knowing the current block number is essential for querying real-time data and performing time-sensitive - operations on the blockchain. It serves as a reference point for network activities and data - synchronization. + This function provides the latest block number, indicating the most recent state of the blockchain. Knowing + the current block number is essential for querying real-time data and performing time-sensitive operations on + the blockchain. It serves as a reference point for network activities and data synchronization. Returns: int: The current chain block number. @@ -1281,7 +1229,6 @@ async def get_current_block(self) -> int: current_block = await subtensor.get_current_block() print(f"Current block: {current_block}") - block = await subtensor.get_current_block() if block > 1000000: print("Network has progressed past block 1M") @@ -1297,20 +1244,20 @@ async def _get_block_hash(self, block_id: int): async def get_block_hash(self, block: Optional[int] = None) -> str: """Retrieves the hash of a specific block on the Bittensor blockchain. - The block hash is a unique identifier representing the cryptographic hash of the block's content, - ensuring its integrity and immutability. It is a fundamental aspect of blockchain technology, - providing a secure reference to each block's data. It is crucial for verifying transactions, - ensuring data consistency, and maintaining the trustworthiness of the blockchain. + The block hash is a unique identifier representing the cryptographic hash of the block's content, ensuring its + integrity and immutability. It is a fundamental aspect of blockchain technology, providing a secure reference + to each block's data. It is crucial for verifying transactions, ensuring data consistency, and maintaining + the trustworthiness of the blockchain. Arguments: - block: The block number for which the hash is to be retrieved. If None, returns the latest block hash. + block: The block number for which the hash is to be retrieved. If `None`, returns the latest block hash. Returns: str: The cryptographic hash of the specified block. Example: # Get hash for specific block - block_hash = await subtensor.get_block_hash(1000000) + block_hash = await subtensor.get_block_hash(block=1000000) print(f"Block 1000000 hash: {block_hash}") # Get latest block hash @@ -1332,9 +1279,8 @@ async def get_parents( block_hash: Optional[str] = None, reuse_block: bool = False, ) -> list[tuple[float, str]]: - """ - This method retrieves the parent of a given hotkey and netuid. It queries the SubtensorModule's ParentKeys - storage function to get the children and formats them before returning as a tuple. + """This method retrieves the parent of a given hotkey and netuid. It queries the SubtensorModule's ParentKeys + storage function to get the children and formats them before returning as a tuple. Arguments: hotkey: The child hotkey SS58. @@ -1376,8 +1322,8 @@ async def get_children( """Retrieves the children of a given hotkey and netuid. This method queries the SubtensorModule's ChildKeys storage function to get the children and formats them - before returning as a tuple. It provides information about the child neurons that a validator has set - for weight distribution. + before returning as a tuple. It provides information about the child neurons that a validator has set for + weight distribution. Arguments: hotkey: The hotkey value. @@ -1387,15 +1333,12 @@ async def get_children( reuse_block: Whether to reuse the last-used block hash. Returns: - tuple[bool, list[tuple[float, str]], str]: A tuple containing a boolean indicating success or failure, - a list of formatted children with their proportions, and an error message (if applicable). + tuple[bool, list[tuple[float, str]], str]: A tuple containing a boolean indicating success or failure, a + list of formatted children with their proportions, and an error message (if applicable). Example: # Get children for a hotkey in subnet 1 - success, children, error = await subtensor.get_children( - hotkey="5F...", - netuid=1 - ) + success, children, error = await subtensor.get_children(hotkey="5F...", netuid=1) if success: for proportion, child_hotkey in children: @@ -1436,9 +1379,8 @@ async def get_children_pending( ]: """Retrieves the pending children of a given hotkey and netuid. - This method queries the SubtensorModule's PendingChildKeys storage function to get children that are - pending approval or in a cooldown period. These are children that have been proposed but not yet - finalized. + This method queries the SubtensorModule's PendingChildKeys storage function to get children that are pending + approval or in a cooldown period. These are children that have been proposed but not yet finalized. Arguments: hotkey: The hotkey value. @@ -1486,8 +1428,8 @@ async def get_commitment( ) -> str: """Retrieves the on-chain commitment for a specific neuron in the Bittensor network. - This method retrieves the commitment data that a neuron has published to the blockchain. Commitments - are used in the commit-reveal mechanism for secure weight setting and other network operations. + This method retrieves the commitment data that a neuron has published to the blockchain. Commitments are used + in the commit-reveal mechanism for secure weight setting and other network operations. Arguments: netuid (int): The unique identifier of the subnetwork. @@ -2024,7 +1966,8 @@ async def get_metagraph_info( Arguments: netuid: The unique identifier of the subnet to query. - field_indices: An optional list of SelectiveMetagraphIndex or int values specifying which fields to retrieve. + field_indices: An optional list of SelectiveMetagraphIndex or int values specifying which fields to + retrieve. If not provided, all available fields will be returned. block: the block number at which to retrieve the hyperparameter. Do not specify if using block_hash or reuse_block @@ -4316,8 +4259,8 @@ async def commit_weights( `True` if the weight commitment is successful, False otherwise. `msg` is a string value describing the success or potential error. - This function allows subnet validators to create a tamper-proof record of their weight vector at a specific point - in time, creating a foundation of transparency and accountability for the Bittensor network. + This function allows subnet validators to create a tamper-proof record of their weight vector at a specific + point in time, creating a foundation of transparency and accountability for the Bittensor network. See also: , @@ -4634,7 +4577,8 @@ async def reveal_weights( ) -> tuple[bool, str]: """ Reveals the weight vector for a specific subnet on the Bittensor blockchain using the provided wallet. - This action serves as a revelation of the subnet validator's previously committed weight distribution as part of the commit-reveal mechanism. + This action serves as a revelation of the subnet validator's previously committed weight distribution as part + of the commit-reveal mechanism. Arguments: wallet (bittensor_wallet.Wallet): The wallet associated with the subnet validator revealing the weights. @@ -4996,14 +4940,18 @@ async def set_weights( period: Optional[int] = 8, ): """ - Sets the weight vector for a neuron acting as a validator, specifying the weights assigned to subnet miners based on their performance evaluation. + Sets the weight vector for a neuron acting as a validator, specifying the weights assigned to subnet miners + based on their performance evaluation. - This method allows subnet validators to submit their weight vectors, which rank the value of each subnet miner's work. These weight vectors are used by the Yuma Consensus algorithm to compute emissions for both validators and miners. + This method allows subnet validators to submit their weight vectors, which rank the value of each subnet + miner's work. These weight vectors are used by the Yuma Consensus algorithm to compute emissions for both + validators and miners. Arguments: wallet (bittensor_wallet.Wallet): The wallet associated with the subnet validator setting the weights. netuid (int): The unique identifier of the subnet. - uids (Union[NDArray[np.int64], torch.LongTensor, list]): The list of subnet miner neuron UIDs that the weights are being + uids (Union[NDArray[np.int64], torch.LongTensor, list]): The list of subnet miner neuron UIDs that the + weights are being set for. weights (Union[NDArray[np.float32], torch.FloatTensor, list]): The corresponding weights to be set for each UID, representing the validator's evaluation of each miner's performance. @@ -5022,7 +4970,8 @@ async def set_weights( tuple[bool, str]: ``True`` if the setting of weights is successful, False otherwise. And `msg`, a string value describing the success or potential error. - This function is crucial in the Yuma Consensus mechanism, where each validator's weight vector contributes to the overall weight matrix used to calculate emissions and maintain network consensus. + This function is crucial in the Yuma Consensus mechanism, where each validator's weight vector contributes + to the overall weight matrix used to calculate emissions and maintain network consensus. See """ From a47c24d23166d5bfaf2218c29d3fe2dcd563ea5c Mon Sep 17 00:00:00 2001 From: michael trestman Date: Tue, 8 Jul 2025 15:06:37 -0700 Subject: [PATCH 11/21] edit docstrings --- bittensor/core/async_subtensor.py | 38 +++++++++++++++---------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/bittensor/core/async_subtensor.py b/bittensor/core/async_subtensor.py index a0dda4f988..6486b080e4 100644 --- a/bittensor/core/async_subtensor.py +++ b/bittensor/core/async_subtensor.py @@ -461,14 +461,14 @@ def _get_substrate( the configuration parameters. Arguments: - fallback_endpoints: List of fallback endpoints to use if default or provided network is not available. + fallback_endpoints: List of fallback endpoints to use if default or provided network is not available. Defaults to `None`. retry_forever: Whether to retry forever on connection errors. Defaults to `False`. _mock: Whether this is a mock instance. Mainly for testing purposes. Defaults to `False`. - archive_endpoints: Similar to fallback_endpoints, but specifically only archive nodes. Will be used in - cases where you are requesting a block that is too old for your current (presumably lite) node. Defaults + archive_endpoints: Similar to fallback_endpoints, but specifically only archive nodes. Will be used in + cases where you are requesting a block that is too old for your current (presumably lite) node. Defaults to `None`. - ws_shutdown_timer: Amount of time, in seconds, to wait after the last response from the chain to close + ws_shutdown_timer: Amount of time, in seconds, to wait after the last response from the chain to close the connection. Returns: @@ -509,7 +509,7 @@ async def query_constant( ) -> Optional["ScaleObj"]: """Retrieves a constant from the specified module on the Bittensor blockchain. - This function is used to access fixed values defined within the blockchain's modules, which are essential for + This function is used to access fixed values defined within the blockchain's modules, which are essential for understanding the network's configuration and rules. These include include critical network parameters such as inflation rates, consensus rules, or validation thresholds, providing a deeper understanding of the Bittensor network's operational parameters. @@ -517,9 +517,9 @@ async def query_constant( Arguments: module_name: The name of the module containing the constant (e.g., "Balances", "SubtensorModule"). constant_name: The name of the constant to retrieve (e.g., "ExistentialDeposit"). - block: The blockchain block number at which to query the constant. Do not specify if using block_hash or + block: The blockchain block number at which to query the constant. Do not specify if using block_hash or reuse_block. - block_hash: The hash of the blockchain block at which to query the constant. Do not specify if using + block_hash: The hash of the blockchain block at which to query the constant. Do not specify if using block or reuse_block. reuse_block: Whether to reuse the blockchain block at which to query the constant. Defaults to `False`. @@ -566,9 +566,9 @@ async def query_map( module: The name of the module from which to query the map storage (e.g., "SubtensorModule", "System"). name: The specific storage function within the module to query (e.g., "Bonds", "Weights"). block: The blockchain block number at which to perform the query. Defaults to `None` (latest block). - block_hash: The hash of the block to retrieve the parameter from. Do not specify if using block or + block_hash: The hash of the block to retrieve the parameter from. Do not specify if using block or reuse_block. - reuse_block: Whether to use the last-used block. Do not set if using block_hash or block. Defaults to + reuse_block: Whether to use the last-used block. Do not set if using block_hash or block. Defaults to `False`. params: Parameters to be passed to the query. Defaults to `None`. @@ -600,14 +600,14 @@ async def query_map_subtensor( reuse_block: bool = False, params: Optional[list] = None, ) -> "AsyncQueryMapResult": - """Queries map storage from the Subtensor module on the Bittensor blockchain. This function is designed to + """Queries map storage from the Subtensor module on the Bittensor blockchain. This function is designed to retrieve a map-like data structure, which can include various neuron-specific details or network-wide attributes. Arguments: name: The name of the map storage function to query. block: The blockchain block number at which to perform the query. - block_hash: The hash of the block to retrieve the parameter from. Do not specify if using block or + block_hash: The hash of the block to retrieve the parameter from. Do not specify if using block or reuse_block. reuse_block: Whether to use the last-used block. Do not set if using block_hash or block. params: A list of parameters to pass to the query function. @@ -615,7 +615,7 @@ async def query_map_subtensor( Returns: An object containing the map-like data structure, or `None` if not found. - This function is particularly useful for analyzing and understanding complex network structures and + This function is particularly useful for analyzing and understanding complex network structures and relationships within the Bittensor ecosystem, such as interneuronal connections and stake distributions. """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) @@ -876,7 +876,7 @@ async def bonds( ) -> list[tuple[int, list[tuple[int, int]]]]: """Retrieves the bond distribution set by subnet validators within a specific subnet. - Bonds represent the "investment" a subnet validator has made in evaluating a specific subnet miner. This + Bonds represent the "investment" a subnet validator has made in evaluating a specific subnet miner. This bonding mechanism is integral to the Yuma Consensus' design intent of incentivizing high-quality performance by subnet miners, and honest evaluation by subnet validators. @@ -924,7 +924,7 @@ async def commit( wallet: The wallet associated with the neuron committing the data. netuid: The unique identifier of the subnet. data: The data to be committed to the network. - period: The number of blocks during which the transaction will remain valid after it's submitted. If the + period: The number of blocks during which the transaction will remain valid after it's submitted. If the transaction is not included in a block within that number of blocks, it will expire and be rejected. You can think of it as an expiration date for the transaction. @@ -961,7 +961,7 @@ async def commit_reveal_enabled( """Check if commit-reveal mechanism is enabled for a given subnet at a specific block. The commit reveal feature is designed to solve the weight-copying problem by giving would-be weight-copiers - access only to stale weights. Copying stale weights should result in subnet validators departing from + access only to stale weights. Copying stale weights should result in subnet validators departing from consensus. Arguments: @@ -1002,13 +1002,13 @@ async def difficulty( This parameter determines the computational challenge required for neurons to participate in consensus and validation processes. The difficulty directly impacts the network's security and integrity by setting the - computational effort required for validating transactions and participating in the network's consensus + computational effort required for validating transactions and participating in the network's consensus mechanism. Arguments: netuid: The unique identifier of the subnet. block: The block number for the query. Do not specify if using block_hash or reuse_block. - block_hash: The hash of the block to retrieve the parameter from. Do not specify if using block or + block_hash: The hash of the block to retrieve the parameter from. Do not specify if using block or reuse_block. reuse_block: Whether to use the last-used block. Do not set if using block_hash or block. @@ -1217,7 +1217,7 @@ async def get_balances( async def get_current_block(self) -> int: """Returns the current block number on the Bittensor blockchain. - This function provides the latest block number, indicating the most recent state of the blockchain. Knowing + This function provides the latest block number, indicating the most recent state of the blockchain. Knowing the current block number is essential for querying real-time data and performing time-sensitive operations on the blockchain. It serves as a reference point for network activities and data synchronization. @@ -4944,7 +4944,7 @@ async def set_weights( based on their performance evaluation. This method allows subnet validators to submit their weight vectors, which rank the value of each subnet - miner's work. These weight vectors are used by the Yuma Consensus algorithm to compute emissions for both + miner's work. These weight vectors are used by the Yuma Consensus algorithm to compute emissions for both validators and miners. Arguments: From e69530a69cd061c21bcf534447d56470f213ed80 Mon Sep 17 00:00:00 2001 From: michael trestman Date: Tue, 8 Jul 2025 15:54:34 -0700 Subject: [PATCH 12/21] edit docstrings --- bittensor/core/async_subtensor.py | 40 ++++++++++++++++++++----------- 1 file changed, 26 insertions(+), 14 deletions(-) diff --git a/bittensor/core/async_subtensor.py b/bittensor/core/async_subtensor.py index 6486b080e4..59d7dba653 100644 --- a/bittensor/core/async_subtensor.py +++ b/bittensor/core/async_subtensor.py @@ -980,7 +980,8 @@ async def commit_reveal_enabled( # Check at specific block enabled = await subtensor.commit_reveal_enabled(netuid=1, block=1000000) - See also: + Notes: + See also: """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) call = await self.get_hyperparameter( @@ -1022,7 +1023,8 @@ async def difficulty( # Get difficulty at specific block difficulty = await subtensor.difficulty(netuid=1, block=1000000) - See also: + Notes: + See also: """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) call = await self.get_hyperparameter( @@ -1113,7 +1115,8 @@ async def get_all_subnets_info( Gaining insights into the subnets' details assists in understanding the network's composition, the roles of different subnets, and their unique features. - See also: + Notes: + See also: """ result = await self.query_runtime_api( runtime_api="SubnetInfoRuntimeApi", @@ -1233,7 +1236,8 @@ async def get_current_block(self) -> int: if block > 1000000: print("Network has progressed past block 1M") - See also: + Notes: + See also: """ return await self.substrate.get_block_number(None) @@ -1264,7 +1268,8 @@ async def get_block_hash(self, block: Optional[int] = None) -> str: latest_hash = await subtensor.get_block_hash() print(f"Latest block hash: {latest_hash}") - See also: + Notes: + See also: """ if block: return await self._get_block_hash(block) @@ -1913,7 +1918,8 @@ async def get_hotkey_owner( Returns: Optional[str]: The SS58 address of the owner if the hotkey exists, or None if it doesn't. - See also: + Notes: + See also: - - - @@ -1987,9 +1993,10 @@ async def get_metagraph_info( field_indices=[SelectiveMetagraphIndex.Name, SelectiveMetagraphIndex.OwnerHotkeys] ) - See also: - - - - + Notes: + See also: + - + - """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) if not block_hash and reuse_block: @@ -2046,7 +2053,8 @@ async def get_all_metagraphs_info( Returns: MetagraphInfo dataclass - See also: See + Notes: + See also: See """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) if not block_hash and reuse_block: @@ -2407,7 +2415,8 @@ async def get_next_epoch_start_block( Returns: int: The block number at which the next epoch will start. - See also: + Notes: + See also: """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) blocks_since_last_step = await self.blocks_since_last_step( @@ -4262,7 +4271,8 @@ async def commit_weights( This function allows subnet validators to create a tamper-proof record of their weight vector at a specific point in time, creating a foundation of transparency and accountability for the Bittensor network. - See also: , + Notes: + See also: , """ retries = 0 @@ -4602,7 +4612,8 @@ async def reveal_weights( This function allows subnet validators to reveal their previously committed weight vector. - See also: , + Notes: + See also: , """ retries = 0 success = False @@ -4973,7 +4984,8 @@ async def set_weights( This function is crucial in the Yuma Consensus mechanism, where each validator's weight vector contributes to the overall weight matrix used to calculate emissions and maintain network consensus. - See + Notes: + See """ async def _blocks_weight_limit() -> bool: From ea4e9562b75c6e0617b7c081a2d1ea8f8abb02e3 Mon Sep 17 00:00:00 2001 From: michael trestman Date: Tue, 8 Jul 2025 15:55:33 -0700 Subject: [PATCH 13/21] edit docstrings --- bittensor/core/async_subtensor.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/bittensor/core/async_subtensor.py b/bittensor/core/async_subtensor.py index 59d7dba653..6b2537afb5 100644 --- a/bittensor/core/async_subtensor.py +++ b/bittensor/core/async_subtensor.py @@ -1920,9 +1920,9 @@ async def get_hotkey_owner( Notes: See also: - - - - - - + - + - + - """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) hk_owner_query = await self.substrate.query( From 3c31fe8674de97e224ce061b800621c42ec529f1 Mon Sep 17 00:00:00 2001 From: michael trestman Date: Tue, 8 Jul 2025 19:00:01 -0700 Subject: [PATCH 14/21] edit docstrings --- bittensor/core/async_subtensor.py | 779 +++++++++++++++--------------- 1 file changed, 378 insertions(+), 401 deletions(-) diff --git a/bittensor/core/async_subtensor.py b/bittensor/core/async_subtensor.py index 8ed725d26d..f7e6c34d95 100644 --- a/bittensor/core/async_subtensor.py +++ b/bittensor/core/async_subtensor.py @@ -232,8 +232,7 @@ async def close(self): async def initialize(self): """Initializes the connection to the blockchain. - This method establishes the connection to the Bittensor blockchain and should be called after creating an - AsyncSubtensor instance before making any queries. + This method establishes the connection to the Bittensor blockchain and should be called after creating an AsyncSubtensor instance before making any queries. Returns: AsyncSubtensor: The initialized instance (self) for method chaining. @@ -303,8 +302,7 @@ async def determine_block_hash( ) -> Optional[str]: """Determine the appropriate block hash based on the provided parameters. - Ensures that only one of the block specification parameters is used and returns the appropriate block hash for - blockchain queries. + Ensures that only one of the block specification parameters is used and returns the appropriate block hash for blockchain queries. Arguments: block: The block number to get the hash for. Do not specify if using block_hash or reuse_block. @@ -347,14 +345,11 @@ async def encode_params( ) -> str: """Encodes parameters into a hex string using their type definitions. - This method takes a call definition (which specifies parameter types) and actual parameter values, then encodes - them into a hex string that can be used for blockchain transactions. + This method takes a call definition (which specifies parameter types) and actual parameter values, then encodes them into a hex string that can be used for blockchain transactions. Arguments: - call_definition: A dictionary containing parameter type definitions. Should have a "params" key with a list - of parameter definitions. - params: The actual parameter values to encode. Can be either a list (for positional parameters) or a - dictionary (for named parameters). + call_definition: A dictionary containing parameter type definitions. Should have a "params" key with a list of parameter definitions. + params: The actual parameter values to encode. Can be either a list (for positional parameters) or a dictionary (for named parameters). Returns: str: A hex-encoded string representation of the parameters. @@ -406,14 +401,13 @@ async def get_hyperparameter( ) -> Optional[Any]: """Retrieves a specified hyperparameter for a specific subnet. - This method queries the blockchain for subnet-specific hyperparameters such as difficulty, tempo, immunity - period, and other network configuration values. + This method queries the blockchain for subnet-specific hyperparameters such as difficulty, tempo, immunity period, and other network configuration values. Arguments: param_name: The name of the hyperparameter to retrieve (e.g., "Difficulty", "Tempo", "ImmunityPeriod"). netuid: The unique identifier of the subnet. block: The block number at which to retrieve the hyperparameter. Do not specify if using block_hash or - reuse_block. + reuse_block. block_hash: The hash of the blockchain block for the query. Do not specify if using block or reuse_block. reuse_block: Whether to reuse the last-used block hash. Do not set if using block_hash or block. @@ -856,7 +850,7 @@ async def blocks_since_last_step( return query.value if query is not None and hasattr(query, "value") else query async def blocks_since_last_update(self, netuid: int, uid: int) -> Optional[int]: - """Returns the number of blocks since the last update, or ``None`` if the subnetwork or UID does not exist. + """Returns the number of blocks since the last update, or `None` if the subnetwork or UID does not exist. Arguments: netuid: The unique identifier of the subnetwork. @@ -1450,12 +1444,12 @@ async def get_commitment( in the commit-reveal mechanism for secure weight setting and other network operations. Arguments: - netuid (int): The unique identifier of the subnetwork. - uid (int): The unique identifier of the neuron. - block (Optional[int]): The block number to retrieve the commitment from. If None, the latest block is used. + netuid: The unique identifier of the subnetwork. + uid: The unique identifier of the neuron. + block: The block number to retrieve the commitment from. If None, the latest block is used. Default is None. - block_hash (Optional[str]): The hash of the block to retrieve the subnet unique identifiers from. - reuse_block (bool): Whether to reuse the last-used block hash. + block_hash: The hash of the block to retrieve the subnet unique identifiers from. + reuse_block: Whether to reuse the last-used block hash. Returns: str: The commitment data as a string. @@ -1496,8 +1490,8 @@ async def get_last_commitment_bonds_reset_block( Retrieves the last block number when the bonds reset were triggered by publish_metadata for a specific neuron. Arguments: - netuid (int): The unique identifier of the subnetwork. - uid (int): The unique identifier of the neuron. + netuid: The unique identifier of the subnetwork. + uid: The unique identifier of the neuron. Returns: Optional[int]: The block number when the bonds were last reset, or None if not found. @@ -1530,11 +1524,11 @@ async def get_all_commitments( analyzing the commit-reveal patterns across an entire subnet. Arguments: - netuid (int): The unique identifier of the subnetwork. - block (Optional[int]): The block number to retrieve the commitment from. If None, the latest block is used. + netuid: The unique identifier of the subnetwork. + block: The block number to retrieve the commitment from. If None, the latest block is used. Default is None. - block_hash (Optional[str]): The hash of the block to retrieve the subnet unique identifiers from. - reuse_block (bool): Whether to reuse the last-used block hash. + block_hash: The hash of the block to retrieve the subnet unique identifiers from. + reuse_block: Whether to reuse the last-used block hash. Returns: dict[str, str]: A mapping of the ss58:commitment with the commitment as a string. @@ -1571,11 +1565,11 @@ async def get_revealed_commitment_by_hotkey( """Returns hotkey related revealed commitment for a given netuid. Arguments: - netuid (int): The unique identifier of the subnetwork. - block (Optional[int]): The block number to retrieve the commitment from. Default is ``None``. + netuid: The unique identifier of the subnetwork. + block: The block number to retrieve the commitment from. Default is `None`. hotkey_ss58_address (str): The ss58 address of the committee member. - block_hash (Optional[str]): The hash of the block to retrieve the subnet unique identifiers from. - reuse_block (bool): Whether to reuse the last-used block hash. + block_hash: The hash of the block to retrieve the subnet unique identifiers from. + reuse_block: Whether to reuse the last-used block hash. Returns: result (tuple[int, str): A tuple of reveal block and commitment message. @@ -1604,9 +1598,9 @@ async def get_revealed_commitment( """Returns uid related revealed commitment for a given netuid. Arguments: - netuid (int): The unique identifier of the subnetwork. - uid (int): The neuron uid to retrieve the commitment from. - block (Optional[int]): The block number to retrieve the commitment from. Default is ``None``. + netuid: The unique identifier of the subnetwork. + uid: The neuron uid to retrieve the commitment from. + block: The block number to retrieve the commitment from. Default is `None`. Returns: result (Optional[tuple[int, str]]: A tuple of reveal block and commitment message. @@ -1638,10 +1632,10 @@ async def get_all_revealed_commitments( """Returns all revealed commitments for a given netuid. Arguments: - netuid (int): The unique identifier of the subnetwork. - block (Optional[int]): The block number to retrieve the commitment from. Default is ``None``. - block_hash (Optional[str]): The hash of the block to retrieve the subnet unique identifiers from. - reuse_block (bool): Whether to reuse the last-used block hash. + netuid: The unique identifier of the subnetwork. + block: The block number to retrieve the commitment from. Default is `None`. + block_hash: The hash of the block to retrieve the subnet unique identifiers from. + reuse_block: Whether to reuse the last-used block hash. Returns: result (dict): A dictionary of all revealed commitments in view @@ -1681,10 +1675,10 @@ async def get_current_weight_commit_info( Retrieves CRV3 weight commit information for a specific subnet. Arguments: - netuid (int): The unique identifier of the subnet. - block (Optional[int]): The blockchain block number for the query. Default is ``None``. - block_hash (Optional[str]): The hash of the block to retrieve the subnet unique identifiers from. - reuse_block (bool): Whether to reuse the last-used block hash. + netuid: The unique identifier of the subnet. + block: The blockchain block number for the query. Default is `None`. + block_hash: The hash of the block to retrieve the subnet unique identifiers from. + reuse_block: Whether to reuse the last-used block hash. Returns: list: A list of commit details, where each entry is a dictionary with keys 'who', 'serialized_commit', and @@ -1714,13 +1708,13 @@ async def get_delegate_by_hotkey( comprehensive view of the delegate's status, including its stakes, nominators, and reward distribution. Arguments: - hotkey_ss58 (str): The ``SS58`` address of the delegate's hotkey. - block (Optional[int]): The blockchain block number for the query. - block_hash (Optional[str]): The hash of the block to retrieve the subnet unique identifiers from. - reuse_block (bool): Whether to reuse the last-used block hash. + hotkey_ss58: The `SS58` address of the delegate's hotkey. + block: The blockchain block number for the query. + block_hash: The hash of the block to retrieve the subnet unique identifiers from. + reuse_block: Whether to reuse the last-used block hash. Returns: - Optional[DelegateInfo]: Detailed information about the delegate neuron, ``None`` if not found. + Optional[DelegateInfo]: Detailed information about the delegate neuron, `None` if not found. This function is essential for understanding the roles and influence of delegate neurons within the Bittensor network's consensus and governance structures. @@ -1750,9 +1744,9 @@ async def get_delegate_identities( Fetches delegates identities from the chain. Arguments: - block (Optional[int]): The blockchain block number for the query. - block_hash (str): the hash of the blockchain block for the query - reuse_block (bool): Whether to reuse the last-used blockchain block hash. + block: The blockchain block number for the query. + block_hash: the hash of the blockchain block for the query + reuse_block: Whether to reuse the last-used blockchain block hash. Returns: Dict {ss58: ChainIdentity, ...} @@ -1785,10 +1779,10 @@ async def get_delegate_take( percentage of rewards that the delegate claims from its nominators' stakes. Arguments: - hotkey_ss58 (str): The ``SS58`` address of the neuron's hotkey. - block (Optional[int]): The blockchain block number for the query. - block_hash (Optional[str]): The hash of the block to retrieve the subnet unique identifiers from. - reuse_block (bool): Whether to reuse the last-used block hash. + hotkey_ss58: The `SS58` address of the neuron's hotkey. + block: The blockchain block number for the query. + block_hash: The hash of the block to retrieve the subnet unique identifiers from. + reuse_block: Whether to reuse the last-used block hash. Returns: float: The delegate take percentage. @@ -1818,10 +1812,10 @@ async def get_delegated( delegates that a specific account has staked tokens on. Arguments: - coldkey_ss58 (str): The `SS58` address of the account's coldkey. - block (Optional[int]): The blockchain block number for the query. - block_hash (Optional[str]): The hash of the blockchain block number for the query. - reuse_block (bool): Whether to reuse the last-used blockchain block hash. + coldkey_ss58: The `SS58` address of the account's coldkey. + block: The blockchain block number for the query. + block_hash: The hash of the blockchain block number for the query. + reuse_block: Whether to reuse the last-used blockchain block hash. Returns: A list of tuples, each containing a delegate's information and staked amount. @@ -1854,7 +1848,7 @@ async def get_delegates( Fetches all delegates on the chain Arguments: - block (Optional[int]): The blockchain block number for the query. + block: The blockchain block number for the query. block_hash (Optional[str]): hash of the blockchain block number for the query. reuse_block (Optional[bool]): whether to reuse the last-used block hash. @@ -1886,9 +1880,9 @@ async def get_existential_deposit( Accounts with balances below this threshold can be reaped to conserve network resources. Arguments: - block (Optional[int]): The blockchain block number for the query. + block: The blockchain block number for the query. block_hash (str): Block hash at which to query the deposit amount. If `None`, the current block is used. - reuse_block (bool): Whether to reuse the last-used blockchain block hash. + reuse_block: Whether to reuse the last-used blockchain block hash. Returns: The existential deposit amount. @@ -2091,8 +2085,8 @@ async def get_netuids_for_hotkey( specific subnets within the Bittensor network where the neuron associated with the hotkey is active. Arguments: - hotkey_ss58 (str): The ``SS58`` address of the neuron's hotkey. - block (Optional[int]): The blockchain block number for the query. + hotkey_ss58: The `SS58` address of the neuron's hotkey. + block: The blockchain block number for the query. block_hash (Optional[str]): The hash of the blockchain block number at which to perform the query. reuse_block (Optional[bool]): Whether to reuse the last-used block hash when retrieving info. @@ -2371,15 +2365,16 @@ async def get_neuron_for_pubkey_and_subnet( (netuid). This function provides detailed neuron information for a particular subnet within the Bittensor network. - Arguments:(str): The ``SS58`` address of the neuron's hotkey. - netuid (int): The unique identifier of the subnet. - block (Optional[int]): The blockchain block number for the query. + Arguments: + hotkey: The `SS58` address of the neuron's hotkey. + netuid: The unique identifier of the subnet. + block: The blockchain block number for the query. block_hash: The blockchain block number at which to perform the query. reuse_block: Whether to reuse the last-used blockchain block hash. Returns: Optional[bittensor.core.chain_data.neuron_info.NeuronInfo]: Detailed information about the neuron if found, - ``None`` otherwise. + `None` otherwise. This function is crucial for accessing specific neuron data and understanding its status, stake, and other attributes within a particular subnet of the Bittensor ecosystem. @@ -2456,8 +2451,8 @@ async def get_owned_hotkeys( Arguments: coldkey_ss58 (str): The SS58 address of the coldkey to query. block (int): The blockchain block number for the query. - block_hash (str): The hash of the blockchain block number for the query. - reuse_block (bool): Whether to reuse the last-used blockchain block hash. + block_hash: The hash of the blockchain block number for the query. + reuse_block: Whether to reuse the last-used blockchain block hash. Returns: list[str]: A list of hotkey SS58 addresses owned by the coldkey. @@ -2486,9 +2481,9 @@ async def get_stake( Returns the stake under a coldkey - hotkey pairing. Arguments: - hotkey_ss58 (str): The SS58 address of the hotkey. + hotkey_ss58: The SS58 address of the hotkey. coldkey_ss58 (str): The SS58 address of the coldkey. - netuid (int): The subnet ID. + netuid: The subnet ID. block (Optional[int]): The block number at which to query the stake information. block_hash (Optional[str]): The hash of the block to retrieve the stake from. Do not specify if using block or reuse_block @@ -2768,7 +2763,7 @@ async def get_stake_for_coldkey_and_hotkey( Arguments: coldkey_ss58 (str): The SS58 address of the coldkey. - hotkey_ss58 (str): The SS58 address of the hotkey. + hotkey_ss58: The SS58 address of the hotkey. netuids (Optional[list[int]]): The subnet IDs to query for. Set to `None` for all subnets. block (Optional[int]): The block number at which to query the stake information. block_hash (Optional[str]): The hash of the block to retrieve the stake from. Do not specify if using block @@ -2816,11 +2811,11 @@ async def get_stake_for_coldkey( Arguments: coldkey_ss58 (str): The SS58 address of the coldkey. block (Optional[int]): The block number at which to query the stake information. - block_hash (Optional[str]): The hash of the blockchain block number for the query. - reuse_block (bool): Whether to reuse the last-used block hash. + block_hash: The hash of the blockchain block number for the query. + reuse_block: Whether to reuse the last-used block hash. Returns: - Optional[list[StakeInfo]]: A list of StakeInfo objects, or ``None`` if no stake information is found. + Optional[list[StakeInfo]]: A list of StakeInfo objects, or `None` if no stake information is found. """ result = await self.query_runtime_api( runtime_api="StakeInfoRuntimeApi", @@ -2884,7 +2879,7 @@ async def get_subnet_burn_cost( amount of Tao that needs to be locked or burned to establish a new Arguments: - block (Optional[int]): The blockchain block number for the query. + block: The blockchain block number for the query. block_hash: The blockchain block_hash of the block id. reuse_block: Whether to reuse the last-used block hash. @@ -2919,10 +2914,10 @@ async def get_subnet_hyperparameters( the operational settings and rules governing the subnet's behavior. Arguments: - netuid (int): The network UID of the subnet to query. - block (Optional[int]): The blockchain block number for the query. - block_hash (Optional[str]): The hash of the blockchain block number for the query. - reuse_block (bool): Whether to reuse the last-used blockchain hash. + netuid: The network UID of the subnet to query. + block: The blockchain block number for the query. + block_hash: The hash of the blockchain block number for the query. + reuse_blocko reuse the last-used blockchain hash. Returns: The subnet's hyperparameters, or `None` if not available. @@ -2963,9 +2958,9 @@ async def get_subnets( Retrieves the list of all subnet unique identifiers (netuids) currently present in the Bittensor network. Arguments: - block (Optional[int]): The blockchain block number for the query. - block_hash (Optional[str]): The hash of the block to retrieve the subnet unique identifiers from. - reuse_block (bool): Whether to reuse the last-used block hash. + block: The blockchain block number for the query. + block_hash: The hash of the block to retrieve the subnet unique identifiers from. + reuse_block: Whether to reuse the last-used block hash. Returns: A list of subnet netuids. @@ -2997,9 +2992,9 @@ async def get_total_subnets( Retrieves the total number of subnets within the Bittensor network as of a specific blockchain block. Arguments: - block (Optional[int]): The blockchain block number for the query. - block_hash (Optional[str]): The blockchain block_hash representation of block id. - reuse_block (bool): Whether to reuse the last-used block hash. + block: The blockchain block number for the query. + block_hash: The blockchain block_hash representation of block id. + reuse_block: Whether to reuse the last-used block hash. Returns: Optional[str]: The total number of subnets in the network. @@ -3026,13 +3021,10 @@ async def get_transfer_fee( conditions and transaction complexity. Arguments: - wallet (bittensor_wallet.Wallet): The wallet from which the transfer is initiated. - dest (str): The ``SS58`` address of the destination account. - value (Union[bittensor.utils.balance.Balance, float, int]): The amount of tokens to be transferred, - specified as a Balance object, or in Tao (float) or Rao (int) units. - - Returns: - bittensor.utils.balance.Balance: The estimated transaction fee for the transfer, represented as a Balance + wallet: The wallet from which the transfer is initiated. + des: The `SS58` address of the destination account. + valuer.utils.balance.Balance, float, int]): The amount of tokens to be transferred, + specified as a Balance object, or in Tao (float) or Rao (int) unit bittensor.utils.balance.Balance: The estimated transaction fee for the transfer, represented as a Balance object. Estimating the transfer fee is essential for planning and executing token transactions, ensuring that the wallet @@ -3070,9 +3062,9 @@ async def get_vote_data( Arguments: proposal_hash (str): The hash of the proposal for which voting data is requested. - block (Optional[int]): The blockchain block number for the query. + block: The blockchain block number for the query. block_hash (Optional[str]): The hash of the blockchain block number to query the voting data. - reuse_block (bool): Whether to reuse the last-used blockchain block hash. + reuse_block: Whether to reuse the last-used blockchain block hash. Returns: An object containing the proposal's voting data, or `None` if not found. @@ -3106,14 +3098,14 @@ async def get_uid_for_hotkey_on_subnet( Retrieves the unique identifier (UID) for a neuron's hotkey on a specific subnet. Arguments: - hotkey_ss58 (str): The ``SS58`` address of the neuron's hotkey. - netuid (int): The unique identifier of the subnet. - block (Optional[int]): The blockchain block number for the query. + hotkey_ss58: The `SS58` address of the neuron's hotkey. + netuid: The unique identifier of the subnet. + block: The blockchain block number for the query. block_hash (Optional[str]): The blockchain block_hash representation of the block id. - reuse_block (bool): Whether to reuse the last-used blockchain block hash. + reuse_block: Whether to reuse the last-used blockchain block hash. Returns: - Optional[int]: The UID of the neuron if it is registered on the subnet, ``None`` otherwise. + Optional[int]: The UID of the neuron if it is registered on the subnet, `None` otherwise. The UID is a critical identifier within the network, linking the neuron's hotkey to its operational and governance activities on a particular subnet. @@ -3144,7 +3136,7 @@ async def filter_netuids_by_registered_hotkeys( all_netuids (Iterable[int]): A list of netuids to filter. filter_for_netuids (Iterable[int]): A subset of all_netuids to filter from the main list. all_hotkeys (Iterable[Wallet]): Hotkeys to filter from the main list. - block (Optional[int]): The blockchain block number for the query. + block: The blockchain block number for the query. block_hash (str): hash of the blockchain block number at which to perform the query. reuse_block (bool): whether to reuse the last-used blockchain hash when retrieving info. @@ -3198,13 +3190,13 @@ async def immunity_period( which new neurons are protected from certain network penalties or restrictions. Arguments: - netuid (int): The unique identifier of the subnet. - block (Optional[int]): The blockchain block number for the query. + netuid: The unique identifier of the subnet. + block: The blockchain block number for the query. block_hash (Optional[str]): The blockchain block_hash representation of the block id. - reuse_block (bool): Whether to reuse the last-used blockchain block hash. + reuse_block: Whether to reuse the last-used blockchain block hash. Returns: - Optional[int]: The value of the 'ImmunityPeriod' hyperparameter if the subnet exists, ``None`` otherwise. + Optional[int]: The value of the 'ImmunityPeriod' hyperparameter if the subnet exists, `None` otherwise. The 'ImmunityPeriod' is a critical aspect of the network's governance system, ensuring that new participants have a grace period to establish themselves and contribute to the network without facing immediate @@ -3237,9 +3229,9 @@ async def is_hotkey_delegate( the neuron associated with the hotkey is part of the network's delegation system. Arguments: - hotkey_ss58 (str): The SS58 address of the neuron's hotkey. - block (Optional[int]): The blockchain block number for the query. - block_hash (Optional[str]): The hash of the blockchain block number for the query. + hotkey_ss58: The SS58 address of the neuron's hotkey. + block: The blockchain block number for the query. + block_hash: The hash of the blockchain block number for the query. reuse_block (Optional[bool]): Whether to reuse the last-used block hash. Returns: @@ -3275,7 +3267,7 @@ async def is_hotkey_registered( block: The blockchain block number at which to perform the query. block_hash: The blockchain block_hash representation of the block id. Do not specify if using block or reuse_block - reuse_block (bool): Whether to reuse the last-used blockchain block hash. Do not set if using block_hash or + reuse_block: Whether to reuse the last-used blockchain block hash. Do not set if using block_hash or reuse_block. Returns: @@ -3306,13 +3298,13 @@ async def is_hotkey_registered_any( Checks if a neuron's hotkey is registered on any subnet within the Bittensor network. Arguments: - hotkey_ss58 (str): The ``SS58`` address of the neuron's hotkey. - block (Optional[int]): The blockchain block number for the query. - block_hash (Optional[str]): The blockchain block_hash representation of block id. - reuse_block (bool): Whether to reuse the last-used block hash. + hotkey_ss58: The `SS58` address of the neuron's hotkey. + block: The blockchain block number for the query. + block_hash: The blockchain block_hash representation of block id. + reuse_block: Whether to reuse the last-used block hash. Returns: - bool: ``True`` if the hotkey is registered on any subnet, False otherwise. + bool: `True` if the hotkey is registered on any subnet, False otherwise. This function is essential for determining the network-wide presence and participation of a neuron. """ @@ -3351,13 +3343,13 @@ async def is_subnet_active( """Verify if subnet with provided netuid is active. Arguments: - netuid (int): The unique identifier of the subnet. - block (Optional[int]): The blockchain block number for the query. - block_hash (Optional[str]): The blockchain block_hash representation of block id. - reuse_block (bool): Whether to reuse the last-used block hash. + netuid: The unique identifier of the subnet. + block: The blockchain block number for the query. + block_hash: The blockchain block_hash representation of block id. + reuse_block: Whether to reuse the last-used block hash. Returns: - True if subnet is active, False otherwise. + `True` if subnet is active, `False` otherwise. This means whether the `start_call` was initiated or not. """ @@ -3393,13 +3385,13 @@ async def max_weight_limit( Returns network MaxWeightsLimit hyperparameter. Arguments: - netuid (int): The unique identifier of the subnetwork. - block (Optional[int]): The blockchain block number for the query. - block_hash (Optional[str]): The blockchain block_hash representation of block id. - reuse_block (bool): Whether to reuse the last-used block hash. + netuid: The unique identifier of the subnetwork. + block: The blockchain block number for the query. + block_hash: The blockchain block_hash representation of block id. + reuse_block: Whether to reuse the last-used block hash. Returns: - Optional[float]: The value of the MaxWeightsLimit hyperparameter, or ``None`` if the subnetwork does not + Optional[float]: The value of the MaxWeightsLimit hyperparameter, or `None` if the subnetwork does not exist or the parameter is not found. """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) @@ -3419,10 +3411,10 @@ async def metagraph( network's structure, including neuron connections and interactions. Arguments: - netuid (int): The network UID of the subnet to query. - lite (bool): If true, returns a metagraph using a lightweight sync (no weights, no bonds). Default is - ``True``. - block (Optional[int]): Block number for synchronization, or ``None`` for the latest block. + netuid: The network UID of the subnet to query. + lite: If true, returns a metagraph using a lightweight sync (no weights, no bonds). Default is + `True`. + block: Block number for synchronization, or `None` for the latest block. Returns: bittensor.core.metagraph.Metagraph: The metagraph representing the subnet's structure and neuron @@ -3453,13 +3445,13 @@ async def min_allowed_weights( Returns network MinAllowedWeights hyperparameter. Arguments: - netuid (int): The unique identifier of the subnetwork. - block (Optional[int]): The blockchain block number for the query. - block_hash (Optional[str]): The blockchain block_hash representation of block id. - reuse_block (bool): Whether to reuse the last-used block hash. + netuid: The unique identifier of the subnetwork. + block: The blockchain block number for the query. + block_hash: The blockchain block_hash representation of block id. + reuse_block: Whether to reuse the last-used block hash. Returns: - Optional[int]: The value of the MinAllowedWeights hyperparameter, or ``None`` if the subnetwork does not + Optional[int]: The value of the MinAllowedWeights hyperparameter, or `None` if the subnetwork does not exist or the parameter is not found. """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) @@ -3485,11 +3477,11 @@ async def neuron_for_uid( neuron's attributes, including its stake, rank, and operational status. Arguments: - uid (int): The unique identifier of the neuron. - netuid (int): The unique identifier of the subnet. - block (Optional[int]): The blockchain block number for the query. - block_hash (str): The hash of the blockchain block number for the query. - reuse_block (bool): Whether to reuse the last-used blockchain block hash. + uid: The unique identifier of the neuron. + netuid: The unique identifier of the subnet. + block: The blockchain block number for the query. + block_hash: The hash of the blockchain block number for the query. + reuse_block: Whether to reuse the last-used blockchain block hash. Returns: Detailed information about the neuron if found, a null neuron otherwise @@ -3527,10 +3519,10 @@ async def neurons( network interactions. Arguments: - netuid (int): The unique identifier of the subnet. - block (Optional[int]): The blockchain block number for the query. - block_hash (str): The hash of the blockchain block number for the query. - reuse_block (bool): Whether to reuse the last-used blockchain block hash. + netuid: The unique identifier of the subnet. + block: The blockchain block number for the query. + block_hash: The hash of the blockchain block number for the query. + reuse_block: Whether to reuse the last-used blockchain block hash. Returns: A list of NeuronInfo objects detailing each neuron's characteristics in the subnet. @@ -3565,10 +3557,10 @@ async def neurons_lite( participation. Arguments: - netuid (int): The unique identifier of the subnet. - block (Optional[int]): The blockchain block number for the query. - block_hash (str): The hash of the blockchain block number for the query. - reuse_block (bool): Whether to reuse the last-used blockchain block hash. + netuid: The unique identifier of the subnet. + block: The blockchain block number for the query. + block_hash: The hash of the blockchain block number for the query. + reuse_block: Whether to reuse the last-used blockchain block hash. Returns: A list of simplified neuron information for the subnet. @@ -3603,14 +3595,14 @@ async def query_identity( decentralized identity and governance system. Arguments: - coldkey_ss58 (str): The coldkey used to query the neuron's identity (technically the neuron's coldkey SS58 + coldkey_ss58: The coldkey used to query the neuron's identity (technically the neuron's coldkey SS58 address). - block (Optional[int]): The blockchain block number for the query. - block_hash (str): The hash of the blockchain block number at which to perform the query. - reuse_block (bool): Whether to reuse the last-used blockchain block hash. + block: The blockchain block number for the query. + block_hash: The hash of the blockchain block number at which to perform the query. + reuse_block: Whether to reuse the last-used blockchain block hash. Returns: - An object containing the identity information of the neuron if found, ``None`` otherwise. + An object containing the identity information of the neuron if found, `None` otherwise. The identity information can include various attributes such as the neuron's stake, rank, and other network-specific details, providing insights into the neuron's role and status within the Bittensor network. @@ -3650,10 +3642,10 @@ async def recycle( that is effectively recycled within the Bittensor network. Arguments: - netuid (int): The unique identifier of the subnet. - block (Optional[int]): The blockchain block number for the query. - block_hash (str): The hash of the blockchain block number for the query. - reuse_block (bool): Whether to reuse the last-used blockchain block hash. + netuid: The unique identifier of the subnet. + block: The blockchain block number for the query. + block_hash: The hash of the blockchain block number for the query. + reuse_block: Whether to reuse the last-used blockchain block hash. Returns: Optional[Balance]: The value of the 'Burn' hyperparameter if the subnet exists, None otherwise. @@ -3683,13 +3675,13 @@ async def set_reveal_commitment( Commits arbitrary data to the Bittensor network by publishing metadata. Arguments: - wallet (bittensor_wallet.Wallet): The wallet associated with the neuron committing the data. - netuid (int): The unique identifier of the subnetwork. - data (str): The data to be committed to the network. - blocks_until_reveal (int): The number of blocks from now after which the data will be revealed. + wallet: The wallet associated with the neuron committing the data. + netuid: The unique identifier of the subnetwork. + data: The data to be committed to the network. + blocks_until_reveal: The number of blocks from now after which the data will be revealed. Defaults to `360` (the number of blocks in one epoch). - block_time (Union[int, float]): The number of seconds between each block. Defaults to `12`. - period (Optional[int]): The number of blocks during which the transaction will remain valid after it's + block_time: The number of seconds between each block. Defaults to `12`. + period: The number of blocks during which the transaction will remain valid after it's submitted. If the transaction is not included in a block within that number of blocks, it will expire and be rejected. You can think of it as an expiration date for the transaction. @@ -3726,10 +3718,10 @@ async def subnet( Retrieves the subnet information for a single subnet in the Bittensor network. Arguments: - netuid (int): The unique identifier of the subnet. - block (Optional[int]): The block number to get the subnets at. - block_hash (Optional[str]): The hash of the blockchain block number for the query. - reuse_block (bool): Whether to reuse the last-used blockchain block hash. + netuid: The unique identifier of the subnet. + block: The block number to get the subnets at. + block_hash: The hash of the blockchain block number for the query. + reuse_block: Whether to reuse the last-used blockchain block hash. Returns: Optional[DynamicInfo]: A DynamicInfo object, containing detailed information about a subnet. @@ -3762,10 +3754,10 @@ async def subnet_exists( Checks if a subnet with the specified unique identifier (netuid) exists within the Bittensor network. Arguments: - netuid (int): The unique identifier of the subnet. - block (Optional[int]): The blockchain block number for the query. - block_hash (Optional[str]): The hash of the blockchain block number at which to check the subnet existence. - reuse_block (bool): Whether to reuse the last-used block hash. + netuid: The unique identifier of the subnet. + block: The blockchain block number for the query. + block_hash: The hash of the blockchain block number at which to check the subnet existence. + reuse_block: Whether to reuse the last-used block hash. Returns: `True` if the subnet exists, `False` otherwise. @@ -3794,13 +3786,13 @@ async def subnetwork_n( Returns network SubnetworkN hyperparameter. Arguments: - netuid (int): The unique identifier of the subnetwork. - block (Optional[int]): The blockchain block number for the query. - block_hash (Optional[str]): The hash of the blockchain block number at which to check the subnet existence. - reuse_block (bool): Whether to reuse the last-used block hash. + netuid: The unique identifier of the subnetwork. + block: The blockchain block number for the query. + block_hash: The hash of the blockchain block number at which to check the subnet existence. + reuse_block: Whether to reuse the last-used block hash. Returns: - Optional[int]: The value of the SubnetworkN hyperparameter, or ``None`` if the subnetwork does not exist or + Optional[int]: The value of the SubnetworkN hyperparameter, or `None` if the subnetwork does not exist or the parameter is not found. """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) @@ -3823,13 +3815,13 @@ async def tempo( Returns network Tempo hyperparameter. Arguments: - netuid (int): The unique identifier of the subnetwork. - block (Optional[int]): The blockchain block number for the query. - block_hash (Optional[str]): The hash of the blockchain block number at which to check the subnet existence. - reuse_block (bool): Whether to reuse the last-used block hash. + netuid: The unique identifier of the subnetwork. + block: The blockchain block number for the query. + block_hash: The hash of the blockchain block number at which to check the subnet existence. + reuse_block: Whether to reuse the last-used block hash. Returns: - Optional[int]: The value of the Tempo hyperparameter, or ``None`` if the subnetwork does not exist or the + Optional[int]: The value of the Tempo hyperparameter, or `None` if the subnetwork does not exist or the parameter is not found. """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) @@ -3852,9 +3844,9 @@ async def tx_rate_limit( This rate limit sets the maximum number of transactions that can be processed within a given time frame. Arguments: - block (Optional[int]): The blockchain block number for the query. - block_hash (Optional[str]): The hash of the blockchain block number at which to check the subnet existence. - reuse_block (bool): Whether to reuse the last-used block hash. + block: The blockchain block number for the query. + block_hash: The hash of the blockchain block number at which to check the subnet existence. + reuse_block: Whether to reuse the last-used block hash. Returns: Optional[int]: The transaction rate limit of the network, None if not available. @@ -3875,7 +3867,7 @@ async def wait_for_block(self, block: Optional[int] = None): waits for the next block. Arguments: - block (Optional[int]): The block number to wait for. If None, waits for the next block. + block: The block number to wait for. If None, waits for the next block. Returns: bool: True if the target block was reached, False if timeout occurred. @@ -3922,10 +3914,10 @@ async def weights( and value assignment mechanisms. Arguments: - netuid (int): The network UID of the subnet to query. - block (Optional[int]): Block number for synchronization, or ``None`` for the latest block. - block_hash (str): The hash of the blockchain block for the query. - reuse_block (bool): Whether to reuse the last-used blockchain block hash. + netuid: The network UID of the subnet to query. + block: Block number for synchronization, or `None` for the latest block. + block_hash: The hash of the blockchain block for the query. + reuse_blocko reuse the last-used blockchain block hash. Returns: A list of tuples mapping each neuron's UID to its assigned weights. @@ -3959,13 +3951,13 @@ async def weights_rate_limit( Returns network WeightsSetRateLimit hyperparameter. Arguments: - netuid (int): The unique identifier of the subnetwork. - block (Optional[int]): The blockchain block number for the query. + netuid: The unique identifier of the subnetwork. + block: The blockchain block number for the query. block_hash (Optional[str]): The blockchain block_hash representation of the block id. - reuse_block (bool): Whether to reuse the last-used blockchain block hash. + reuse_block: Whether to reuse the last-used blockchain block hash. Returns: - Optional[int]: The value of the WeightsSetRateLimit hyperparameter, or ``None`` if the subnetwork does not + Optional[int]: The value of the WeightsSetRateLimit hyperparameter, or `None` if the subnetwork does not exist or the parameter is not found. """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) @@ -4064,13 +4056,13 @@ async def sign_and_send_extrinsic( Helper method to sign and submit an extrinsic call to chain. Arguments: - call (scalecodec.types.GenericCall): a prepared Call object - wallet (bittensor_wallet.Wallet): the wallet whose coldkey will be used to sign the extrinsic - wait_for_inclusion (bool): whether to wait until the extrinsic call is included on the chain - wait_for_finalization (bool): whether to wait until the extrinsic call is finalized on the chain + call: a prepared Call object + wallet: the wallet whose coldkey will be used to sign the extrinsic + wait_for_inclusion: whether to wait until the extrinsic call is included on the chain + wait_for_finalization: whether to wait until the extrinsic call is finalized on the chain sign_with: the wallet's keypair to use for the signing. Options are "coldkey", "hotkey", "coldkeypub" use_nonce: unique identifier for the transaction related with hot/coldkey. - period (Optional[int]): The number of blocks during which the transaction will remain valid after it's + period: The number of blocks during which the transaction will remain valid after it's submitted. If the transaction is not included in a block within that number of blocks, it will expire and be rejected. You can think of it as an expiration date for the transaction. nonce_key: the type on nonce to use. Options are "hotkey" or "coldkey". @@ -4152,24 +4144,24 @@ async def add_stake( Arguments: wallet: The wallet to be used for staking. hotkey_ss58: The SS58 address of the hotkey associated with the neuron to which you intend to delegate your - stake. If not specified, the wallet's hotkey will be used. Defaults to ``None``. + stake. If not specified, the wallet's hotkey will be used. Defaults to `None`. netuid: The unique identifier of the subnet to which the neuron belongs. amount: The amount of TAO to stake. - wait_for_inclusion: Waits for the transaction to be included in a block. Defaults to ``True``. - wait_for_finalization: Waits for the transaction to be finalized on the blockchain. Defaults to ``False``. + wait_for_inclusion: Waits for the transaction to be included in a block. Defaults to `True`. + wait_for_finalization: Waits for the transaction to be finalized on the blockchain. Defaults to `False`. safe_staking: If true, enables price safety checks to protect against fluctuating prices. The stake will - only execute if the price change doesn't exceed the rate tolerance. Default is ``False``. + only execute if the price change doesn't exceed the rate tolerance. Default is `False`. allow_partial_stake: If true and safe_staking is enabled, allows partial staking when the full amount would exceed the price tolerance. If false, the entire stake fails if it would exceed the tolerance. - Default is ``False``. + Default is `False`. rate_tolerance: The maximum allowed price change ratio when staking. For example, 0.005 = 0.5% maximum price increase. Only used when safe_staking is True. Default is ``0.005``. period: The number of blocks during which the transaction will remain valid after it's submitted. If the transaction is not included in a block within that number of blocks, it will expire and be rejected. You - can think of it as an expiration date for the transaction. Defaults to ``None``. + can think of it as an expiration date for the transaction. Defaults to `None`. Returns: - bool: ``True`` if the staking is successful, False otherwise. + bool: `True` if the staking is successful, False otherwise. This function enables neurons to increase their stake in the network, enhancing their influence and potential. When safe_staking is enabled, it provides protection against price fluctuations during the time stake is @@ -4254,15 +4246,14 @@ async def add_stake_multiple( This bulk operation allows for efficient staking across different neurons from a single wallet. Arguments: - wallet (bittensor_wallet.Wallet): The wallet used for staking. - hotkey_ss58s (list[str]): List of ``SS58`` addresses of hotkeys to stake to. - netuids: list of subnet UIDs - amounts (list[Balance]): Corresponding amounts of TAO to stake for each hotkey. - wait_for_inclusion (bool): Waits for the transaction to be included in a block. - wait_for_finalization (bool): Waits for the transaction to be finalized on the blockchain. + wallet: The wallet used for staking. + hotkey_ss58s: List of `SS58` addresses of hotkeys to stake to. + netui: list of subnet UIDs + amounts: Corresponding amounts of TAO to stake for each hotkey. + wait_for_inclusion: Waits for the transaction to be included inor_finalization (bool): Waits for the transaction to be finalized on the blockchain. Returns: - bool: ``True`` if the staking is successful for all specified neurons, False otherwise. + bool: `True` if the staking is successful for all specified neurons, False otherwise. This function is essential for managing stakes across multiple neurons, reflecting the dynamic and collaborative nature of the Bittensor network. @@ -4290,18 +4281,17 @@ async def burned_register( TAO tokens, allowing them to be re-mined by performing work on the network. Arguments: - wallet (bittensor_wallet.Wallet): The wallet associated with the neuron to be registered. - netuid (int): The unique identifier of the subnet. - wait_for_inclusion (bool, optional): Waits for the transaction to be included in a block. Defaults to + wallet: The wallet associated with the neuron to be registered. + netuid: The unique identifier of the subnet. + wait_for_inclusion: Waits for the transaction to be included in a block. Defaults to `False`. - wait_for_finalization (bool, optional): Waits for the transaction to be finalized on the blockchain. - Defaults to `True`. - period (Optional[int]): The number of blocks during which the transaction will remain valid after it's + wait_for_finalization: Waits for the transaction to be finalized on the blockchain. + period: The number of blocks during which the transaction will remain valid after it's submitted. If the transaction is not included in a block within that number of blocks, it will expire and be rejected. You can think of it as an expiration date for the transaction. Returns: - bool: ``True`` if the registration is successful, False otherwise. + bool: `True` if the registration is successful, False otherwise. """ async with self: if netuid == 0: @@ -4340,18 +4330,17 @@ async def commit_weights( This action serves as a commitment or snapshot of the validator's current weight distribution. Arguments: - wallet (bittensor_wallet.Wallet): The wallet associated with the subnet validator committing the weights. - netuid (int): The unique identifier of the subnet. - salt (list[int]): list of randomly generated integers as salt to generated weighted hash. - uids (np.ndarray): NumPy array of subnet miner neuron UIDs for which weights are being committed. - weights (np.ndarray): NumPy array of weight values corresponding to each UID. - version_key (int): Version key for compatibility with the network. Default is ``int representation of - a Bittensor version.``. - wait_for_inclusion (bool): Waits for the transaction to be included in a block. Default is ``False``. - wait_for_finalization (bool): Waits for the transaction to be finalized on the blockchain. Default is - ``False``. - max_retries (int): The number of maximum attempts to commit weights. Default is ``5``. - period (Optional[int]): The number of blocks during which the transaction will remain valid after it's + wallet: The wallet associated with the subnet validator committing the weights. + netuid: The unique identifier of the subnet. + salt: list of randomly generated integers as salt to generated weighted hash. + uids: NumPy array of subnet miner neuron UIDs for which weights are being committed. + weightsy of weight values corresponding toon_key + version_key: Integer representatino of version key for compatibility with the network. + wait_for_inclusion: Waits for the transaction to be included in a block. Default is `False`. + wait_for_finalization: Waits for the transaction to be finalized on the blockchain. Default is + `False`. + max_retries: The number of maximum attempts to commit weights. Default is `5`. + period: The number of blocks during which the transaction will remain valid after it's submitted. If the transaction is not included in a block within that number of blocks, it will expire and be rejected. You can think of it as an expiration date for the transaction. @@ -4494,20 +4483,20 @@ async def move_stake( Moves stake to a different hotkey and/or subnet. Arguments: - wallet (bittensor.wallet): The wallet to move stake from. - origin_hotkey (str): The SS58 address of the source hotkey. - origin_netuid (int): The netuid of the source subnet. - destination_hotkey (str): The SS58 address of the destination hotkey. - destination_netuid (int): The netuid of the destination subnet. - amount (Balance): Amount of stake to move. - wait_for_inclusion (bool): Waits for the transaction to be included in a block. - wait_for_finalization (bool): Waits for the transaction to be finalized on the blockchain. - period (Optional[int]): The number of blocks during which the transaction will remain valid after it's + wallet: The wallet to move stake from. + origin_hotkey: The SS58 address of the source hotkey. + origin_netuid: The netuid of the source subnet. + destination_hotkey: The SS58 address of the destination hotkey. + destination_netuid: The netuid of the destination subnet. + amount: Amount of stake to move. + wait_for_inclusion: Waits for the transaction to be included in a block. + wait_for_finalization: Waits for the transaction to be finalized on the blockchain. + period: The number of blocks during which the transaction will remain valid after it's submitted. If the transaction is not included in a block within that number of blocks, it will expire and be rejected. You can think of it as an expiration date for the transaction. Returns: - success (bool): True if the stake movement was successful. + success: True if the stake movement was successful. """ amount = check_and_convert_to_balance(amount) return await move_stake_extrinsic( @@ -4546,26 +4535,25 @@ async def register( stake, set weights, and receive incentives. Arguments: - wallet (bittensor_wallet.Wallet): The wallet associated with the neuron to be registered. - netuid (int): The unique identifier of the subnet. - wait_for_inclusion (bool): Waits for the transaction to be included in a block. Defaults to `False`. - wait_for_finalization (bool): Waits for the transaction to be finalized on the blockchain. Defaults to - `True`. - max_allowed_attempts (int): Maximum number of attempts to register the wallet. - output_in_place (bool): If true, prints the progress of the proof of work to the console in-place. Meaning + wallet: The wallet associated with the neuron to be registered. + nee unique identifier of the subnet. + wait_for_inclusion: Waits for the transaction to be included in a block. Defaults to `False`. + wait_for_finalization: Waits for the transaction to be finalized on the blockchain. Defaults to + max_allowed_attempts: Maximum number of attempts to register the wallet. + output_in_place: If true, prints the progress of the proof of work to the console in-place. Meaning the progress is printed on the same lines. Defaults to `True`. - cuda (bool): If ``true``, the wallet should be registered using CUDA device(s). Defaults to `False`. - dev_id (Union[List[int], int]): The CUDA device id to use, or a list of device ids. Defaults to `0` (zero). - tpb (int): The number of threads per block (CUDA). Default to `256`. - num_processes (Optional[int]): The number of processes to use to register. Default to `None`. - update_interval (Optional[int]): The number of nonces to solve between updates. Default to `None`. - log_verbose (bool): If ``true``, the registration process will log more information. Default to `False`. - period (Optional[int]): The number of blocks during which the transaction will remain valid after it's + cuda: If `true`, the wallet should be registered using CUDA device(s). Defaults to `False`. + dev_id: The CUDA device id to use, or a list of device ids. Defaults to `0` (zero). + tpb: The number of threads per block (CUDA). Default to `256`. + num_processes The number of processes to use to register. Default to `None`. + update_interval: The number of nonces to solve between updates. Default to `None`. + log_verbose: If `true`, the registration process will log more information. Default to `False`. + period: The number of blocks during which the transaction will remain valid after it's submitted. If the transaction is not included in a block within that number of blocks, it will expire and be rejected. You can think of it as an expiration date for the transaction. Returns: - bool: ``True`` if the registration is successful, False otherwise. + bool: `True` if the registration is successful, False otherwise. This function facilitates the entry of new neurons into the network, supporting the decentralized growth and scalability of the Bittensor ecosystem. @@ -4598,12 +4586,12 @@ async def register_subnet( Registers a new subnetwork on the Bittensor network. Arguments: - wallet (bittensor_wallet.Wallet): The wallet to be used for subnet registration. - 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. Default is `False`. - 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. Default is True. - period (Optional[int]): The number of blocks during which the transaction will remain valid after it's + wallet: The wallet to be used for subnet registration. + wait_for_inclusion: If set, waits for the extrinsic to enter a block before returning `True`, + os `False` if the extrinsic fails to enter the block within the timeout. Default is `False`. + wait_for_finalization: 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. Default is `False`. + period: The number of blocks during which the transaction will remain valid after it's submitted. If the transaction is not included in a block within that number of blocks, it will expire and be rejected. You can think of it as an expiration date for the transaction. @@ -4683,29 +4671,28 @@ async def reveal_weights( of the commit-reveal mechanism. Arguments: - wallet (bittensor_wallet.Wallet): The wallet associated with the subnet validator revealing the weights. - netuid (int): The unique identifier of the subnet. - uids (np.ndarray): NumPy array of subnet miner neuron UIDs for which weights are being revealed. - weights (np.ndarray): NumPy array of weight values corresponding to each UID. - salt (np.ndarray): NumPy array of salt values corresponding to the hash function. - version_key (int): Version key for compatibility with the network. Default is ``int representation of - the Bittensor version``. - wait_for_inclusion (bool): Waits for the transaction to be included in a block. Default is ``False``. - wait_for_finalization (bool): Waits for the transaction to be finalized on the blockchain. Default is - ``False``. - max_retries (int): The number of maximum attempts to reveal weights. Default is ``5``. - period (Optional[int]): The number of blocks during which the transaction will remain valid after it's + wallet: The wallet associated with the subnet validator revealing the weights. + nee unique identifier of the subnet. + uids: NumPy array of subnet miner neuron UIDs for which weights are being revealed. + weights: NumPy array of weight values corresponding to each UID. + salt: NumPy array of salt values + version_key: Version key for compatibility with the network. Default is `int representation of + the Bittensor version`. + wait_for_inclusion: Waits for the transaction to be included in a block. Default is `False`. + wait_for_finalization: Waits for the transaction to be finalized on the blockchain. Default is + `False`. + max_retries: The number of maximum attempts to reveal weights. Default is `5`. + period: The number of blocks during which the transaction will remain valid after it's submitted. If the transaction is not included in a block within that number of blocks, it will expire and be rejected. You can think of it as an expiration date for the transaction. Returns: - tuple[bool, str]: ``True`` if the weight revelation is successful, False otherwise. And `msg`, a string + tuple[bool, str]: `True` if the weight revelation is successful, False otherwise. And `msg`, a string value describing the success or potential error. This function allows subnet validators to reveal their previously committed weight vector. - Notes: - See also: , + See also: , """ retries = 0 success = False @@ -4746,10 +4733,10 @@ async def root_set_pending_childkey_cooldown( Arguments: wallet: bittensor wallet instance. cooldown: the number of blocks to setting pending childkey cooldown. - wait_for_inclusion (bool): Waits for the transaction to be included in a block. Default is ``False``. - wait_for_finalization (bool): Waits for the transaction to be finalized on the blockchain. Default is - ``False``. - period (Optional[int]): The number of blocks during which the transaction will remain valid after it's + wait_for_inclusion: Waits for the transaction to be included in a block. Default is `False`. + wait_for_finalization: Waits for the transaction to be finalized on the blockchain. Default is + `False`. + period: The number of blocks during which the transaction will remain valid after it's submitted. If the transaction is not included in a block within that number of blocks, it will expire and be rejected. You can think of it as an expiration date for the transaction. @@ -4816,17 +4803,15 @@ async def root_set_weights( Set weights for the root network. Arguments: - wallet (bittensor_wallet.Wallet): bittensor wallet instance. - netuids (list[int]): The list of subnet uids. - weights (list[float]): The list of weights to be set. - version_key (int, optional): Version key for compatibility with the network. Default is ``0``. - wait_for_inclusion (bool, optional): Waits for the transaction to be included in a block. Defaults to - ``False``. - wait_for_finalization (bool, optional): Waits for the transaction to be finalized on the blockchain. - Defaults to ``False``. - period (Optional[int]): The number of blocks during which the transaction will remain valid after it's - submitted. If the transaction is not included in a block within that number of blocks, it will expire - and be rejected. You can think of it as an expiration date for the transaction. + wallet: bittensor wallet instance. + netuids: The list of subnet uids. + weights: The list of weights to be set. + version_key: Version key for compatibility with the network. Default is `0`. + wait_for_inclusion: Waits for the transaction to be included in a block. + wait_for_finalization: Waits for the transaction to be finalized on the blockchain. Defaults to `False`. + period: The number of blocks during which the transaction will remain valid after it's submitted. If the + transaction is not included in a block within that number of blocks, it will expire and be rejected. + You can think of it as an expiration date for the transaction. Returns: `True` if the setting of weights is successful, `False` otherwise. @@ -4860,14 +4845,14 @@ async def set_children( Allows a coldkey to set children-keys. Arguments: - wallet (bittensor_wallet.Wallet): bittensor wallet instance. - hotkey (str): The ``SS58`` address of the neuron's hotkey. - netuid (int): The netuid value. - children (list[tuple[float, str]]): A list of children with their proportions. - wait_for_inclusion (bool): Waits for the transaction to be included in a block. - wait_for_finalization (bool): Waits for the transaction to be finalized on the blockchain. + wallet: bittensor wallet instance. + hotke: The `SS58` address of the neuron's hotkey. + netuid: The netuid value. + children: A list of children with their proportions. + wait_for_inclusion: Waits for the transaction to be included in a block. + wait_for_finalization: Waits for the transaction to be finalized on the blockchain. raise_error: Raises a relevant exception rather than returning `False` if unsuccessful. - period (Optional[int]): The number of blocks during which the transaction will remain valid after it's + period: The number of blocks during which the transaction will remain valid after it's submitted. If the transaction is not included in a block within that number of blocks, it will expire and be rejected. You can think of it as an expiration date for the transaction. @@ -4915,13 +4900,13 @@ async def set_delegate_take( The 'take' represents the percentage of rewards that the delegate claims from its nominators' stakes. Arguments: - wallet (bittensor_wallet.Wallet): bittensor wallet instance. - hotkey_ss58 (str): The ``SS58`` address of the neuron's hotkey. - take (float): Percentage reward for the delegate. - wait_for_inclusion (bool): Waits for the transaction to be included in a block. - wait_for_finalization (bool): Waits for the transaction to be finalized on the blockchain. - raise_error: Raises a relevant exception rather than returning `False` if unsuccessful. - period (Optional[int]): The number of blocks during which the transaction will remain valid after it's + wallet: bittensor wallet instance. + hotkey_ss58: The `SS58` address of the neuron's hotkey. + take: Percentage reward for the delegate. + wait_for_inclusion: Waits for the transaction to be included in a block. + wait_for_finalization: Waits for the transaction to be finalized on_error: Raises a relevant exception + rather than returning `False` if unsuccessful. + period: The number of blocks during which the transaction will remain valid after it's submitted. If the transaction is not included in a block within that number of blocks, it will expire and be rejected. You can think of it as an expiration date for the transaction. @@ -4996,15 +4981,15 @@ async def set_subnet_identity( Sets the identity of a subnet for a specific wallet and network. Arguments: - wallet (Wallet): The wallet instance that will authorize the transaction. - netuid (int): The unique ID of the network on which the operation takes place. + wallet: The wallet instance that will authorize the transaction. + netuid: The unique ID of the network on which the operation takes place. subnet_identity (SubnetIdentity): The identity data of the subnet including attributes like name, GitHub repository, contact, URL, discord, description, and any additional metadata. - wait_for_inclusion (bool): Indicates if the function should wait for the transaction to be included in the + wait_for_inclusion: Indicates if the function should wait for the transaction to be included in the block. - wait_for_finalization (bool): Indicates if the function should wait for the transaction to reach + wait_for_finalization: Indicates if the function should wait for the transaction to reach finalization. - period (Optional[int]): The number of blocks during which the transaction will remain valid after it's + period: The number of blocks during which the transaction will remain valid after it's submitted. If the transaction is not included in a block within that number of blocks, it will expire and be rejected. You can think of it as an expiration date for the transaction. @@ -5051,26 +5036,24 @@ async def set_weights( validators and miners. Arguments: - wallet (bittensor_wallet.Wallet): The wallet associated with the subnet validator setting the weights. - netuid (int): The unique identifier of the subnet. - uids (Union[NDArray[np.int64], torch.LongTensor, list]): The list of subnet miner neuron UIDs that the - weights are being - set for. - weights (Union[NDArray[np.float32], torch.FloatTensor, list]): The corresponding weights to be set for each + wallet: The wallet associated with the subnet validator setting the weights. + netuid: The unique identifier of the subnet. + uids: The list of subnet miner neuron UIDs that the weights are being set for. + weights: The corresponding weights to be set for each UID, representing the validator's evaluation of each miner's performance. UID, representing the validator's evaluation of each miner's performance. - version_key (int): Version key for compatibility with the network. Default is int representation of + version_key: Version key for compatibility with the network. Default is int representation of the Bittensor version. - wait_for_inclusion (bool): Waits for the transaction to be included in a block. Default is ``False``. - wait_for_finalization (bool): Waits for the transaction to be finalized on the blockchain. Default is - ``False``. - max_retries (int): The number of maximum attempts to set weights. Default is ``5``. - block_time (float): The number of seconds for block duration. Default is 12.0 seconds. - period (Optional[int]): The number of blocks during which the transaction will remain valid after it's + wait_for_inclusion: Waits for the transaction to be included in a block. Default is `False`. + wait_for_finalization: Waits for the transaction to be finalized on the blockchain. Default is + `False`. + max_retries: The number of maximum attempts to set weights. Default is `5`. + block_time: The number of seconds for block duration. Default is 12.0 seconds. + period: The number of blocks during which the transaction will remain valid after it's submitted. If the transaction is not included in a block within that number of blocks, it will expire and be rejected. You can think of it as an expiration date for the transaction. Default is 8. Returns: - tuple[bool, str]: ``True`` if the setting of weights is successful, False otherwise. And `msg`, a string + tuple[bool, str]: `True` if the setting of weights is successful, False otherwise. And `msg`, a string value describing the success or potential error. This function is crucial in the Yuma Consensus mechanism, where each validator's weight vector contributes @@ -5169,19 +5152,18 @@ async def serve_axon( set up the Axon, a key component of a neuron that handles incoming queries and data processing tasks. Arguments: - netuid (int): The unique identifier of the subnetwork. + netuid: The unique identifier of the subnetwork. axon (bittensor.core.axon.Axon): The Axon instance to be registered for serving. - wait_for_inclusion (bool): Waits for the transaction to be included in a block. Default is ``False``. - wait_for_finalization (bool): Waits for the transaction to be finalized on the blockchain. Default is - ``True``. - certificate (bittensor.utils.Certificate): Certificate to use for TLS. If ``None``, no TLS will be used. - Defaults to ``None``. - period (Optional[int]): The number of blocks during which the transaction will remain valid after it's + wait_for_inclusion: Waits for the transaction to be included in a block. Default is `False`. + wait_for_finalization: Waits for the transaction to be finalized on the blockchain. Default is + `True`. + certificate: Certificate to use for TLS. If `None`, no TLS will be used. Defaults to `None`. + period: The number of blocks during which the transaction will remain valid after it's submitted. If the transaction is not included in a block within that number of blocks, it will expire and be rejected. You can think of it as an expiration date for the transaction. Returns: - bool: ``True`` if the Axon serve registration is successful, False otherwise. + bool: `True` if the Axon serve registration is successful, False otherwise. By registering an Axon, the neuron becomes an active part of the network's distributed computing infrastructure, contributing to the collective intelligence of Bittensor. @@ -5209,15 +5191,13 @@ async def start_call( a new subnet's emission mechanism). Arguments: - wallet (Wallet): The wallet used to sign the extrinsic (must be unlocked). - netuid (int): The UID of the target subnet for which the call is being initiated. - wait_for_inclusion (bool, optional): Whether to wait for the extrinsic to be included in a block. - Defaults to `True`. - wait_for_finalization (bool, optional): Whether to wait for finalization of the extrinsic. - Defaults to `False`. - period (Optional[int]): The number of blocks during which the transaction will remain valid after it's - submitted. If the transaction is not included in a block within that number of blocks, it will expire - and be rejected. You can think of it as an expiration date for the transaction. + wallet: The wallet used to sign the extrinsic (must be unlocked). + netuid: The UID of the target subnet for which the call is being initiated. + wait_for_inclusion: Whether to wait for the extrinsic to be included in a block. Defaults to `True`. + wait_for_finalization: Whether to wait for finalization of the extrinsic. Defaults to `False`. + period: The number of blocks during which the transaction will remain valid after it's submitted. If the + transaction is not included in a block within that number of blocks, it will expire and be rejected. You + can think of it as an expiration date for the transaction. Returns: Tuple[bool, str]: @@ -5252,28 +5232,28 @@ async def swap_stake( Like subnet hopping - same owner, same hotkey, just changing which subnet the stake is in. Arguments: - wallet (bittensor.wallet): The wallet to swap stake from. - hotkey_ss58 (str): The SS58 address of the hotkey whose stake is being swapped. - origin_netuid (int): The netuid from which stake is removed. - destination_netuid (int): The netuid to which stake is added. - amount (Union[Balance, float]): The amount to swap. - wait_for_inclusion (bool): Waits for the transaction to be included in a block. - wait_for_finalization (bool): Waits for the transaction to be finalized on the blockchain. - safe_staking (bool): If true, enables price safety checks to protect against fluctuating prices. The swap + wallet: The wallet to swap stake from. + hotkey_ss58: The SS58 address of the hotkey whose stake is being swapped. + origin_netuid: The netuid from which stake is removed. + destination_netuid: The netuid to which stake is added. + amount: The amount to swap. + wait_for_inclusion: Waits for the transaction to be included in a block. + wait_for_finalization: Waits for the transaction to be finalized on the blockchain. + safe_staking: If true, enables price safety checks to protect against fluctuating prices. The swap will only execute if the price ratio between subnets doesn't exceed the rate tolerance. Default is False. - allow_partial_stake (bool): If true and safe_staking is enabled, allows partial stake swaps when + allow_partial_stake: If true and safe_staking is enabled, allows partial stake swaps when the full amount would exceed the price threshold. If false, the entire swap fails if it would exceed the threshold. Default is False. - rate_tolerance (float): The maximum allowed increase in the price ratio between subnets + rate_tolerance: The maximum allowed increase in the price ratio between subnets (origin_price/destination_price). For example, 0.005 = 0.5% maximum increase. Only used when safe_staking is True. Default is 0.005. - period (Optional[int]): The number of blocks during which the transaction will remain valid after it's + period: The number of blocks during which the transaction will remain valid after it's submitted. If the transaction is not included in a block within that number of blocks, it will expire and be rejected. You can think of it as an expiration date for the transaction. Returns: - success (bool): True if the extrinsic was successful. + success: True if the extrinsic was successful. The price ratio for swap_stake in safe mode is calculated as: origin_subnet_price / destination_subnet_price When safe_staking is enabled, the swap will only execute if: @@ -5351,15 +5331,14 @@ async def transfer( Transfer token of amount to destination. Arguments: - wallet (bittensor_wallet.Wallet): Source wallet for the transfer. - dest (str): Destination address for the transfer. - amount (float): Number of tokens to transfer. - transfer_all (bool): Flag to transfer all tokens. Default is ``False``. - wait_for_inclusion (bool): Waits for the transaction to be included in a block. Default is ``True``. - wait_for_finalization (bool): Waits for the transaction to be finalized on the blockchain. Default is - ``False``. - keep_alive (bool): Flag to keep the connection alive. Default is ``True``. - period (Optional[int]): The number of blocks during which the transaction will remain valid after it's + wallet: Source wallet for the transfer. + des: Destination address for the transfer. + amount: Number of tokens to transfer. + transfer_all: Flag to transfer all tokens. Default is `False`. + wait_for_inclusion: Waits for the transaction to be included in a block. Default isr_finalization (bool): Waits for the transaction to be finalized on the blockchain. Default is + `False`. + keep_alive: Flag to keep the connection alive. Default is `True`. + period: The number of blocks during which the transaction will remain valid after it's submitted. If the transaction is not included in a block within that number of blocks, it will expire and be rejected. You can think of it as an expiration date for the transaction. Returns: @@ -5394,20 +5373,20 @@ async def transfer_stake( Transfers stake from one subnet to another while changing the coldkey owner. Arguments: - wallet (bittensor.wallet): The wallet to transfer stake from. + wallet: The wallet to transfer stake from. destination_coldkey_ss58 (str): The destination coldkey SS58 address. - hotkey_ss58 (str): The hotkey SS58 address associated with the stake. - origin_netuid (int): The source subnet UID. - destination_netuid (int): The destination subnet UID. - amount (Balance): Amount to transfer. - wait_for_inclusion (bool): If true, waits for inclusion before returning. - wait_for_finalization (bool): If true, waits for finalization before returning. - period (Optional[int]): The number of blocks during which the transaction will remain valid after it's + hotkey_ss58: The hotkey SS58 address associated with the stake. + origin_netuid: The source subnet UID. + destination_netuid: The destination subnet UID. + amount: Amount to transfer. + wait_for_inclusion: If true, waits for inclusion before returning. + wait_for_finalization: If true, waits for finalization before returning. + period: The number of blocks during which the transaction will remain valid after it's submitted. If the transaction is not included in a block within that number of blocks, it will expire and be rejected. You can think of it as an expiration date for the transaction. Returns: - success (bool): True if the transfer was successful. + success: True if the transfer was successful. """ amount = check_and_convert_to_balance(amount) return await transfer_stake_extrinsic( @@ -5442,27 +5421,26 @@ async def unstake( individual neuron stakes within the Bittensor network. Arguments: - wallet (bittensor_wallet.wallet): The wallet associated with the neuron from which the stake is being + wallet: The wallet associated with the neuron from which the stake is being removed. - hotkey_ss58 (Optional[str]): The ``SS58`` address of the hotkey account to unstake from. - netuid (Optional[int]): The unique identifier of the subnet. - amount (Balance): The amount of alpha to unstake. If not specified, unstakes all. - wait_for_inclusion (bool): Waits for the transaction to be included in a block. - wait_for_finalization (bool): Waits for the transaction to be finalized on the blockchain. - safe_staking (bool): If true, enables price safety checks to protect against fluctuating prices. The unstake + hotkey_ss58: The `SS58` address of the hotkey account to unstake from. + netuid: The unique identifier of the subnet. + amount: The amount of alpha to unstake. If not specified, unstakes all. + wait_for_inclusion: Waits for the transaction to be included inr_finalization (bool): Waits for the transaction to be finalized on the blockchain. + safe_staking: If true, enables price safety checks to protect against fluctuating prices. The unstake will only execute if the price change doesn't exceed the rate tolerance. Default is False. - allow_partial_stake (bool): If true and safe_staking is enabled, allows partial unstaking when + allow_partial_stake: If true and safe_staking is enabled, allows partial unstaking when the full amount would exceed the price threshold. If false, the entire unstake fails if it would exceed the threshold. Default is False. - rate_tolerance (float): The maximum allowed price change ratio when unstaking. For example, + rate_tolerance: The maximum allowed price change ratio when unstaking. For example, 0.005 = 0.5% maximum price decrease. Only used when safe_staking is True. Default is 0.005. - period (Optional[int]): The number of blocks during which the transaction will remain valid after it's + period: The number of blocks during which the transaction will remain valid after it's submitted. If the transaction is not included in a block within that number of blocks, it will expire and be rejected. You can think of it as an expiration date for the transaction. unstake_all: If `True`, unstakes all tokens and `amount` is ignored. Default is `False` Returns: - bool: ``True`` if the unstaking process is successful, False otherwise. + bool: `True` if the unstaking process is successful, False otherwise. This function supports flexible stake management, allowing neurons to adjust their network participation and potential reward accruals. @@ -5579,28 +5557,27 @@ async def unstake_multiple( unstake_all: bool = False, ) -> bool: """ - Performs batch unstaking from multiple hotkey accounts, allowing a neuron to reduce its staked amounts - efficiently. This function is useful for managing the distribution of stakes across multiple neurons. - - Arguments: - wallet (bittensor_wallet.Wallet): The wallet linked to the coldkey from which the stakes are being - withdrawn. - hotkey_ss58s (List[str]): A list of hotkey ``SS58`` addresses to unstake from. - netuids (list[int]): Subnets unique IDs. - amounts (List[Union[Balance, float]]): The amounts of TAO to unstake from each hotkey. If not provided, - unstakes all available stakes. - wait_for_inclusion (bool): Waits for the transaction to be included in a block. - wait_for_finalization (bool): Waits for the transaction to be finalized on the blockchain. - period (Optional[int]): The number of blocks during which the transaction will remain valid after it's - submitted. If the transaction is not included in a block within that number of blocks, it will expire - and be rejected. You can think of it as an expiration date for the transaction. - unstake_all: If true, unstakes all tokens. Default is ``False``. If `True` amounts are ignored. - - Returns: - bool: ``True`` if the batch unstaking is successful, False otherwise. - - This function allows for strategic reallocation or withdrawal of stakes, aligning with the dynamic stake - management aspect of the Bittensor network. + Performs batch unstaking from multiple hotkey accounts, allowing a neuron to reduce its staked amounts + efficiently. This function is useful for managing the distribution of stakes across multiple neurons. + + Arguments: + wallet: The wallet linked to the coldkey from which the stakes are being + withdrawn. + s (List[str]): A list of hotkey `SS58` addresses to unstake from. + netuidst]): Subnets unique IDs. + amounts (List[Union[Balance, float]]): The amounts of TAO to unstake from each hotkey. If not provided, + unstakes all_inclusion (bool): Waits for the transaction to be included in a block. + wait_for_finalization: Waits for the transaction to be finalized on the blockchain. + period: The number of blocks during which the transaction will remain valid after it's + submitted. If the transaction is not included in a block within that number of blocks, it will expire + and be rejected. You can think of it as an expiration date for the transaction. + unstake_all: If true, unstakes all tokens. Default is `False`. If `True` amounts are ignored. + + Returns: + bool: `True` if the batch unstaking is successful, False otherwise. + + This function allows for strategic reallocation or withdrawal of stakes, aligning with the dynamic stake + management aspect of the Bittensor network. """ return await unstake_multiple_extrinsic( subtensor=self, From 5ba0adf67ca338877e0f0428f552a2dd0912d720 Mon Sep 17 00:00:00 2001 From: michael trestman Date: Tue, 8 Jul 2025 19:09:35 -0700 Subject: [PATCH 15/21] edit docstrings --- bittensor/core/async_subtensor.py | 53 +++++++++++++++++++------------ 1 file changed, 32 insertions(+), 21 deletions(-) diff --git a/bittensor/core/async_subtensor.py b/bittensor/core/async_subtensor.py index f7e6c34d95..229edb0a4c 100644 --- a/bittensor/core/async_subtensor.py +++ b/bittensor/core/async_subtensor.py @@ -232,7 +232,8 @@ async def close(self): async def initialize(self): """Initializes the connection to the blockchain. - This method establishes the connection to the Bittensor blockchain and should be called after creating an AsyncSubtensor instance before making any queries. + This method establishes the connection to the Bittensor blockchain and should be called after creating an + AsyncSubtensor instance before making any queries. Returns: AsyncSubtensor: The initialized instance (self) for method chaining. @@ -302,7 +303,8 @@ async def determine_block_hash( ) -> Optional[str]: """Determine the appropriate block hash based on the provided parameters. - Ensures that only one of the block specification parameters is used and returns the appropriate block hash for blockchain queries. + Ensures that only one of the block specification parameters is used and returns the appropriate block hash + for blockchain queries. Arguments: block: The block number to get the hash for. Do not specify if using block_hash or reuse_block. @@ -345,11 +347,14 @@ async def encode_params( ) -> str: """Encodes parameters into a hex string using their type definitions. - This method takes a call definition (which specifies parameter types) and actual parameter values, then encodes them into a hex string that can be used for blockchain transactions. + This method takes a call definition (which specifies parameter types) and actual parameter values, then + encodes them into a hex string that can be used for blockchain transactions. Arguments: - call_definition: A dictionary containing parameter type definitions. Should have a "params" key with a list of parameter definitions. - params: The actual parameter values to encode. Can be either a list (for positional parameters) or a dictionary (for named parameters). + call_definition: A dictionary containing parameter type definitions. Should have a "params" key with a + list of parameter definitions. + params: The actual parameter values to encode. Can be either a list (for positional parameters) or a + dictionary (for named parameters). Returns: str: A hex-encoded string representation of the parameters. @@ -401,13 +406,14 @@ async def get_hyperparameter( ) -> Optional[Any]: """Retrieves a specified hyperparameter for a specific subnet. - This method queries the blockchain for subnet-specific hyperparameters such as difficulty, tempo, immunity period, and other network configuration values. + This method queries the blockchain for subnet-specific hyperparameters such as difficulty, tempo, immunity + period, and other network configuration values. Arguments: param_name: The name of the hyperparameter to retrieve (e.g., "Difficulty", "Tempo", "ImmunityPeriod"). netuid: The unique identifier of the subnet. block: The block number at which to retrieve the hyperparameter. Do not specify if using block_hash or - reuse_block. + reuse_block. block_hash: The hash of the blockchain block for the query. Do not specify if using block or reuse_block. reuse_block: Whether to reuse the last-used block hash. Do not set if using block_hash or block. @@ -3017,19 +3023,22 @@ async def get_transfer_fee( ) -> Balance: """ Calculates the transaction fee for transferring tokens from a wallet to a specified destination address. This - function simulates the transfer to estimate the associated cost, taking into account the current network - conditions and transaction complexity. + function simulates the transfer to estimate the associated cost, taking into account the current network + conditions and transaction complexity. Arguments: wallet: The wallet from which the transfer is initiated. - des: The `SS58` address of the destination account. - valuer.utils.balance.Balance, float, int]): The amount of tokens to be transferred, - specified as a Balance object, or in Tao (float) or Rao (int) unit bittensor.utils.balance.Balance: The estimated transaction fee for the transfer, represented as a Balance + dest: The `SS58` address of the destination account. + value: The amount of tokens to be transferred, specified as a Balance object, or in Tao (float) or Rao + (int) units. + + Returns: + bittensor.utils.balance.Balance: The estimated transaction fee for the transfer, represented as a Balance object. - Estimating the transfer fee is essential for planning and executing token transactions, ensuring that the wallet - has sufficient funds to cover both the transfer amount and the associated costs. This function provides a - crucial tool for managing financial operations within the Bittensor network. + Estimating the transfer fee is essential for planning and executing token transactions, ensuring that the + wallet has sufficient funds to cover both the transfer amount and the associated costs. This function provides + a crucial tool for managing financial operations within the Bittensor network. """ value = check_and_convert_to_balance(value) @@ -4250,7 +4259,8 @@ async def add_stake_multiple( hotkey_ss58s: List of `SS58` addresses of hotkeys to stake to. netui: list of subnet UIDs amounts: Corresponding amounts of TAO to stake for each hotkey. - wait_for_inclusion: Waits for the transaction to be included inor_finalization (bool): Waits for the transaction to be finalized on the blockchain. + wait_for_inclusion: Waits for the transaction to be included in a block. Defaults to `True`. + wait_for_finalization: Waits for the transaction to be finalized on the blockchain. Defaults to `False`. Returns: bool: `True` if the staking is successful for all specified neurons, False otherwise. @@ -5039,8 +5049,8 @@ async def set_weights( wallet: The wallet associated with the subnet validator setting the weights. netuid: The unique identifier of the subnet. uids: The list of subnet miner neuron UIDs that the weights are being set for. - weights: The corresponding weights to be set for each UID, representing the validator's evaluation of each miner's performance. - UID, representing the validator's evaluation of each miner's performance. + weights: The corresponding weights to be set for each UID, representing the validator's evaluation of each + miner's performance. version_key: Version key for compatibility with the network. Default is int representation of the Bittensor version. wait_for_inclusion: Waits for the transaction to be included in a block. Default is `False`. @@ -5335,8 +5345,8 @@ async def transfer( des: Destination address for the transfer. amount: Number of tokens to transfer. transfer_all: Flag to transfer all tokens. Default is `False`. - wait_for_inclusion: Waits for the transaction to be included in a block. Default isr_finalization (bool): Waits for the transaction to be finalized on the blockchain. Default is - `False`. + wait_for_inclusion: Waits for the transaction to be included in a block. Defaults to `True`. + wait_for_finalization: Waits for the transaction to be finalized on the blockchain. Defaults to `False`. keep_alive: Flag to keep the connection alive. Default is `True`. period: The number of blocks during which the transaction will remain valid after it's submitted. If the transaction is not included in a block within that number of blocks, it will expire @@ -5426,7 +5436,8 @@ async def unstake( hotkey_ss58: The `SS58` address of the hotkey account to unstake from. netuid: The unique identifier of the subnet. amount: The amount of alpha to unstake. If not specified, unstakes all. - wait_for_inclusion: Waits for the transaction to be included inr_finalization (bool): Waits for the transaction to be finalized on the blockchain. + wait_for_inclusion: Waits for the transaction to be included in a block. Defaults to `True`. + wait_for_finalization: Waits for the transaction to be finalized on the blockchain. Defaults to `False`. safe_staking: If true, enables price safety checks to protect against fluctuating prices. The unstake will only execute if the price change doesn't exceed the rate tolerance. Default is False. allow_partial_stake: If true and safe_staking is enabled, allows partial unstaking when From 3e7cc71b5f614920b4818f95aa72649cbe0d3833 Mon Sep 17 00:00:00 2001 From: michael trestman Date: Tue, 8 Jul 2025 19:55:19 -0700 Subject: [PATCH 16/21] edit docstrings --- bittensor/core/async_subtensor.py | 60 +++++++++++++++---------------- 1 file changed, 30 insertions(+), 30 deletions(-) diff --git a/bittensor/core/async_subtensor.py b/bittensor/core/async_subtensor.py index 229edb0a4c..1d52b8af92 100644 --- a/bittensor/core/async_subtensor.py +++ b/bittensor/core/async_subtensor.py @@ -1573,7 +1573,7 @@ async def get_revealed_commitment_by_hotkey( Arguments: netuid: The unique identifier of the subnetwork. block: The block number to retrieve the commitment from. Default is `None`. - hotkey_ss58_address (str): The ss58 address of the committee member. + hotkey_ss58_address: The ss58 address of the committee member. block_hash: The hash of the block to retrieve the subnet unique identifiers from. reuse_block: Whether to reuse the last-used block hash. @@ -1855,7 +1855,7 @@ async def get_delegates( Arguments: block: The blockchain block number for the query. - block_hash (Optional[str]): hash of the blockchain block number for the query. + block_hash: hash of the blockchain block number for the query. reuse_block (Optional[bool]): whether to reuse the last-used block hash. Returns: @@ -1887,7 +1887,7 @@ async def get_existential_deposit( Arguments: block: The blockchain block number for the query. - block_hash (str): Block hash at which to query the deposit amount. If `None`, the current block is used. + block_hash: Block hash at which to query the deposit amount. If `None`, the current block is used. reuse_block: Whether to reuse the last-used blockchain block hash. Returns: @@ -1923,10 +1923,10 @@ async def get_hotkey_owner( specified block hash, it returns None. Arguments: - hotkey_ss58 (str): The SS58 address of the hotkey. - block (Optional[int]): The blockchain block number for the query. - block_hash (Optional[str]): The hash of the block at which to check the hotkey ownership. - reuse_block (bool): Whether to reuse the last-used blockchain hash. + hotkey_ss58: The SS58 address of the hotkey. + block: The blockchain block number for the query. + block_hash: The hash of the block at which to check the hotkey ownership. + reuse_block: Whether to reuse the last-used blockchain hash. Returns: Optional[str]: The SS58 address of the owner if the hotkey exists, or None if it doesn't. @@ -2059,9 +2059,9 @@ async def get_all_metagraphs_info( Arguments: block: the block number at which to retrieve the hyperparameter. Do not specify if using block_hash or reuse_block - block_hash (Optional[str]): The hash of blockchain block number for the query. Do not specify if using + block_hash: The hash of blockchain block number for the query. Do not specify if using block or reuse_block - reuse_block (bool): Whether to reuse the last-used block hash. Do not set if using block_hash or block. + reuse_block: Whether to reuse the last-used block hash. Do not set if using block_hash or block. Returns: MetagraphInfo dataclass @@ -2093,7 +2093,7 @@ async def get_netuids_for_hotkey( Arguments: hotkey_ss58: The `SS58` address of the neuron's hotkey. block: The blockchain block number for the query. - block_hash (Optional[str]): The hash of the blockchain block number at which to perform the query. + block_hash: The hash of the blockchain block number at which to perform the query. reuse_block (Optional[bool]): Whether to reuse the last-used block hash when retrieving info. Returns: @@ -2490,10 +2490,10 @@ async def get_stake( hotkey_ss58: The SS58 address of the hotkey. coldkey_ss58 (str): The SS58 address of the coldkey. netuid: The subnet ID. - block (Optional[int]): The block number at which to query the stake information. - block_hash (Optional[str]): The hash of the block to retrieve the stake from. Do not specify if using block + block: The block number at which to query the stake information. + block_hash: The hash of the block to retrieve the stake from. Do not specify if using block or reuse_block - reuse_block (bool): Whether to use the last-used block. Do not set if using block_hash or block. + reuse_block: Whether to use the last-used block. Do not set if using block_hash or block. Returns: Balance: The stake under the coldkey - hotkey pairing. @@ -2579,9 +2579,9 @@ async def get_subnet_info( Arguments: netuid: The unique identifier of the subnet. block: The blockchain block number for the query. - block_hash (Optional[str]): The hash of the block to retrieve the stake from. Do not specify if using block + block_hash: The hash of the block to retrieve the stake from. Do not specify if using block or reuse_block - reuse_block (bool): Whether to use the last-used block. Do not set if using block_hash or block. + reuse_block: Whether to use the last-used block. Do not set if using block_hash or block. Returns: SubnetInfo: A SubnetInfo objects, each containing detailed information about a subnet. @@ -2613,9 +2613,9 @@ async def get_subnet_price( Arguments: netuid: The unique identifier of the subnet. block: The blockchain block number for the query. - block_hash (Optional[str]): The hash of the block to retrieve the stake from. Do not specify if using block + block_hash: The hash of the block to retrieve the stake from. Do not specify if using block or reuse_block - reuse_block (bool): Whether to use the last-used block. Do not set if using block_hash or block. + reuse_block: Whether to use the last-used block. Do not set if using block_hash or block. Returns: The current Alpha price in TAO units for the specified subnet. @@ -2648,9 +2648,9 @@ async def get_subnet_prices( Args: block: The blockchain block number for the query. - block_hash (Optional[str]): The hash of the block to retrieve the stake from. Do not specify if using block + block_hash: The hash of the block to retrieve the stake from. Do not specify if using block or reuse_block - reuse_block (bool): Whether to use the last-used block. Do not set if using block_hash or block. + reuse_block: Whether to use the last-used block. Do not set if using block_hash or block. Returns: dict: @@ -2771,10 +2771,10 @@ async def get_stake_for_coldkey_and_hotkey( coldkey_ss58 (str): The SS58 address of the coldkey. hotkey_ss58: The SS58 address of the hotkey. netuids (Optional[list[int]]): The subnet IDs to query for. Set to `None` for all subnets. - block (Optional[int]): The block number at which to query the stake information. - block_hash (Optional[str]): The hash of the block to retrieve the stake from. Do not specify if using block + block: The block number at which to query the stake information. + block_hash: The hash of the block to retrieve the stake from. Do not specify if using block or reuse_block - reuse_block (bool): Whether to use the last-used block. Do not set if using block_hash or block. + reuse_block: Whether to use the last-used block. Do not set if using block_hash or block. Returns: A {netuid: StakeInfo} pairing of all stakes across all subnets. @@ -2816,7 +2816,7 @@ async def get_stake_for_coldkey( Arguments: coldkey_ss58 (str): The SS58 address of the coldkey. - block (Optional[int]): The block number at which to query the stake information. + block: The block number at which to query the stake information. block_hash: The hash of the blockchain block number for the query. reuse_block: Whether to reuse the last-used block hash. @@ -3072,7 +3072,7 @@ async def get_vote_data( Arguments: proposal_hash (str): The hash of the proposal for which voting data is requested. block: The blockchain block number for the query. - block_hash (Optional[str]): The hash of the blockchain block number to query the voting data. + block_hash: The hash of the blockchain block number to query the voting data. reuse_block: Whether to reuse the last-used blockchain block hash. Returns: @@ -3110,7 +3110,7 @@ async def get_uid_for_hotkey_on_subnet( hotkey_ss58: The `SS58` address of the neuron's hotkey. netuid: The unique identifier of the subnet. block: The blockchain block number for the query. - block_hash (Optional[str]): The blockchain block_hash representation of the block id. + block_hash: The blockchain block_hash representation of the block id. reuse_block: Whether to reuse the last-used blockchain block hash. Returns: @@ -3146,8 +3146,8 @@ async def filter_netuids_by_registered_hotkeys( filter_for_netuids (Iterable[int]): A subset of all_netuids to filter from the main list. all_hotkeys (Iterable[Wallet]): Hotkeys to filter from the main list. block: The blockchain block number for the query. - block_hash (str): hash of the blockchain block number at which to perform the query. - reuse_block (bool): whether to reuse the last-used blockchain hash when retrieving info. + block_hash: hash of the blockchain block number at which to perform the query. + reuse_block: whether to reuse the last-used blockchain hash when retrieving info. Returns: The filtered list of netuids. @@ -3201,7 +3201,7 @@ async def immunity_period( Arguments: netuid: The unique identifier of the subnet. block: The blockchain block number for the query. - block_hash (Optional[str]): The blockchain block_hash representation of the block id. + block_hash: The blockchain block_hash representation of the block id. reuse_block: Whether to reuse the last-used blockchain block hash. Returns: @@ -3962,7 +3962,7 @@ async def weights_rate_limit( Arguments: netuid: The unique identifier of the subnetwork. block: The blockchain block number for the query. - block_hash (Optional[str]): The blockchain block_hash representation of the block id. + block_hash: The blockchain block_hash representation of the block id. reuse_block: Whether to reuse the last-used blockchain block hash. Returns: @@ -4779,7 +4779,7 @@ async def root_register( Arguments: wallet (bittensor_wallet.Wallet): Bittensor wallet instance. - block_hash (Optional[str]): This argument will be removed in Bittensor v10 + block_hash: This argument will be removed in Bittensor v10 wait_for_inclusion (bool): Waits for the transaction to be included in a block. Default is ``False``. wait_for_finalization (bool): Waits for the transaction to be finalized on the blockchain. Default is ``False``. From b78498c177a48209761a1cddfd92edd8ca335ca5 Mon Sep 17 00:00:00 2001 From: michael trestman Date: Wed, 9 Jul 2025 06:28:32 -0700 Subject: [PATCH 17/21] edit docstrings --- bittensor/core/async_subtensor.py | 56 +++++++++++++++---------------- 1 file changed, 28 insertions(+), 28 deletions(-) diff --git a/bittensor/core/async_subtensor.py b/bittensor/core/async_subtensor.py index 1d52b8af92..ebc1811714 100644 --- a/bittensor/core/async_subtensor.py +++ b/bittensor/core/async_subtensor.py @@ -1856,7 +1856,7 @@ async def get_delegates( Arguments: block: The blockchain block number for the query. block_hash: hash of the blockchain block number for the query. - reuse_block (Optional[bool]): whether to reuse the last-used block hash. + reuse_block: whether to reuse the last-used block hash. Returns: List of DelegateInfo objects, or an empty list if there are no delegates. @@ -2094,7 +2094,7 @@ async def get_netuids_for_hotkey( hotkey_ss58: The `SS58` address of the neuron's hotkey. block: The blockchain block number for the query. block_hash: The hash of the blockchain block number at which to perform the query. - reuse_block (Optional[bool]): Whether to reuse the last-used block hash when retrieving info. + reuse_block: Whether to reuse the last-used block hash when retrieving info. Returns: A list of netuids where the neuron is a member. @@ -2455,8 +2455,8 @@ async def get_owned_hotkeys( Retrieves all hotkeys owned by a specific coldkey address. Arguments: - coldkey_ss58 (str): The SS58 address of the coldkey to query. - block (int): The blockchain block number for the query. + coldkey_ss58: The SS58 address of the coldkey to query. + block: The blockchain block number for the query. block_hash: The hash of the blockchain block number for the query. reuse_block: Whether to reuse the last-used blockchain block hash. @@ -2488,7 +2488,7 @@ async def get_stake( Arguments: hotkey_ss58: The SS58 address of the hotkey. - coldkey_ss58 (str): The SS58 address of the coldkey. + coldkey_ss58: The SS58 address of the coldkey. netuid: The subnet ID. block: The block number at which to query the stake information. block_hash: The hash of the block to retrieve the stake from. Do not specify if using block @@ -2646,7 +2646,7 @@ async def get_subnet_prices( ) -> dict[int, Balance]: """Gets the current Alpha price in TAO for a specified subnet. - Args: + Argsuments: block: The blockchain block number for the query. block_hash: The hash of the block to retrieve the stake from. Do not specify if using block or reuse_block @@ -2768,9 +2768,9 @@ async def get_stake_for_coldkey_and_hotkey( Retrieves all coldkey-hotkey pairing stake across specified (or all) subnets Arguments: - coldkey_ss58 (str): The SS58 address of the coldkey. + coldkey_ss58: The SS58 address of the coldkey. hotkey_ss58: The SS58 address of the hotkey. - netuids (Optional[list[int]]): The subnet IDs to query for. Set to `None` for all subnets. + netuids: The subnet IDs to query for. Set to `None` for all subnets. block: The block number at which to query the stake information. block_hash: The hash of the block to retrieve the stake from. Do not specify if using block or reuse_block @@ -2815,7 +2815,7 @@ async def get_stake_for_coldkey( Retrieves the stake information for a given coldkey. Arguments: - coldkey_ss58 (str): The SS58 address of the coldkey. + coldkey_ss58: The SS58 address of the coldkey. block: The block number at which to query the stake information. block_hash: The hash of the blockchain block number for the query. reuse_block: Whether to reuse the last-used block hash. @@ -2923,7 +2923,7 @@ async def get_subnet_hyperparameters( netuid: The network UID of the subnet to query. block: The blockchain block number for the query. block_hash: The hash of the blockchain block number for the query. - reuse_blocko reuse the last-used blockchain hash. + reuse_block: Whether to reuse the last-used blockchain hash. Returns: The subnet's hyperparameters, or `None` if not available. @@ -3070,7 +3070,7 @@ async def get_vote_data( about how senate members have voted on the proposal. Arguments: - proposal_hash (str): The hash of the proposal for which voting data is requested. + proposal_hash: The hash of the proposal for which voting data is requested. block: The blockchain block number for the query. block_hash: The hash of the blockchain block number to query the voting data. reuse_block: Whether to reuse the last-used blockchain block hash. @@ -3142,9 +3142,9 @@ async def filter_netuids_by_registered_hotkeys( Filters a given list of all netuids for certain specified netuids and hotkeys Arguments: - all_netuids (Iterable[int]): A list of netuids to filter. - filter_for_netuids (Iterable[int]): A subset of all_netuids to filter from the main list. - all_hotkeys (Iterable[Wallet]): Hotkeys to filter from the main list. + all_netuids: A list of netuids to filter. + filter_for_netuids: A subset of all_netuids to filter from the main list. + all_hotkeys: Hotkeys to filter from the main list. block: The blockchain block number for the query. block_hash: hash of the blockchain block number at which to perform the query. reuse_block: whether to reuse the last-used blockchain hash when retrieving info. @@ -3241,7 +3241,7 @@ async def is_hotkey_delegate( hotkey_ss58: The SS58 address of the neuron's hotkey. block: The blockchain block number for the query. block_hash: The hash of the blockchain block number for the query. - reuse_block (Optional[bool]): Whether to reuse the last-used block hash. + reuse_block: Whether to reuse the last-used block hash. Returns: `True` if the hotkey is a delegate, `False` otherwise. @@ -3926,7 +3926,7 @@ async def weights( netuid: The network UID of the subnet to query. block: Block number for synchronization, or `None` for the latest block. block_hash: The hash of the blockchain block for the query. - reuse_blocko reuse the last-used blockchain block hash. + reuse_block: reuse the last-used blockchain block hash. Returns: A list of tuples mapping each neuron's UID to its assigned weights. @@ -4778,12 +4778,12 @@ async def root_register( Register neuron by recycling some TAO. Arguments: - wallet (bittensor_wallet.Wallet): Bittensor wallet instance. + wallet: Bittensor wallet instance. block_hash: This argument will be removed in Bittensor v10 - wait_for_inclusion (bool): Waits for the transaction to be included in a block. Default is ``False``. - wait_for_finalization (bool): Waits for the transaction to be finalized on the blockchain. Default is - ``False``. - period (Optional[int]): The number of blocks during which the transaction will remain valid after it's + wait_for_inclusion: Waits for the transaction to be included in a block. Default is `False`. + wait_for_finalization: Waits for the transaction to be finalized on the blockchain. Default is + `False`. + period: The number of blocks during which the transaction will remain valid after it's submitted. If the transaction is not included in a block within that number of blocks, it will expire and be rejected. You can think of it as an expiration date for the transaction. @@ -4993,7 +4993,7 @@ async def set_subnet_identity( Arguments: wallet: The wallet instance that will authorize the transaction. netuid: The unique ID of the network on which the operation takes place. - subnet_identity (SubnetIdentity): The identity data of the subnet including attributes like name, GitHub + subnet_identity: The identity data of the subnet including attributes like name, GitHub repository, contact, URL, discord, description, and any additional metadata. wait_for_inclusion: Indicates if the function should wait for the transaction to be included in the block. @@ -5163,7 +5163,7 @@ async def serve_axon( Arguments: netuid: The unique identifier of the subnetwork. - axon (bittensor.core.axon.Axon): The Axon instance to be registered for serving. + axon: The Axon instance to be registered for serving. wait_for_inclusion: Waits for the transaction to be included in a block. Default is `False`. wait_for_finalization: Waits for the transaction to be finalized on the blockchain. Default is `True`. @@ -5384,7 +5384,7 @@ async def transfer_stake( Arguments: wallet: The wallet to transfer stake from. - destination_coldkey_ss58 (str): The destination coldkey SS58 address. + destination_coldkey_ss58: The destination coldkey SS58 address. hotkey_ss58: The hotkey SS58 address associated with the stake. origin_netuid: The source subnet UID. destination_netuid: The destination subnet UID. @@ -5574,10 +5574,10 @@ async def unstake_multiple( Arguments: wallet: The wallet linked to the coldkey from which the stakes are being withdrawn. - s (List[str]): A list of hotkey `SS58` addresses to unstake from. - netuidst]): Subnets unique IDs. - amounts (List[Union[Balance, float]]): The amounts of TAO to unstake from each hotkey. If not provided, - unstakes all_inclusion (bool): Waits for the transaction to be included in a block. + hotkey_ss58s: A list of hotkey `SS58` addresses to unstake from. + netuids: Subnets unique IDs. + amounts: The amounts of TAO to unstake from each hotkey. If not provided, unstakes all. + wait_for_inclusion: Waits for the transaction to be included in a block. wait_for_finalization: Waits for the transaction to be finalized on the blockchain. period: The number of blocks during which the transaction will remain valid after it's submitted. If the transaction is not included in a block within that number of blocks, it will expire From dacb11e7654648abc2d9f5748720c5216085649a Mon Sep 17 00:00:00 2001 From: michael trestman Date: Wed, 9 Jul 2025 06:46:24 -0700 Subject: [PATCH 18/21] edit docstrings --- bittensor/core/async_subtensor.py | 96 +++++++++++++++---------------- 1 file changed, 48 insertions(+), 48 deletions(-) diff --git a/bittensor/core/async_subtensor.py b/bittensor/core/async_subtensor.py index ebc1811714..3bef936ae0 100644 --- a/bittensor/core/async_subtensor.py +++ b/bittensor/core/async_subtensor.py @@ -149,19 +149,19 @@ def __init__( """Initializes an AsyncSubtensor instance for blockchain interaction. Arguments: - network: The network name or type to connect to (e.g., "finney", "test"). If `None`, uses the default + network: The network name or type to connect to (e.g., "finney", "test"). If ``None``, uses the default network from config. - config: Configuration object for the AsyncSubtensor instance. If `None`, uses the default configuration. - log_verbose: Enables or disables verbose logging. Defaults to `False`. + config: Configuration object for the AsyncSubtensor instance. If ``None``, uses the default configuration. + log_verbose: Enables or disables verbose logging. Defaults to ``False``. fallback_endpoints: List of fallback endpoints to use if default or provided network is not available. - Defaults to `None`. - retry_forever: Whether to retry forever on connection errors. Defaults to `False`. - _mock: Whether this is a mock instance. Mainly for testing purposes. Defaults to `False`. + Defaults to ``None``. + retry_forever: Whether to retry forever on connection errors. Defaults to ``False``. + _mock: Whether this is a mock instance. Mainly for testing purposes. Defaults to ``False``. archive_endpoints: Similar to fallback_endpoints, but specifically only archive nodes. Will be used in cases where you are requesting a block that is too old for your current (presumably lite) node. - Defaults to `None`. + Defaults to ``None``. websocket_shutdown_timer: Amount of time, in seconds, to wait after the last response from the chain to - close the connection. Defaults to `5.0`. + close the connection. Defaults to ``5.0``. Returns: None @@ -330,7 +330,7 @@ async def determine_block_hash( # Ensure that only one of the parameters is specified. if sum(bool(x) for x in [block, block_hash, reuse_block]) > 1: raise ValueError( - "Only one of `block`, `block_hash`, or `reuse_block` can be specified." + "Only one of ``block``, ``block_hash``, or ``reuse_block`` can be specified." ) # Return the appropriate value. @@ -462,12 +462,12 @@ def _get_substrate( Arguments: fallback_endpoints: List of fallback endpoints to use if default or provided network is not available. - Defaults to `None`. - retry_forever: Whether to retry forever on connection errors. Defaults to `False`. - _mock: Whether this is a mock instance. Mainly for testing purposes. Defaults to `False`. + Defaults to ``None``. + retry_forever: Whether to retry forever on connection errors. Defaults to ``False``. + _mock: Whether this is a mock instance. Mainly for testing purposes. Defaults to ``False``. archive_endpoints: Similar to fallback_endpoints, but specifically only archive nodes. Will be used in cases where you are requesting a block that is too old for your current (presumably lite) node. Defaults - to `None`. + to ``None``. ws_shutdown_timer: Amount of time, in seconds, to wait after the last response from the chain to close the connection. @@ -521,10 +521,10 @@ async def query_constant( reuse_block. block_hash: The hash of the blockchain block at which to query the constant. Do not specify if using block or reuse_block. - reuse_block: Whether to reuse the blockchain block at which to query the constant. Defaults to `False`. + reuse_block: Whether to reuse the blockchain block at which to query the constant. Defaults to ``False``. Returns: - Optional[async_substrate_interface.types.ScaleObj]: The value of the constant if found, `None` otherwise. + Optional[async_substrate_interface.types.ScaleObj]: The value of the constant if found, ``None`` otherwise. Example: # Get existential deposit constant @@ -565,12 +565,12 @@ async def query_map( Arguments: module: The name of the module from which to query the map storage (e.g., "SubtensorModule", "System"). name: The specific storage function within the module to query (e.g., "Bonds", "Weights"). - block: The blockchain block number at which to perform the query. Defaults to `None` (latest block). + block: The blockchain block number at which to perform the query. Defaults to ``None`` (latest block). block_hash: The hash of the block to retrieve the parameter from. Do not specify if using block or reuse_block. reuse_block: Whether to use the last-used block. Do not set if using block_hash or block. Defaults to - `False`. - params: Parameters to be passed to the query. Defaults to `None`. + ``False``. + params: Parameters to be passed to the query. Defaults to ``None``. Returns: AsyncQueryMapResult: A data structure representing the map storage if found, None otherwise. @@ -613,7 +613,7 @@ async def query_map_subtensor( params: A list of parameters to pass to the query function. Returns: - An object containing the map-like data structure, or `None` if not found. + An object containing the map-like data structure, or ``None`` if not found. This function is particularly useful for analyzing and understanding complex network structures and relationships within the Bittensor ecosystem, such as interneuronal connections and stake distributions. @@ -650,7 +650,7 @@ async def query_module( params: A list of parameters to pass to the query function. Returns: - An object containing the requested data if found, `None` otherwise. + An object containing the requested data if found, ``None`` otherwise. This versatile query function is key to accessing a wide range of data and insights from different parts of the Bittensor blockchain, enhancing the understanding and analysis of the network's state and dynamics. @@ -687,7 +687,7 @@ async def query_runtime_api( reuse_block: Whether to reuse the last-used block hash. Do not set if using block_hash or block. Returns: - The decoded result from the runtime API call, or `None` if the call fails. + The decoded result from the runtime API call, or ``None`` if the call fails. This function enables access to the deeper layers of the Bittensor blockchain, allowing for detailed and specific interactions with the network's runtime environment. @@ -856,7 +856,7 @@ async def blocks_since_last_step( return query.value if query is not None and hasattr(query, "value") else query async def blocks_since_last_update(self, netuid: int, uid: int) -> Optional[int]: - """Returns the number of blocks since the last update, or `None` if the subnetwork or UID does not exist. + """Returns the number of blocks since the last update, or ``None`` if the subnetwork or UID does not exist. Arguments: netuid: The unique identifier of the subnetwork. @@ -1267,7 +1267,7 @@ async def get_block_hash(self, block: Optional[int] = None) -> str: the trustworthiness of the blockchain. Arguments: - block: The block number for which the hash is to be retrieved. If `None`, returns the latest block hash. + block: The block number for which the hash is to be retrieved. If ``None``, returns the latest block hash. Returns: str: The cryptographic hash of the specified block. @@ -1572,7 +1572,7 @@ async def get_revealed_commitment_by_hotkey( Arguments: netuid: The unique identifier of the subnetwork. - block: The block number to retrieve the commitment from. Default is `None`. + block: The block number to retrieve the commitment from. Default is ``None``. hotkey_ss58_address: The ss58 address of the committee member. block_hash: The hash of the block to retrieve the subnet unique identifiers from. reuse_block: Whether to reuse the last-used block hash. @@ -1606,7 +1606,7 @@ async def get_revealed_commitment( Arguments: netuid: The unique identifier of the subnetwork. uid: The neuron uid to retrieve the commitment from. - block: The block number to retrieve the commitment from. Default is `None`. + block: The block number to retrieve the commitment from. Default is ``None``. Returns: result (Optional[tuple[int, str]]: A tuple of reveal block and commitment message. @@ -1639,7 +1639,7 @@ async def get_all_revealed_commitments( Arguments: netuid: The unique identifier of the subnetwork. - block: The block number to retrieve the commitment from. Default is `None`. + block: The block number to retrieve the commitment from. Default is ``None``. block_hash: The hash of the block to retrieve the subnet unique identifiers from. reuse_block: Whether to reuse the last-used block hash. @@ -1682,7 +1682,7 @@ async def get_current_weight_commit_info( Arguments: netuid: The unique identifier of the subnet. - block: The blockchain block number for the query. Default is `None`. + block: The blockchain block number for the query. Default is ``None``. block_hash: The hash of the block to retrieve the subnet unique identifiers from. reuse_block: Whether to reuse the last-used block hash. @@ -1714,13 +1714,13 @@ async def get_delegate_by_hotkey( comprehensive view of the delegate's status, including its stakes, nominators, and reward distribution. Arguments: - hotkey_ss58: The `SS58` address of the delegate's hotkey. + hotkey_ss58: The ``SS58`` address of the delegate's hotkey. block: The blockchain block number for the query. block_hash: The hash of the block to retrieve the subnet unique identifiers from. reuse_block: Whether to reuse the last-used block hash. Returns: - Optional[DelegateInfo]: Detailed information about the delegate neuron, `None` if not found. + Optional[DelegateInfo]: Detailed information about the delegate neuron, ``None`` if not found. This function is essential for understanding the roles and influence of delegate neurons within the Bittensor network's consensus and governance structures. @@ -1818,7 +1818,7 @@ async def get_delegated( delegates that a specific account has staked tokens on. Arguments: - coldkey_ss58: The `SS58` address of the account's coldkey. + coldkey_ss58: The ``SS58`` address of the account's coldkey. block: The blockchain block number for the query. block_hash: The hash of the blockchain block number for the query. reuse_block: Whether to reuse the last-used blockchain block hash. @@ -1887,7 +1887,7 @@ async def get_existential_deposit( Arguments: block: The blockchain block number for the query. - block_hash: Block hash at which to query the deposit amount. If `None`, the current block is used. + block_hash: Block hash at which to query the deposit amount. If ``None``, the current block is used. reuse_block: Whether to reuse the last-used blockchain block hash. Returns: @@ -2025,7 +2025,7 @@ async def get_metagraph_info( ] else: raise ValueError( - "`field_indices` must be a list of SelectiveMetagraphIndex enums or ints." + "``field_indices`` must be a list of SelectiveMetagraphIndex enums or ints." ) query = await self.substrate.runtime_call( @@ -2135,7 +2135,7 @@ async def get_neuron_certificate( reuse_block: Whether to use the last-used block. Do not set if using block_hash or block. Returns: - the certificate of the neuron if found, `None` otherwise. + the certificate of the neuron if found, ``None`` otherwise. This function is used for certificate discovery for setting up mutual tls communication between neurons. """ @@ -2372,7 +2372,7 @@ async def get_neuron_for_pubkey_and_subnet( network. Arguments: - hotkey: The `SS58` address of the neuron's hotkey. + hotkey: The ``SS58`` address of the neuron's hotkey. netuid: The unique identifier of the subnet. block: The blockchain block number for the query. block_hash: The blockchain block number at which to perform the query. @@ -2380,7 +2380,7 @@ async def get_neuron_for_pubkey_and_subnet( Returns: Optional[bittensor.core.chain_data.neuron_info.NeuronInfo]: Detailed information about the neuron if found, - `None` otherwise. + ``None`` otherwise. This function is crucial for accessing specific neuron data and understanding its status, stake, and other attributes within a particular subnet of the Bittensor ecosystem. @@ -2414,7 +2414,7 @@ async def get_next_epoch_start_block( """ Calculates the first block number of the next epoch for the given subnet. - If `block` is not provided, the current chain block will be used. Epochs are + If ``block`` is not provided, the current chain block will be used. Epochs are determined based on the subnet's tempo (i.e., blocks per epoch). The result is the block number at which the next epoch will begin. @@ -2770,7 +2770,7 @@ async def get_stake_for_coldkey_and_hotkey( Arguments: coldkey_ss58: The SS58 address of the coldkey. hotkey_ss58: The SS58 address of the hotkey. - netuids: The subnet IDs to query for. Set to `None` for all subnets. + netuids: The subnet IDs to query for. Set to ``None`` for all subnets. block: The block number at which to query the stake information. block_hash: The hash of the block to retrieve the stake from. Do not specify if using block or reuse_block @@ -2821,7 +2821,7 @@ async def get_stake_for_coldkey( reuse_block: Whether to reuse the last-used block hash. Returns: - Optional[list[StakeInfo]]: A list of StakeInfo objects, or `None` if no stake information is found. + Optional[list[StakeInfo]]: A list of StakeInfo objects, or ``None`` if no stake information is found. """ result = await self.query_runtime_api( runtime_api="StakeInfoRuntimeApi", @@ -2926,7 +2926,7 @@ async def get_subnet_hyperparameters( reuse_block: Whether to reuse the last-used blockchain hash. Returns: - The subnet's hyperparameters, or `None` if not available. + The subnet's hyperparameters, or ``None`` if not available. Understanding the hyperparameters is crucial for comprehending how subnets are configured and managed, and how they interact with the network's consensus and incentive mechanisms. @@ -3028,7 +3028,7 @@ async def get_transfer_fee( Arguments: wallet: The wallet from which the transfer is initiated. - dest: The `SS58` address of the destination account. + dest: The ``SS58`` address of the destination account. value: The amount of tokens to be transferred, specified as a Balance object, or in Tao (float) or Rao (int) units. @@ -3076,7 +3076,7 @@ async def get_vote_data( reuse_block: Whether to reuse the last-used blockchain block hash. Returns: - An object containing the proposal's voting data, or `None` if not found. + An object containing the proposal's voting data, or ``None`` if not found. This function is important for tracking and understanding the decision-making processes within the Bittensor network, particularly how proposals are received and acted upon by the governing body. @@ -3114,7 +3114,7 @@ async def get_uid_for_hotkey_on_subnet( reuse_block: Whether to reuse the last-used blockchain block hash. Returns: - Optional[int]: The UID of the neuron if it is registered on the subnet, `None` otherwise. + Optional[int]: The UID of the neuron if it is registered on the subnet, ``None`` otherwise. The UID is a critical identifier within the network, linking the neuron's hotkey to its operational and governance activities on a particular subnet. @@ -3205,7 +3205,7 @@ async def immunity_period( reuse_block: Whether to reuse the last-used blockchain block hash. Returns: - Optional[int]: The value of the 'ImmunityPeriod' hyperparameter if the subnet exists, `None` otherwise. + Optional[int]: The value of the 'ImmunityPeriod' hyperparameter if the subnet exists, ``None`` otherwise. The 'ImmunityPeriod' is a critical aspect of the network's governance system, ensuring that new participants have a grace period to establish themselves and contribute to the network without facing immediate @@ -3244,7 +3244,7 @@ async def is_hotkey_delegate( reuse_block: Whether to reuse the last-used block hash. Returns: - `True` if the hotkey is a delegate, `False` otherwise. + ``True`` if the hotkey is a delegate, ``False`` otherwise. Being a delegate is a significant status within the Bittensor network, indicating a neuron's involvement in consensus and governance processes. @@ -3271,7 +3271,7 @@ async def is_hotkey_registered( Arguments: hotkey_ss58: The SS58 address of the neuron's hotkey. - netuid: The unique identifier of the subnet to check the registration. If `None`, the + netuid: The unique identifier of the subnet to check the registration. If ``None``, the registration is checked across all subnets. block: The blockchain block number at which to perform the query. block_hash: The blockchain block_hash representation of the block id. Do not specify if using block or @@ -3280,8 +3280,8 @@ async def is_hotkey_registered( reuse_block. Returns: - bool: `True` if the hotkey is registered in the specified context (either any subnet or a specific subnet), - `False` otherwise. + bool: ``True`` if the hotkey is registered in the specified context (either any subnet or a specific subnet), + ``False`` otherwise. This function is important for verifying the active status of neurons in the Bittensor network. It aids in understanding whether a neuron is eligible to participate in network processes such as consensus, @@ -3313,7 +3313,7 @@ async def is_hotkey_registered_any( reuse_block: Whether to reuse the last-used block hash. Returns: - bool: `True` if the hotkey is registered on any subnet, False otherwise. + bool: ``True`` if the hotkey is registered on any subnet, False otherwise. This function is essential for determining the network-wide presence and participation of a neuron. """ From c6d08c9fb6b9b158fcd89d07f6f22871b4eda312 Mon Sep 17 00:00:00 2001 From: michael trestman Date: Wed, 9 Jul 2025 06:55:07 -0700 Subject: [PATCH 19/21] edit docstrings --- bittensor/core/async_subtensor.py | 110 +++++++++++++++--------------- 1 file changed, 55 insertions(+), 55 deletions(-) diff --git a/bittensor/core/async_subtensor.py b/bittensor/core/async_subtensor.py index 3bef936ae0..20dda8f788 100644 --- a/bittensor/core/async_subtensor.py +++ b/bittensor/core/async_subtensor.py @@ -1785,7 +1785,7 @@ async def get_delegate_take( percentage of rewards that the delegate claims from its nominators' stakes. Arguments: - hotkey_ss58: The `SS58` address of the neuron's hotkey. + hotkey_ss58: The ``SS58`` address of the neuron's hotkey. block: The blockchain block number for the query. block_hash: The hash of the block to retrieve the subnet unique identifiers from. reuse_block: Whether to reuse the last-used block hash. @@ -2091,7 +2091,7 @@ async def get_netuids_for_hotkey( specific subnets within the Bittensor network where the neuron associated with the hotkey is active. Arguments: - hotkey_ss58: The `SS58` address of the neuron's hotkey. + hotkey_ss58: The ``SS58`` address of the neuron's hotkey. block: The blockchain block number for the query. block_hash: The hash of the blockchain block number at which to perform the query. reuse_block: Whether to reuse the last-used block hash when retrieving info. @@ -3107,7 +3107,7 @@ async def get_uid_for_hotkey_on_subnet( Retrieves the unique identifier (UID) for a neuron's hotkey on a specific subnet. Arguments: - hotkey_ss58: The `SS58` address of the neuron's hotkey. + hotkey_ss58: The ``SS58`` address of the neuron's hotkey. netuid: The unique identifier of the subnet. block: The blockchain block number for the query. block_hash: The blockchain block_hash representation of the block id. @@ -3307,7 +3307,7 @@ async def is_hotkey_registered_any( Checks if a neuron's hotkey is registered on any subnet within the Bittensor network. Arguments: - hotkey_ss58: The `SS58` address of the neuron's hotkey. + hotkey_ss58: The ``SS58`` address of the neuron's hotkey. block: The blockchain block number for the query. block_hash: The blockchain block_hash representation of block id. reuse_block: Whether to reuse the last-used block hash. @@ -3358,9 +3358,9 @@ async def is_subnet_active( reuse_block: Whether to reuse the last-used block hash. Returns: - `True` if subnet is active, `False` otherwise. + ``True`` if subnet is active, ``False`` otherwise. - This means whether the `start_call` was initiated or not. + Note: This means whether the ``start_call`` was initiated or not. """ query = await self.query_subtensor( name="FirstEmissionBlockNumber", @@ -3400,7 +3400,7 @@ async def max_weight_limit( reuse_block: Whether to reuse the last-used block hash. Returns: - Optional[float]: The value of the MaxWeightsLimit hyperparameter, or `None` if the subnetwork does not + Optional[float]: The value of the MaxWeightsLimit hyperparameter, or ``None`` if the subnetwork does not exist or the parameter is not found. """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) @@ -3422,7 +3422,7 @@ async def metagraph( Arguments: netuid: The network UID of the subnet to query. lite: If true, returns a metagraph using a lightweight sync (no weights, no bonds). Default is - `True`. + ``True``. block: Block number for synchronization, or `None` for the latest block. Returns: @@ -3460,7 +3460,7 @@ async def min_allowed_weights( reuse_block: Whether to reuse the last-used block hash. Returns: - Optional[int]: The value of the MinAllowedWeights hyperparameter, or `None` if the subnetwork does not + Optional[int]: The value of the MinAllowedWeights hyperparameter, or ``None`` if the subnetwork does not exist or the parameter is not found. """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) @@ -3611,13 +3611,13 @@ async def query_identity( reuse_block: Whether to reuse the last-used blockchain block hash. Returns: - An object containing the identity information of the neuron if found, `None` otherwise. + An object containing the identity information of the neuron if found, ``None`` otherwise. The identity information can include various attributes such as the neuron's stake, rank, and other network-specific details, providing insights into the neuron's role and status within the Bittensor network. Note: - See the `Bittensor CLI documentation `_ for supported identity + See the ``Bittensor CLI documentation ``_ for supported identity parameters. """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) @@ -3657,7 +3657,7 @@ async def recycle( reuse_block: Whether to reuse the last-used blockchain block hash. Returns: - Optional[Balance]: The value of the 'Burn' hyperparameter if the subnet exists, None otherwise. + Optional[Balance]: The value of the 'Burn' hyperparameter if the subnet exists, ``None`` otherwise. Understanding the 'Burn' rate is essential for analyzing the network registration usage, particularly how it is correlated with user activity and the overall cost of participation in a given subnet. @@ -3688,14 +3688,14 @@ async def set_reveal_commitment( netuid: The unique identifier of the subnetwork. data: The data to be committed to the network. blocks_until_reveal: The number of blocks from now after which the data will be revealed. - Defaults to `360` (the number of blocks in one epoch). - block_time: The number of seconds between each block. Defaults to `12`. + Defaults to ``360`` (the number of blocks in one epoch). + block_time: The number of seconds between each block. Defaults to ``12``. period: The number of blocks during which the transaction will remain valid after it's submitted. If the transaction is not included in a block within that number of blocks, it will expire and be rejected. You can think of it as an expiration date for the transaction. Returns: - bool: `True` if the commitment was successful, `False` otherwise. + bool: ``True`` if the commitment was successful, ``False`` otherwise. Note: A commitment can be set once per subnet epoch and is reset at the next epoch in the chain automatically. """ @@ -3769,7 +3769,7 @@ async def subnet_exists( reuse_block: Whether to reuse the last-used block hash. Returns: - `True` if the subnet exists, `False` otherwise. + ``True`` if the subnet exists, ``False`` otherwise. This function is critical for verifying the presence of specific subnets in the network, enabling a deeper understanding of the network's structure and composition. @@ -3801,7 +3801,7 @@ async def subnetwork_n( reuse_block: Whether to reuse the last-used block hash. Returns: - Optional[int]: The value of the SubnetworkN hyperparameter, or `None` if the subnetwork does not exist or + Optional[int]: The value of the SubnetworkN hyperparameter, or ``None`` if the subnetwork does not exist or the parameter is not found. """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) @@ -3830,7 +3830,7 @@ async def tempo( reuse_block: Whether to reuse the last-used block hash. Returns: - Optional[int]: The value of the Tempo hyperparameter, or `None` if the subnetwork does not exist or the + Optional[int]: The value of the Tempo hyperparameter, or ``None`` if the subnetwork does not exist or the parameter is not found. """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) @@ -3858,7 +3858,7 @@ async def tx_rate_limit( reuse_block: Whether to reuse the last-used block hash. Returns: - Optional[int]: The transaction rate limit of the network, None if not available. + Optional[int]: The transaction rate limit of the network, ``None`` if not available. The transaction rate limit is an essential parameter for ensuring the stability and scalability of the Bittensor network. It helps in managing network load and preventing congestion, thereby maintaining efficient and @@ -3876,10 +3876,10 @@ async def wait_for_block(self, block: Optional[int] = None): waits for the next block. Arguments: - block: The block number to wait for. If None, waits for the next block. + block: The block number to wait for. If ``None``, waits for the next block. Returns: - bool: True if the target block was reached, False if timeout occurred. + bool: ``True`` if the target block was reached, ``False`` if timeout occurred. Example: import bittensor as bt @@ -3966,7 +3966,7 @@ async def weights_rate_limit( reuse_block: Whether to reuse the last-used blockchain block hash. Returns: - Optional[int]: The value of the WeightsSetRateLimit hyperparameter, or `None` if the subnetwork does not + Optional[int]: The value of the WeightsSetRateLimit hyperparameter, or ``None`` if the subnetwork does not exist or the parameter is not found. """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) @@ -4076,7 +4076,7 @@ async def sign_and_send_extrinsic( and be rejected. You can think of it as an expiration date for the transaction. nonce_key: the type on nonce to use. Options are "hotkey" or "coldkey". nonce_key: the type on nonce to use. Options are "hotkey", "coldkey", or "coldkeypub". - raise_error: raises a relevant exception rather than returning `False` if unsuccessful. + raise_error: raises a relevant exception rather than returning ``False`` if unsuccessful. Returns: (success, error message) @@ -4153,24 +4153,24 @@ async def add_stake( Arguments: wallet: The wallet to be used for staking. hotkey_ss58: The SS58 address of the hotkey associated with the neuron to which you intend to delegate your - stake. If not specified, the wallet's hotkey will be used. Defaults to `None`. + stake. If not specified, the wallet's hotkey will be used. Defaults to ``None``. netuid: The unique identifier of the subnet to which the neuron belongs. amount: The amount of TAO to stake. wait_for_inclusion: Waits for the transaction to be included in a block. Defaults to `True`. wait_for_finalization: Waits for the transaction to be finalized on the blockchain. Defaults to `False`. safe_staking: If true, enables price safety checks to protect against fluctuating prices. The stake will - only execute if the price change doesn't exceed the rate tolerance. Default is `False`. + only execute if the price change doesn't exceed the rate tolerance. Default is ``False``. allow_partial_stake: If true and safe_staking is enabled, allows partial staking when the full amount would exceed the price tolerance. If false, the entire stake fails if it would exceed the tolerance. - Default is `False`. + Default is ``False``. rate_tolerance: The maximum allowed price change ratio when staking. For example, 0.005 = 0.5% maximum price increase. Only used when safe_staking is True. Default is ``0.005``. period: The number of blocks during which the transaction will remain valid after it's submitted. If the transaction is not included in a block within that number of blocks, it will expire and be rejected. You - can think of it as an expiration date for the transaction. Defaults to `None`. + can think of it as an expiration date for the transaction. Defaults to ``None``. Returns: - bool: `True` if the staking is successful, False otherwise. + bool: ``True`` if the staking is successful, ``False`` otherwise. This function enables neurons to increase their stake in the network, enhancing their influence and potential. When safe_staking is enabled, it provides protection against price fluctuations during the time stake is @@ -4225,7 +4225,7 @@ async def add_liquidity( - True and a success message if the extrinsic is successfully submitted or processed. - False and an error message if the submission fails or the wallet cannot be unlocked. - Note: Adding is allowed even when user liquidity is enabled in specified subnet. Call `toggle_user_liquidity` + Note: Adding is allowed even when user liquidity is enabled in specified subnet. Call ``toggle_user_liquidity`` method to enable/disable user liquidity. """ return await add_liquidity_extrinsic( @@ -4256,14 +4256,14 @@ async def add_stake_multiple( Arguments: wallet: The wallet used for staking. - hotkey_ss58s: List of `SS58` addresses of hotkeys to stake to. + hotkey_ss58s: List of ``SS58`` addresses of hotkeys to stake to. netui: list of subnet UIDs amounts: Corresponding amounts of TAO to stake for each hotkey. wait_for_inclusion: Waits for the transaction to be included in a block. Defaults to `True`. wait_for_finalization: Waits for the transaction to be finalized on the blockchain. Defaults to `False`. Returns: - bool: `True` if the staking is successful for all specified neurons, False otherwise. + bool: ``True`` if the staking is successful for all specified neurons, ``False`` otherwise. This function is essential for managing stakes across multiple neurons, reflecting the dynamic and collaborative nature of the Bittensor network. @@ -4294,7 +4294,7 @@ async def burned_register( wallet: The wallet associated with the neuron to be registered. netuid: The unique identifier of the subnet. wait_for_inclusion: Waits for the transaction to be included in a block. Defaults to - `False`. + ``False``. wait_for_finalization: Waits for the transaction to be finalized on the blockchain. period: The number of blocks during which the transaction will remain valid after it's submitted. If the transaction is not included in a block within that number of blocks, it will expire @@ -4911,11 +4911,11 @@ async def set_delegate_take( Arguments: wallet: bittensor wallet instance. - hotkey_ss58: The `SS58` address of the neuron's hotkey. + hotkey_ss58: The ``SS58`` address of the neuron's hotkey. take: Percentage reward for the delegate. wait_for_inclusion: Waits for the transaction to be included in a block. wait_for_finalization: Waits for the transaction to be finalized on_error: Raises a relevant exception - rather than returning `False` if unsuccessful. + rather than returning ``False`` if unsuccessful. period: The number of blocks during which the transaction will remain valid after it's submitted. If the transaction is not included in a block within that number of blocks, it will expire and be rejected. You can think of it as an expiration date for the transaction. @@ -5568,27 +5568,27 @@ async def unstake_multiple( unstake_all: bool = False, ) -> bool: """ - Performs batch unstaking from multiple hotkey accounts, allowing a neuron to reduce its staked amounts - efficiently. This function is useful for managing the distribution of stakes across multiple neurons. - - Arguments: - wallet: The wallet linked to the coldkey from which the stakes are being - withdrawn. - hotkey_ss58s: A list of hotkey `SS58` addresses to unstake from. - netuids: Subnets unique IDs. - amounts: The amounts of TAO to unstake from each hotkey. If not provided, unstakes all. - wait_for_inclusion: Waits for the transaction to be included in a block. - wait_for_finalization: Waits for the transaction to be finalized on the blockchain. - period: The number of blocks during which the transaction will remain valid after it's - submitted. If the transaction is not included in a block within that number of blocks, it will expire - and be rejected. You can think of it as an expiration date for the transaction. - unstake_all: If true, unstakes all tokens. Default is `False`. If `True` amounts are ignored. - - Returns: - bool: `True` if the batch unstaking is successful, False otherwise. - - This function allows for strategic reallocation or withdrawal of stakes, aligning with the dynamic stake - management aspect of the Bittensor network. + Performs batch unstaking from multiple hotkey accounts, allowing a neuron to reduce its staked amounts + efficiently. This function is useful for managing the distribution of stakes across multiple neurons. + + Arguments: + wallet: The wallet linked to the coldkey from which the stakes are being + withdrawn. + hotkey_ss58s: A list of hotkey `SS58` addresses to unstake from. + netuids: Subnets unique IDs. + amounts: The amounts of TAO to unstake from each hotkey. If not provided, unstakes all. + wait_for_inclusion: Waits for the transaction to be included in a block. + wait_for_finalization: Waits for the transaction to be finalized on the blockchain. + period: The number of blocks during which the transaction will remain valid after it's + submitted. If the transaction is not included in a block within that number of blocks, it will expire + and be rejected. You can think of it as an expiration date for the transaction. + unstake_all: If true, unstakes all tokens. Default is `False`. If `True` amounts are ignored. + + Returns: + bool: `True` if the batch unstaking is successful, False otherwise. + + This function allows for strategic reallocation or withdrawal of stakes, aligning with the dynamic stake + management aspect of the Bittensor network. """ return await unstake_multiple_extrinsic( subtensor=self, From 2794155ddf563fedcfbee6928fbd34c72e8b9781 Mon Sep 17 00:00:00 2001 From: Roman <167799377+basfroman@users.noreply.github.com> Date: Wed, 9 Jul 2025 08:58:26 -0700 Subject: [PATCH 20/21] Update bittensor/core/async_subtensor.py --- bittensor/core/async_subtensor.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bittensor/core/async_subtensor.py b/bittensor/core/async_subtensor.py index 20dda8f788..0b814c5426 100644 --- a/bittensor/core/async_subtensor.py +++ b/bittensor/core/async_subtensor.py @@ -2025,7 +2025,7 @@ async def get_metagraph_info( ] else: raise ValueError( - "``field_indices`` must be a list of SelectiveMetagraphIndex enums or ints." + "`field_indices` must be a list of SelectiveMetagraphIndex enums or ints." ) query = await self.substrate.runtime_call( From 004c02524e072a45cfbe53255622a0347e253c81 Mon Sep 17 00:00:00 2001 From: Roman Date: Wed, 9 Jul 2025 09:53:42 -0700 Subject: [PATCH 21/21] fix annotations, update docstrings --- bittensor/core/async_subtensor.py | 394 +++++++++---------- bittensor/core/extrinsics/asyncex/serving.py | 2 +- 2 files changed, 194 insertions(+), 202 deletions(-) diff --git a/bittensor/core/async_subtensor.py b/bittensor/core/async_subtensor.py index 0b814c5426..aa67ec1d18 100644 --- a/bittensor/core/async_subtensor.py +++ b/bittensor/core/async_subtensor.py @@ -3,7 +3,7 @@ import ssl from datetime import datetime, timezone from functools import partial -from typing import Optional, Any, Union, Iterable, TYPE_CHECKING +from typing import cast, Optional, Any, Union, Iterable, TYPE_CHECKING import asyncstdlib as a import numpy as np @@ -462,14 +462,14 @@ def _get_substrate( Arguments: fallback_endpoints: List of fallback endpoints to use if default or provided network is not available. - Defaults to ``None``. + Defaults to ``None``. retry_forever: Whether to retry forever on connection errors. Defaults to ``False``. _mock: Whether this is a mock instance. Mainly for testing purposes. Defaults to ``False``. archive_endpoints: Similar to fallback_endpoints, but specifically only archive nodes. Will be used in - cases where you are requesting a block that is too old for your current (presumably lite) node. Defaults - to ``None``. - ws_shutdown_timer: Amount of time, in seconds, to wait after the last response from the chain to close - the connection. + cases where you are requesting a block that is too old for your current (presumably lite) node. Defaults + to ``None``. + ws_shutdown_timer: Amount of time, in seconds, to wait after the last response from the chain to close the + connection. Returns: Either AsyncSubstrateInterface or RetryAsyncSubstrate. @@ -518,9 +518,9 @@ async def query_constant( module_name: The name of the module containing the constant (e.g., "Balances", "SubtensorModule"). constant_name: The name of the constant to retrieve (e.g., "ExistentialDeposit"). block: The blockchain block number at which to query the constant. Do not specify if using block_hash or - reuse_block. + reuse_block. block_hash: The hash of the blockchain block at which to query the constant. Do not specify if using - block or reuse_block. + block or reuse_block. reuse_block: Whether to reuse the blockchain block at which to query the constant. Defaults to ``False``. Returns: @@ -567,9 +567,9 @@ async def query_map( name: The specific storage function within the module to query (e.g., "Bonds", "Weights"). block: The blockchain block number at which to perform the query. Defaults to ``None`` (latest block). block_hash: The hash of the block to retrieve the parameter from. Do not specify if using block or - reuse_block. + reuse_block. reuse_block: Whether to use the last-used block. Do not set if using block_hash or block. Defaults to - ``False``. + ``False``. params: Parameters to be passed to the query. Defaults to ``None``. Returns: @@ -608,7 +608,7 @@ async def query_map_subtensor( name: The name of the map storage function to query. block: The blockchain block number at which to perform the query. block_hash: The hash of the block to retrieve the parameter from. Do not specify if using block or - reuse_block. + reuse_block. reuse_block: Whether to use the last-used block. Do not set if using block_hash or block. params: A list of parameters to pass to the query function. @@ -723,8 +723,8 @@ async def query_subtensor( Returns: query_response: An object containing the requested data. - This query function is essential for accessing detailed information about the network and its neurons, - providing valuable insights into the state and dynamics of the Bittensor ecosystem. + This query function is essential for accessing detailed information about the network and its neurons, providing + valuable insights into the state and dynamics of the Bittensor ecosystem. """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) return await self.substrate.query( @@ -757,8 +757,8 @@ async def state_call( Returns: result (dict[Any, Any]): The result of the rpc call. - The state call function provides a more direct and flexible way of querying blockchain data, useful for - specific use cases where standard queries are insufficient. + The state call function provides a more direct and flexible way of querying blockchain data, useful for specific + use cases where standard queries are insufficient. """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) return await self.substrate.rpc_request( @@ -886,7 +886,7 @@ async def bonds( Bonds represent the "investment" a subnet validator has made in evaluating a specific subnet miner. This bonding mechanism is integral to the Yuma Consensus' design intent of incentivizing high-quality performance - by subnet miners, and honest evaluation by subnet validators. + by subnet miners, and honest evaluation by subnet validators. Arguments: netuid: The unique identifier of the subnet. @@ -926,15 +926,15 @@ async def commit( """Commits arbitrary data to the Bittensor network by publishing metadata. This method allows neurons to publish arbitrary data to the blockchain, which can be used for various purposes - such as sharing model updates, configuration data, or other network-relevant information. + such as sharing model updates, configuration data, or other network-relevant information. Arguments: wallet: The wallet associated with the neuron committing the data. netuid: The unique identifier of the subnet. data: The data to be committed to the network. period: The number of blocks during which the transaction will remain valid after it's submitted. If the - transaction is not included in a block within that number of blocks, it will expire and be rejected. You - can think of it as an expiration date for the transaction. + transaction is not included in a block within that number of blocks, it will expire and be rejected. You + can think of it as an expiration date for the transaction. Returns: bool: True if the commit was successful, False otherwise. @@ -969,8 +969,7 @@ async def commit_reveal_enabled( """Check if commit-reveal mechanism is enabled for a given subnet at a specific block. The commit reveal feature is designed to solve the weight-copying problem by giving would-be weight-copiers - access only to stale weights. Copying stale weights should result in subnet validators departing from - consensus. + access only to stale weights. Copying stale weights should result in subnet validators departing from consensus. Arguments: netuid: The unique identifier of the subnet for which to check the commit-reveal mechanism. @@ -1018,7 +1017,7 @@ async def difficulty( netuid: The unique identifier of the subnet. block: The block number for the query. Do not specify if using block_hash or reuse_block. block_hash: The hash of the block to retrieve the parameter from. Do not specify if using block or - reuse_block. + reuse_block. reuse_block: Whether to use the last-used block. Do not set if using block_hash or block. Returns: @@ -1192,9 +1191,9 @@ async def get_balances( ) -> dict[str, Balance]: """Retrieves the balance for given coldkey(s). - This method efficiently queries multiple coldkey addresses in a single batch operation, returning a - dictionary mapping each address to its corresponding balance. This is more efficient than calling get_balance - multiple times. + This method efficiently queries multiple coldkey addresses in a single batch operation, returning a dictionary + mapping each address to its corresponding balance. This is more efficient than calling get_balance multiple + times. Arguments: *addresses: Variable number of coldkey addresses in SS58 format. @@ -1235,7 +1234,7 @@ async def get_current_block(self) -> int: This function provides the latest block number, indicating the most recent state of the blockchain. Knowing the current block number is essential for querying real-time data and performing time-sensitive operations on - the blockchain. It serves as a reference point for network activities and data synchronization. + the blockchain. It serves as a reference point for network activities and data synchronization. Returns: int: The current chain block number. @@ -1263,8 +1262,8 @@ async def get_block_hash(self, block: Optional[int] = None) -> str: The block hash is a unique identifier representing the cryptographic hash of the block's content, ensuring its integrity and immutability. It is a fundamental aspect of blockchain technology, providing a secure reference - to each block's data. It is crucial for verifying transactions, ensuring data consistency, and maintaining - the trustworthiness of the blockchain. + to each block's data. It is crucial for verifying transactions, ensuring data consistency, and maintaining the + trustworthiness of the blockchain. Arguments: block: The block number for which the hash is to be retrieved. If ``None``, returns the latest block hash. @@ -1339,9 +1338,9 @@ async def get_children( ) -> tuple[bool, list[tuple[float, str]], str]: """Retrieves the children of a given hotkey and netuid. - This method queries the SubtensorModule's ChildKeys storage function to get the children and formats them - before returning as a tuple. It provides information about the child neurons that a validator has set for - weight distribution. + This method queries the SubtensorModule's ChildKeys storage function to get the children and formats them before + returning as a tuple. It provides information about the child neurons that a validator has set for weight + distribution. Arguments: hotkey: The hotkey value. @@ -1446,8 +1445,8 @@ async def get_commitment( ) -> str: """Retrieves the on-chain commitment for a specific neuron in the Bittensor network. - This method retrieves the commitment data that a neuron has published to the blockchain. Commitments are used - in the commit-reveal mechanism for secure weight setting and other network operations. + This method retrieves the commitment data that a neuron has published to the blockchain. Commitments are used in + the commit-reveal mechanism for secure weight setting and other network operations. Arguments: netuid: The unique identifier of the subnetwork. @@ -1515,7 +1514,7 @@ async def get_last_commitment_bonds_reset_block( try: return decode_block(block) except TypeError: - return "" + return None async def get_all_commitments( self, @@ -1526,8 +1525,8 @@ async def get_all_commitments( ) -> dict[str, str]: """Retrieves the on-chain commitments for a specific subnet in the Bittensor network. - This method retrieves all commitment data for all neurons in a specific subnet. This is useful for - analyzing the commit-reveal patterns across an entire subnet. + This method retrieves all commitment data for all neurons in a specific subnet. This is useful for analyzing the + commit-reveal patterns across an entire subnet. Arguments: netuid: The unique identifier of the subnetwork. @@ -1644,8 +1643,7 @@ async def get_all_revealed_commitments( reuse_block: Whether to reuse the last-used block hash. Returns: - result (dict): A dictionary of all revealed commitments in view - {ss58_address: (reveal block, commitment message)}. + result: A dictionary of all revealed commitments in view {ss58_address: (reveal block, commitment message)}. Example of result: { @@ -1711,7 +1709,7 @@ async def get_delegate_by_hotkey( ) -> Optional[DelegateInfo]: """ Retrieves detailed information about a delegate neuron based on its hotkey. This function provides a - comprehensive view of the delegate's status, including its stakes, nominators, and reward distribution. + comprehensive view of the delegate's status, including its stakes, nominators, and reward distribution. Arguments: hotkey_ss58: The ``SS58`` address of the delegate's hotkey. @@ -1723,7 +1721,7 @@ async def get_delegate_by_hotkey( Optional[DelegateInfo]: Detailed information about the delegate neuron, ``None`` if not found. This function is essential for understanding the roles and influence of delegate neurons within the Bittensor - network's consensus and governance structures. + network's consensus and governance structures. """ result = await self.query_runtime_api( @@ -1782,7 +1780,7 @@ async def get_delegate_take( ) -> float: """ Retrieves the delegate 'take' percentage for a neuron identified by its hotkey. The 'take' represents the - percentage of rewards that the delegate claims from its nominators' stakes. + percentage of rewards that the delegate claims from its nominators' stakes. Arguments: hotkey_ss58: The ``SS58`` address of the neuron's hotkey. @@ -1794,7 +1792,7 @@ async def get_delegate_take( float: The delegate take percentage. The delegate take is a critical parameter in the network's incentive structure, influencing the distribution of - rewards among neurons and their nominators. + rewards among neurons and their nominators. """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) result = await self.query_subtensor( @@ -1827,7 +1825,7 @@ async def get_delegated( A list of tuples, each containing a delegate's information and staked amount. This function is important for account holders to understand their stake allocations and their involvement in - the network's delegation and consensus mechanisms. + the network's delegation and consensus mechanisms. """ result = await self.query_runtime_api( @@ -1894,8 +1892,7 @@ async def get_existential_deposit( The existential deposit amount. The existential deposit is a fundamental economic parameter in the Bittensor network, ensuring efficient use of - storage and preventing the proliferation of dust accounts. - + storage and preventing the proliferation of dust accounts. """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) result = await self.substrate.get_constant( @@ -1920,7 +1917,7 @@ async def get_hotkey_owner( """ Retrieves the owner of the given hotkey at a specific block hash. This function queries the blockchain for the owner of the provided hotkey. If the hotkey does not exist at the - specified block hash, it returns None. + specified block hash, it returns None. Arguments: hotkey_ss58: The SS58 address of the hotkey. @@ -1986,8 +1983,7 @@ async def get_metagraph_info( Arguments: netuid: The unique identifier of the subnet to query. field_indices: An optional list of SelectiveMetagraphIndex or int values specifying which fields to - retrieve. - If not provided, all available fields will be returned. + retrieve. If not provided, all available fields will be returned. block: the block number at which to retrieve the hyperparameter. Do not specify if using block_hash or reuse_block block_hash: The hash of blockchain block number for the query. Do not specify if using @@ -2088,7 +2084,7 @@ async def get_netuids_for_hotkey( ) -> list[int]: """ Retrieves a list of subnet UIDs (netuids) for which a given hotkey is a member. This function identifies the - specific subnets within the Bittensor network where the neuron associated with the hotkey is active. + specific subnets within the Bittensor network where the neuron associated with the hotkey is active. Arguments: hotkey_ss58: The ``SS58`` address of the neuron's hotkey. @@ -2124,7 +2120,7 @@ async def get_neuron_certificate( ) -> Optional[Certificate]: """ Retrieves the TLS certificate for a specific neuron identified by its unique identifier (UID) within a - specified subnet (netuid) of the Bittensor network. + specified subnet (netuid) of the Bittensor network. Arguments: hotkey: The hotkey to query. @@ -2140,12 +2136,15 @@ async def get_neuron_certificate( This function is used for certificate discovery for setting up mutual tls communication between neurons. """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) - certificate = await self.query_module( - module="SubtensorModule", - name="NeuronCertificates", - block_hash=block_hash, - reuse_block=reuse_block, - params=[netuid, hotkey], + certificate = cast( + Union[str, dict], + await self.query_module( + module="SubtensorModule", + name="NeuronCertificates", + block_hash=block_hash, + reuse_block=reuse_block, + params=[netuid, hotkey], + ), ) try: if certificate: @@ -2368,11 +2367,11 @@ async def get_neuron_for_pubkey_and_subnet( ) -> "NeuronInfo": """ Retrieves information about a neuron based on its public key (hotkey SS58 address) and the specific subnet UID - (netuid). This function provides detailed neuron information for a particular subnet within the Bittensor - network. + (netuid). This function provides detailed neuron information for a particular subnet within the Bittensor + network. Arguments: - hotkey: The ``SS58`` address of the neuron's hotkey. + hotkey_ss58: The ``SS58`` address of the neuron's hotkey. netuid: The unique identifier of the subnet. block: The blockchain block number for the query. block_hash: The blockchain block number at which to perform the query. @@ -2383,7 +2382,7 @@ async def get_neuron_for_pubkey_and_subnet( ``None`` otherwise. This function is crucial for accessing specific neuron data and understanding its status, stake, and other - attributes within a particular subnet of the Bittensor ecosystem. + attributes within a particular subnet of the Bittensor ecosystem. """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) uid_query = await self.substrate.query( @@ -2414,18 +2413,15 @@ async def get_next_epoch_start_block( """ Calculates the first block number of the next epoch for the given subnet. - If ``block`` is not provided, the current chain block will be used. Epochs are - determined based on the subnet's tempo (i.e., blocks per epoch). The result - is the block number at which the next epoch will begin. + If ``block`` is not provided, the current chain block will be used. Epochs are determined based on the subnet's + tempo (i.e., blocks per epoch). The result is the block number at which the next epoch will begin. Arguments: netuid: The unique identifier of the subnet. - block: The reference block to calculate from. - If None, uses the current chain block height. + block: The reference block to calculate from. If None, uses the current chain block height. block_hash: The blockchain block number at which to perform the query. reuse_block: Whether to reuse the last-used blockchain block hash. - Returns: int: The block number at which the next epoch will start. @@ -2587,7 +2583,7 @@ async def get_subnet_info( SubnetInfo: A SubnetInfo objects, each containing detailed information about a subnet. Gaining insights into the subnet's details assists in understanding the network's composition, the roles of - different subnets, and their unique features. + different subnets, and their unique features. """ result = await self.query_runtime_api( runtime_api="SubnetInfoRuntimeApi", @@ -2646,7 +2642,7 @@ async def get_subnet_prices( ) -> dict[int, Balance]: """Gets the current Alpha price in TAO for a specified subnet. - Argsuments: + Arguments: block: The blockchain block number for the query. block_hash: The hash of the block to retrieve the stake from. Do not specify if using block or reuse_block @@ -2821,7 +2817,7 @@ async def get_stake_for_coldkey( reuse_block: Whether to reuse the last-used block hash. Returns: - Optional[list[StakeInfo]]: A list of StakeInfo objects, or ``None`` if no stake information is found. + An optional list of StakeInfo objects, or ``None`` if no stake information is found. """ result = await self.query_runtime_api( runtime_api="StakeInfoRuntimeApi", @@ -2855,9 +2851,9 @@ async def get_stake_for_hotkey( hotkey_ss58: The SS58 address of the hotkey. netuid: The subnet ID to query for. block: The block number at which to query the stake information. Do not specify if also specifying - block_hash or reuse_block + block_hash or reuse_block. block_hash: The hash of the blockchain block number for the query. Do not specify if also specifying block - or reuse_block + or reuse_block. reuse_block: Whether to reuse for this query the last-used block. Do not specify if also specifying block or block_hash. """ @@ -2917,7 +2913,7 @@ async def get_subnet_hyperparameters( ) -> Optional["SubnetHyperparameters"]: """ Retrieves the hyperparameters for a specific subnet within the Bittensor network. These hyperparameters define - the operational settings and rules governing the subnet's behavior. + the operational settings and rules governing the subnet's behavior. Arguments: netuid: The network UID of the subnet to query. @@ -2929,7 +2925,7 @@ async def get_subnet_hyperparameters( The subnet's hyperparameters, or ``None`` if not available. Understanding the hyperparameters is crucial for comprehending how subnets are configured and managed, and how - they interact with the network's consensus and incentive mechanisms. + they interact with the network's consensus and incentive mechanisms. """ result = await self.query_runtime_api( runtime_api="SubnetInfoRuntimeApi", @@ -2971,8 +2967,8 @@ async def get_subnets( Returns: A list of subnet netuids. - This function provides a comprehensive view of the subnets within the Bittensor network, - offering insights into its diversity and scale. + This function provides a comprehensive view of the subnets within the Bittensor network, offering insights into + its diversity and scale. """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) result = await self.substrate.query_map( @@ -3006,7 +3002,7 @@ async def get_total_subnets( Optional[str]: The total number of subnets in the network. Understanding the total number of subnets is essential for assessing the network's growth and the extent of its - decentralized infrastructure. + decentralized infrastructure. """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) result = await self.substrate.query( @@ -3067,7 +3063,7 @@ async def get_vote_data( ) -> Optional["ProposalVoteData"]: """ Retrieves the voting data for a specific proposal on the Bittensor blockchain. This data includes information - about how senate members have voted on the proposal. + about how senate members have voted on the proposal. Arguments: proposal_hash: The hash of the proposal for which voting data is requested. @@ -3079,7 +3075,7 @@ async def get_vote_data( An object containing the proposal's voting data, or ``None`` if not found. This function is important for tracking and understanding the decision-making processes within the Bittensor - network, particularly how proposals are received and acted upon by the governing body. + network, particularly how proposals are received and acted upon by the governing body. """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) vote_data: dict[str, Any] = await self.substrate.query( @@ -3117,7 +3113,7 @@ async def get_uid_for_hotkey_on_subnet( Optional[int]: The UID of the neuron if it is registered on the subnet, ``None`` otherwise. The UID is a critical identifier within the network, linking the neuron's hotkey to its operational and - governance activities on a particular subnet. + governance activities on a particular subnet. """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) result = await self.substrate.query( @@ -3196,7 +3192,7 @@ async def immunity_period( ) -> Optional[int]: """ Retrieves the 'ImmunityPeriod' hyperparameter for a specific subnet. This parameter defines the duration during - which new neurons are protected from certain network penalties or restrictions. + which new neurons are protected from certain network penalties or restrictions. Arguments: netuid: The unique identifier of the subnet. @@ -3208,8 +3204,8 @@ async def immunity_period( Optional[int]: The value of the 'ImmunityPeriod' hyperparameter if the subnet exists, ``None`` otherwise. The 'ImmunityPeriod' is a critical aspect of the network's governance system, ensuring that new participants - have a grace period to establish themselves and contribute to the network without facing immediate - punitive actions. + have a grace period to establish themselves and contribute to the network without facing immediate punitive + actions. """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) call = await self.get_hyperparameter( @@ -3235,7 +3231,7 @@ async def is_hotkey_delegate( ) -> bool: """ Determines whether a given hotkey (public key) is a delegate on the Bittensor network. This function checks if - the neuron associated with the hotkey is part of the network's delegation system. + the neuron associated with the hotkey is part of the network's delegation system. Arguments: hotkey_ss58: The SS58 address of the neuron's hotkey. @@ -3247,7 +3243,7 @@ async def is_hotkey_delegate( ``True`` if the hotkey is a delegate, ``False`` otherwise. Being a delegate is a significant status within the Bittensor network, indicating a neuron's involvement in - consensus and governance processes. + consensus and governance processes. """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) delegates = await self.get_delegates( @@ -3265,9 +3261,8 @@ async def is_hotkey_registered( ) -> bool: """ Determines whether a given hotkey (public key) is registered in the Bittensor network, either globally across - any subnet or specifically on a specified subnet. This function checks the registration status of a neuron - identified by its hotkey, which is crucial for validating its participation and activities within the - network. + any subnet or specifically on a specified subnet. This function checks the registration status of a neuron + identified by its hotkey, which is crucial for validating its participation and activities within the network. Arguments: hotkey_ss58: The SS58 address of the neuron's hotkey. @@ -3275,7 +3270,7 @@ async def is_hotkey_registered( registration is checked across all subnets. block: The blockchain block number at which to perform the query. block_hash: The blockchain block_hash representation of the block id. Do not specify if using block or - reuse_block + reuse_block. reuse_block: Whether to reuse the last-used blockchain block hash. Do not set if using block_hash or reuse_block. @@ -3284,8 +3279,8 @@ async def is_hotkey_registered( ``False`` otherwise. This function is important for verifying the active status of neurons in the Bittensor network. It aids in - understanding whether a neuron is eligible to participate in network processes such as consensus, - validation, and incentive distribution based on its registration status. + understanding whether a neuron is eligible to participate in network processes such as consensus, validation, + and incentive distribution based on its registration status. """ if netuid is None: return await self.is_hotkey_registered_any( @@ -3417,7 +3412,7 @@ async def metagraph( ) -> "AsyncMetagraph": """ Returns a synced metagraph for a specified subnet within the Bittensor network. The metagraph represents the - network's structure, including neuron connections and interactions. + network's structure, including neuron connections and interactions. Arguments: netuid: The network UID of the subnet to query. @@ -3430,7 +3425,7 @@ async def metagraph( relationships. The metagraph is an essential tool for understanding the topology and dynamics of the Bittensor network's - decentralized architecture, particularly in relation to neuron interconnectivity and consensus processes. + decentralized architecture, particularly in relation to neuron interconnectivity and consensus processes. """ metagraph = AsyncMetagraph( network=self.chain_endpoint, @@ -3482,8 +3477,8 @@ async def neuron_for_uid( ) -> NeuronInfo: """ Retrieves detailed information about a specific neuron identified by its unique identifier (UID) within a - specified subnet (netuid) of the Bittensor network. This function provides a comprehensive view of a - neuron's attributes, including its stake, rank, and operational status. + specified subnet (netuid) of the Bittensor network. This function provides a comprehensive view of a neuron's + attributes, including its stake, rank, and operational status. Arguments: uid: The unique identifier of the neuron. @@ -3496,7 +3491,7 @@ async def neuron_for_uid( Detailed information about the neuron if found, a null neuron otherwise This function is crucial for analyzing individual neurons' contributions and status within a specific subnet, - offering insights into their roles in the network's consensus and validation mechanisms. + offering insights into their roles in the network's consensus and validation mechanisms. """ if uid is None: return NeuronInfo.get_null_neuron() @@ -3525,7 +3520,7 @@ async def neurons( """ Retrieves a list of all neurons within a specified subnet of the Bittensor network. This function provides a snapshot of the subnet's neuron population, including each neuron's attributes and - network interactions. + network interactions. Arguments: netuid: The unique identifier of the subnet. @@ -3537,7 +3532,7 @@ async def neurons( A list of NeuronInfo objects detailing each neuron's characteristics in the subnet. Understanding the distribution and status of neurons within a subnet is key to comprehending the network's - decentralized structure and the dynamics of its consensus and governance processes. + decentralized structure and the dynamics of its consensus and governance processes. """ result = await self.query_runtime_api( runtime_api="NeuronInfoRuntimeApi", @@ -3563,7 +3558,7 @@ async def neurons_lite( """ Retrieves a list of neurons in a 'lite' format from a specific subnet of the Bittensor network. This function provides a streamlined view of the neurons, focusing on key attributes such as stake and network - participation. + participation. Arguments: netuid: The unique identifier of the subnet. @@ -3575,7 +3570,7 @@ async def neurons_lite( A list of simplified neuron information for the subnet. This function offers a quick overview of the neuron population within a subnet, facilitating efficient analysis - of the network's decentralized structure and neuron dynamics. + of the network's decentralized structure and neuron dynamics. """ result = await self.query_runtime_api( runtime_api="NeuronInfoRuntimeApi", @@ -3600,8 +3595,8 @@ async def query_identity( ) -> Optional[ChainIdentity]: """ Queries the identity of a neuron on the Bittensor blockchain using the given key. This function retrieves - detailed identity information about a specific neuron, which is a crucial aspect of the network's - decentralized identity and governance system. + detailed identity information about a specific neuron, which is a crucial aspect of the network's decentralized + identity and governance system. Arguments: coldkey_ss58: The coldkey used to query the neuron's identity (technically the neuron's coldkey SS58 @@ -3614,19 +3609,22 @@ async def query_identity( An object containing the identity information of the neuron if found, ``None`` otherwise. The identity information can include various attributes such as the neuron's stake, rank, and other - network-specific details, providing insights into the neuron's role and status within the Bittensor network. + network-specific details, providing insights into the neuron's role and status within the Bittensor network. Note: See the ``Bittensor CLI documentation ``_ for supported identity parameters. """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) - identity_info = await self.substrate.query( - module="SubtensorModule", - storage_function="IdentitiesV2", - params=[coldkey_ss58], - block_hash=block_hash, - reuse_block_hash=reuse_block, + identity_info = cast( + dict, + await self.substrate.query( + module="SubtensorModule", + storage_function="IdentitiesV2", + params=[coldkey_ss58], + block_hash=block_hash, + reuse_block_hash=reuse_block, + ), ) if not identity_info: @@ -3648,7 +3646,7 @@ async def recycle( ) -> Optional[Balance]: """ Retrieves the 'Burn' hyperparameter for a specified subnet. The 'Burn' parameter represents the amount of Tao - that is effectively recycled within the Bittensor network. + that is effectively recycled within the Bittensor network. Arguments: netuid: The unique identifier of the subnet. @@ -3660,7 +3658,7 @@ async def recycle( Optional[Balance]: The value of the 'Burn' hyperparameter if the subnet exists, ``None`` otherwise. Understanding the 'Burn' rate is essential for analyzing the network registration usage, particularly how it is - correlated with user activity and the overall cost of participation in a given subnet. + correlated with user activity and the overall cost of participation in a given subnet. """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) call = await self.get_hyperparameter( @@ -3771,8 +3769,8 @@ async def subnet_exists( Returns: ``True`` if the subnet exists, ``False`` otherwise. - This function is critical for verifying the presence of specific subnets in the network, - enabling a deeper understanding of the network's structure and composition. + This function is critical for verifying the presence of specific subnets in the network, enabling a deeper + understanding of the network's structure and composition. """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) result = await self.substrate.query( @@ -3861,8 +3859,8 @@ async def tx_rate_limit( Optional[int]: The transaction rate limit of the network, ``None`` if not available. The transaction rate limit is an essential parameter for ensuring the stability and scalability of the Bittensor - network. It helps in managing network load and preventing congestion, thereby maintaining efficient and - timely transaction processing. + network. It helps in managing network load and preventing congestion, thereby maintaining efficient and timely + transaction processing. """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) result = await self.query_subtensor( @@ -3872,8 +3870,7 @@ async def tx_rate_limit( async def wait_for_block(self, block: Optional[int] = None): """ - Waits until a specific block is reached on the chain. If no block is specified, - waits for the next block. + Waits until a specific block is reached on the chain. If no block is specified, waits for the next block. Arguments: block: The block number to wait for. If ``None``, waits for the next block. @@ -3905,7 +3902,7 @@ async def handler(block_data: dict): else: target_block = current_block["header"]["number"] + 1 - await self.substrate._get_block_handler( + await self.substrate.get_block_handler( current_block_hash, header_only=True, subscription_handler=handler ) return True @@ -3920,7 +3917,7 @@ async def weights( """ Retrieves the weight distribution set by neurons within a specific subnet of the Bittensor network. This function maps each neuron's UID to the weights it assigns to other neurons, reflecting the network's trust - and value assignment mechanisms. + and value assignment mechanisms. Arguments: netuid: The network UID of the subnet to query. @@ -3932,7 +3929,7 @@ async def weights( A list of tuples mapping each neuron's UID to its assigned weights. The weight distribution is a key factor in the network's consensus algorithm and the ranking of neurons, - influencing their influence and reward allocation within the subnet. + influencing their influence and reward allocation within the subnet. """ block_hash = await self.determine_block_hash(block, block_hash, reuse_block) # TODO look into seeing if we can speed this up with storage query @@ -3985,7 +3982,7 @@ async def get_timestamp( reuse_block: bool = False, ) -> datetime: """ - Retrieves the datetime timestamp for a given block + Retrieves the datetime timestamp for a given block. Arguments: block: The blockchain block number for the query. Do not specify if specifying block_hash or reuse_block. @@ -3995,7 +3992,7 @@ async def get_timestamp( block_hash. Returns: - datetime object for the timestamp of the block + datetime object for the timestamp of the block. """ res = await self.query_module( "Timestamp", @@ -4147,8 +4144,8 @@ async def add_stake( ) -> bool: """ Adds a stake from the specified wallet to the neuron identified by the SS58 address of its hotkey in specified - subnet. Staking is a fundamental process in the Bittensor network that enables neurons to participate - actively and earn incentives. + subnet. Staking is a fundamental process in the Bittensor network that enables neurons to participate actively + and earn incentives. Arguments: wallet: The wallet to be used for staking. @@ -4163,8 +4160,8 @@ async def add_stake( allow_partial_stake: If true and safe_staking is enabled, allows partial staking when the full amount would exceed the price tolerance. If false, the entire stake fails if it would exceed the tolerance. Default is ``False``. - rate_tolerance: The maximum allowed price change ratio when staking. For example, - 0.005 = 0.5% maximum price increase. Only used when safe_staking is True. Default is ``0.005``. + rate_tolerance: The maximum allowed price change ratio when staking. For example, 0.005 = 0.5% maximum price + increase. Only used when safe_staking is True. Default is ``0.005``. period: The number of blocks during which the transaction will remain valid after it's submitted. If the transaction is not included in a block within that number of blocks, it will expire and be rejected. You can think of it as an expiration date for the transaction. Defaults to ``None``. @@ -4173,8 +4170,8 @@ async def add_stake( bool: ``True`` if the staking is successful, ``False`` otherwise. This function enables neurons to increase their stake in the network, enhancing their influence and potential. - When safe_staking is enabled, it provides protection against price fluctuations during the time stake is - executed and the time it is actually processed by the chain. + When safe_staking is enabled, it provides protection against price fluctuations during the time stake is + executed and the time it is actually processed by the chain. """ amount = check_and_convert_to_balance(amount) return await add_stake_extrinsic( @@ -4257,7 +4254,7 @@ async def add_stake_multiple( Arguments: wallet: The wallet used for staking. hotkey_ss58s: List of ``SS58`` addresses of hotkeys to stake to. - netui: list of subnet UIDs + netuids: list of subnet UIDs. amounts: Corresponding amounts of TAO to stake for each hotkey. wait_for_inclusion: Waits for the transaction to be included in a block. Defaults to `True`. wait_for_finalization: Waits for the transaction to be finalized on the blockchain. Defaults to `False`. @@ -4266,7 +4263,7 @@ async def add_stake_multiple( bool: ``True`` if the staking is successful for all specified neurons, ``False`` otherwise. This function is essential for managing stakes across multiple neurons, reflecting the dynamic and collaborative - nature of the Bittensor network. + nature of the Bittensor network. """ return await add_stake_multiple_extrinsic( subtensor=self, @@ -4288,7 +4285,7 @@ async def burned_register( ) -> bool: """ Registers a neuron on the Bittensor network by recycling TAO. This method of registration involves recycling - TAO tokens, allowing them to be re-mined by performing work on the network. + TAO tokens, allowing them to be re-mined by performing work on the network. Arguments: wallet: The wallet associated with the neuron to be registered. @@ -4344,8 +4341,8 @@ async def commit_weights( netuid: The unique identifier of the subnet. salt: list of randomly generated integers as salt to generated weighted hash. uids: NumPy array of subnet miner neuron UIDs for which weights are being committed. - weightsy of weight values corresponding toon_key - version_key: Integer representatino of version key for compatibility with the network. + weights: of weight values corresponding toon_key + version_key: Integer representation of version key for compatibility with the network. wait_for_inclusion: Waits for the transaction to be included in a block. Default is `False`. wait_for_finalization: Waits for the transaction to be finalized on the blockchain. Default is `False`. @@ -4364,7 +4361,6 @@ async def commit_weights( Notes: See also: , - """ retries = 0 success = False @@ -4542,11 +4538,11 @@ async def register( Registers a neuron on the Bittensor network using the provided wallet. Registration is a critical step for a neuron to become an active participant in the network, enabling it to - stake, set weights, and receive incentives. + stake, set weights, and receive incentives. Arguments: wallet: The wallet associated with the neuron to be registered. - nee unique identifier of the subnet. + netuid: unique identifier of the subnet. wait_for_inclusion: Waits for the transaction to be included in a block. Defaults to `False`. wait_for_finalization: Waits for the transaction to be finalized on the blockchain. Defaults to max_allowed_attempts: Maximum number of attempts to register the wallet. @@ -4555,7 +4551,7 @@ async def register( cuda: If `true`, the wallet should be registered using CUDA device(s). Defaults to `False`. dev_id: The CUDA device id to use, or a list of device ids. Defaults to `0` (zero). tpb: The number of threads per block (CUDA). Default to `256`. - num_processes The number of processes to use to register. Default to `None`. + num_processes: The number of processes to use to register. Default to `None`. update_interval: The number of nonces to solve between updates. Default to `None`. log_verbose: If `true`, the registration process will log more information. Default to `False`. period: The number of blocks during which the transaction will remain valid after it's @@ -4565,8 +4561,8 @@ async def register( Returns: bool: `True` if the registration is successful, False otherwise. - This function facilitates the entry of new neurons into the network, supporting the decentralized - growth and scalability of the Bittensor ecosystem. + This function facilitates the entry of new neurons into the network, supporting the decentralized growth and + scalability of the Bittensor ecosystem. """ return await register_extrinsic( subtensor=self, @@ -4607,7 +4603,6 @@ async def register_subnet( Returns: bool: True if the subnet registration was successful, False otherwise. - """ return await register_subnet_extrinsic( subtensor=self, @@ -4682,7 +4677,7 @@ async def reveal_weights( Arguments: wallet: The wallet associated with the subnet validator revealing the weights. - nee unique identifier of the subnet. + netuid: unique identifier of the subnet. uids: NumPy array of subnet miner neuron UIDs for which weights are being revealed. weights: NumPy array of weight values corresponding to each UID. salt: NumPy array of salt values @@ -4856,7 +4851,7 @@ async def set_children( Arguments: wallet: bittensor wallet instance. - hotke: The `SS58` address of the neuron's hotkey. + hotkey: The `SS58` address of the neuron's hotkey. netuid: The netuid value. children: A list of children with their proportions. wait_for_inclusion: Waits for the transaction to be included in a block. @@ -4916,6 +4911,7 @@ async def set_delegate_take( wait_for_inclusion: Waits for the transaction to be included in a block. wait_for_finalization: Waits for the transaction to be finalized on_error: Raises a relevant exception rather than returning ``False`` if unsuccessful. + raise_error: raises a relevant exception rather than returning ``False`` if unsuccessful. period: The number of blocks during which the transaction will remain valid after it's submitted. If the transaction is not included in a block within that number of blocks, it will expire and be rejected. You can think of it as an expiration date for the transaction. @@ -4935,7 +4931,7 @@ async def set_delegate_take( bittensor_wallet.errors.KeyFileError: Failed to decode keyfile data. The delegate take is a critical parameter in the network's incentive structure, influencing the distribution of - rewards among neurons and their nominators. + rewards among neurons and their nominators. """ # u16 representation of the take @@ -5041,9 +5037,9 @@ async def set_weights( Sets the weight vector for a neuron acting as a validator, specifying the weights assigned to subnet miners based on their performance evaluation. - This method allows subnet validators to submit their weight vectors, which rank the value of each subnet - miner's work. These weight vectors are used by the Yuma Consensus algorithm to compute emissions for both - validators and miners. + This method allows subnet validators to submit their weight vectors, which rank the value of each subnet miner's + work. These weight vectors are used by the Yuma Consensus algorithm to compute emissions for both validators and + miners. Arguments: wallet: The wallet associated with the subnet validator setting the weights. @@ -5066,8 +5062,8 @@ async def set_weights( tuple[bool, str]: `True` if the setting of weights is successful, False otherwise. And `msg`, a string value describing the success or potential error. - This function is crucial in the Yuma Consensus mechanism, where each validator's weight vector contributes - to the overall weight matrix used to calculate emissions and maintain network consensus. + This function is crucial in the Yuma Consensus mechanism, where each validator's weight vector contributes to + the overall weight matrix used to calculate emissions and maintain network consensus. Notes: See @@ -5093,7 +5089,7 @@ async def _blocks_weight_limit() -> bool: f"Hotkey {wallet.hotkey.ss58_address} not registered in subnet {netuid}", ) - if (await self.commit_reveal_enabled(netuid=netuid)) is True: + if await self.commit_reveal_enabled(netuid=netuid): # go with `commit reveal v3` extrinsic while ( @@ -5159,24 +5155,23 @@ async def serve_axon( ) -> bool: """ Registers an ``Axon`` serving endpoint on the Bittensor network for a specific neuron. This function is used to - set up the Axon, a key component of a neuron that handles incoming queries and data processing tasks. + set up the Axon, a key component of a neuron that handles incoming queries and data processing tasks. Arguments: netuid: The unique identifier of the subnetwork. axon: The Axon instance to be registered for serving. wait_for_inclusion: Waits for the transaction to be included in a block. Default is `False`. - wait_for_finalization: Waits for the transaction to be finalized on the blockchain. Default is - `True`. + wait_for_finalization: Waits for the transaction to be finalized on the blockchain. Default is `True`. certificate: Certificate to use for TLS. If `None`, no TLS will be used. Defaults to `None`. - period: The number of blocks during which the transaction will remain valid after it's - submitted. If the transaction is not included in a block within that number of blocks, it will expire - and be rejected. You can think of it as an expiration date for the transaction. + period: The number of blocks during which the transaction will remain valid after it's submitted. If the + transaction is not included in a block within that number of blocks, it will expire and be rejected. You + can think of it as an expiration date for the transaction. Returns: bool: `True` if the Axon serve registration is successful, False otherwise. By registering an Axon, the neuron becomes an active part of the network's distributed computing infrastructure, - contributing to the collective intelligence of Bittensor. + contributing to the collective intelligence of Bittensor. """ return await serve_axon_extrinsic( subtensor=self, @@ -5198,7 +5193,7 @@ async def start_call( ) -> tuple[bool, str]: """ Submits a start_call extrinsic to the blockchain, to trigger the start call process for a subnet (used to start - a new subnet's emission mechanism). + a new subnet's emission mechanism). Arguments: wallet: The wallet used to sign the extrinsic (must be unlocked). @@ -5249,28 +5244,27 @@ async def swap_stake( amount: The amount to swap. wait_for_inclusion: Waits for the transaction to be included in a block. wait_for_finalization: Waits for the transaction to be finalized on the blockchain. - safe_staking: If true, enables price safety checks to protect against fluctuating prices. The swap - will only execute if the price ratio between subnets doesn't exceed the rate tolerance. + safe_staking: If true, enables price safety checks to protect against fluctuating prices. The swap will only + execute if the price ratio between subnets doesn't exceed the rate tolerance. Default is False. + allow_partial_stake: If true and safe_staking is enabled, allows partial stake swaps when the full amount + would exceed the price threshold. If false, the entire swap fails if it would exceed the threshold. Default is False. - allow_partial_stake: If true and safe_staking is enabled, allows partial stake swaps when - the full amount would exceed the price threshold. If false, the entire swap fails if it would - exceed the threshold. Default is False. rate_tolerance: The maximum allowed increase in the price ratio between subnets - (origin_price/destination_price). For example, 0.005 = 0.5% maximum increase. Only used - when safe_staking is True. Default is 0.005. - period: The number of blocks during which the transaction will remain valid after it's - submitted. If the transaction is not included in a block within that number of blocks, it will expire - and be rejected. You can think of it as an expiration date for the transaction. + (origin_price/destination_price). For example, 0.005 = 0.5% maximum increase. Only used when + safe_staking is True. Default is 0.005. + period: The number of blocks during which the transaction will remain valid after it's submitted. If the + transaction is not included in a block within that number of blocks, it will expire and be rejected. You + can think of it as an expiration date for the transaction. Returns: success: True if the extrinsic was successful. The price ratio for swap_stake in safe mode is calculated as: origin_subnet_price / destination_subnet_price When safe_staking is enabled, the swap will only execute if: - - With allow_partial_stake=False: The entire swap amount can be executed without the price ratio - increasing more than rate_tolerance - - With allow_partial_stake=True: A partial amount will be swapped up to the point where the - price ratio would increase by rate_tolerance + - With allow_partial_stake=False: The entire swap amount can be executed without the price ratio increasing + more than rate_tolerance. + - With allow_partial_stake=True: A partial amount will be swapped up to the point where the price ratio + would increase by rate_tolerance. """ amount = check_and_convert_to_balance(amount) return await swap_stake_extrinsic( @@ -5305,9 +5299,9 @@ async def toggle_user_liquidity( enable: Boolean indicating whether to enable user liquidity. wait_for_inclusion: Whether to wait for the extrinsic to be included in a block. Defaults to True. wait_for_finalization: Whether to wait for finalization of the extrinsic. Defaults to False. - period: The number of blocks during which the transaction will remain valid after it's submitted. If - the transaction is not included in a block within that number of blocks, it will expire and be rejected. - You can think of it as an expiration date for the transaction. + period: The number of blocks during which the transaction will remain valid after it's submitted. If the + transaction is not included in a block within that number of blocks, it will expire and be rejected. You + can think of it as an expiration date for the transaction. Returns: Tuple[bool, str]: @@ -5342,15 +5336,15 @@ async def transfer( Arguments: wallet: Source wallet for the transfer. - des: Destination address for the transfer. + dest: Destination address for the transfer. amount: Number of tokens to transfer. transfer_all: Flag to transfer all tokens. Default is `False`. wait_for_inclusion: Waits for the transaction to be included in a block. Defaults to `True`. wait_for_finalization: Waits for the transaction to be finalized on the blockchain. Defaults to `False`. keep_alive: Flag to keep the connection alive. Default is `True`. - period: The number of blocks during which the transaction will remain valid after it's - submitted. If the transaction is not included in a block within that number of blocks, it will expire - and be rejected. You can think of it as an expiration date for the transaction. + period: The number of blocks during which the transaction will remain valid after it's submitted. If the + transaction is not included in a block within that number of blocks, it will expire and be rejected. You + can think of it as an expiration date for the transaction. Returns: `True` if the transferring was successful, otherwise `False`. """ @@ -5391,9 +5385,9 @@ async def transfer_stake( amount: Amount to transfer. wait_for_inclusion: If true, waits for inclusion before returning. wait_for_finalization: If true, waits for finalization before returning. - period: The number of blocks during which the transaction will remain valid after it's - submitted. If the transaction is not included in a block within that number of blocks, it will expire - and be rejected. You can think of it as an expiration date for the transaction. + period: The number of blocks during which the transaction will remain valid after it's submitted. If the + transaction is not included in a block within that number of blocks, it will expire and be rejected. You + can think of it as an expiration date for the transaction. Returns: success: True if the transfer was successful. @@ -5428,7 +5422,7 @@ async def unstake( ) -> bool: """ Removes a specified amount of stake from a single hotkey account. This function is critical for adjusting - individual neuron stakes within the Bittensor network. + individual neuron stakes within the Bittensor network. Arguments: wallet: The wallet associated with the neuron from which the stake is being @@ -5438,23 +5432,23 @@ async def unstake( amount: The amount of alpha to unstake. If not specified, unstakes all. wait_for_inclusion: Waits for the transaction to be included in a block. Defaults to `True`. wait_for_finalization: Waits for the transaction to be finalized on the blockchain. Defaults to `False`. - safe_staking: If true, enables price safety checks to protect against fluctuating prices. The unstake - will only execute if the price change doesn't exceed the rate tolerance. Default is False. + safe_staking: If true, enables price safety checks to protect against fluctuating prices. The unstake will + only execute if the price change doesn't exceed the rate tolerance. Default is False. allow_partial_stake: If true and safe_staking is enabled, allows partial unstaking when - the full amount would exceed the price threshold. If false, the entire unstake fails if it would - exceed the threshold. Default is False. - rate_tolerance: The maximum allowed price change ratio when unstaking. For example, - 0.005 = 0.5% maximum price decrease. Only used when safe_staking is True. Default is 0.005. - period: The number of blocks during which the transaction will remain valid after it's - submitted. If the transaction is not included in a block within that number of blocks, it will expire - and be rejected. You can think of it as an expiration date for the transaction. + the full amount would exceed the price threshold. If false, the entire unstake fails if it would exceed + the threshold. Default is False. + rate_tolerance: The maximum allowed price change ratio when unstaking. For example, 0.005 = 0.5% maximum + price decrease. Only used when safe_staking is True. Default is 0.005. + period: The number of blocks during which the transaction will remain valid after it's submitted. If the + transaction is not included in a block within that number of blocks, it will expire and be rejected. You + can think of it as an expiration date for the transaction. unstake_all: If `True`, unstakes all tokens and `amount` is ignored. Default is `False` Returns: bool: `True` if the unstaking process is successful, False otherwise. This function supports flexible stake management, allowing neurons to adjust their network participation and - potential reward accruals. + potential reward accruals. """ amount = check_and_convert_to_balance(amount) return await unstake_extrinsic( @@ -5569,26 +5563,25 @@ async def unstake_multiple( ) -> bool: """ Performs batch unstaking from multiple hotkey accounts, allowing a neuron to reduce its staked amounts - efficiently. This function is useful for managing the distribution of stakes across multiple neurons. + efficiently. This function is useful for managing the distribution of stakes across multiple neurons. Arguments: - wallet: The wallet linked to the coldkey from which the stakes are being - withdrawn. + wallet: The wallet linked to the coldkey from which the stakes are being withdrawn. hotkey_ss58s: A list of hotkey `SS58` addresses to unstake from. netuids: Subnets unique IDs. amounts: The amounts of TAO to unstake from each hotkey. If not provided, unstakes all. wait_for_inclusion: Waits for the transaction to be included in a block. wait_for_finalization: Waits for the transaction to be finalized on the blockchain. - period: The number of blocks during which the transaction will remain valid after it's - submitted. If the transaction is not included in a block within that number of blocks, it will expire - and be rejected. You can think of it as an expiration date for the transaction. + period: The number of blocks during which the transaction will remain valid after it's submitted. If the + transaction is not included in a block within that number of blocks, it will expire and be rejected. You + can think of it as an expiration date for the transaction. unstake_all: If true, unstakes all tokens. Default is `False`. If `True` amounts are ignored. Returns: bool: `True` if the batch unstaking is successful, False otherwise. This function allows for strategic reallocation or withdrawal of stakes, aligning with the dynamic stake - management aspect of the Bittensor network. + management aspect of the Bittensor network. """ return await unstake_multiple_extrinsic( subtensor=self, @@ -5609,9 +5602,8 @@ async def get_async_subtensor( _mock: bool = False, log_verbose: bool = False, ) -> "AsyncSubtensor": - """ - Factory method to create an initialized AsyncSubtensor. Mainly useful for when you don't want to run - `await subtensor.initialize()` after instantiation. + """Factory method to create an initialized AsyncSubtensor. + Mainly useful for when you don't want to run `await subtensor.initialize()` after instantiation. """ sub = AsyncSubtensor( network=network, config=config, _mock=_mock, log_verbose=log_verbose diff --git a/bittensor/core/extrinsics/asyncex/serving.py b/bittensor/core/extrinsics/asyncex/serving.py index 5fa46554d0..ffd952e049 100644 --- a/bittensor/core/extrinsics/asyncex/serving.py +++ b/bittensor/core/extrinsics/asyncex/serving.py @@ -306,7 +306,7 @@ async def get_metadata( block: Optional[int] = None, block_hash: Optional[str] = None, reuse_block: bool = False, -) -> str: +) -> Union[str, dict]: """Fetches metadata from the blockchain for a given hotkey and netuid.""" async with subtensor.substrate: block_hash = await subtensor.determine_block_hash(