bittensor.core.async_subtensor

Contents

bittensor.core.async_subtensor#

Classes#

AsyncSubtensor

Asynchronous interface for interacting with the Bittensor blockchain.

Functions#

get_async_subtensor([network, config, _mock, log_verbose])

Factory method to create an initialized AsyncSubtensor.

Module Contents#

class bittensor.core.async_subtensor.AsyncSubtensor(network=None, config=None, log_verbose=False, fallback_endpoints=None, retry_forever=False, _mock=False, archive_endpoints=None, websocket_shutdown_timer=5.0)[source]#

Bases: bittensor.core.types.SubtensorMixin

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.

Initializes an AsyncSubtensor instance for blockchain interaction.

Parameters:
  • network (Optional[str]) – The network name or type to connect to (e.g., “finney”, “test”). If None, uses the default network from config.

  • config (Optional[bittensor.core.config.Config]) – Configuration object for the AsyncSubtensor instance. If None, uses the default configuration.

  • log_verbose (bool) – Enables or disables verbose logging. Defaults to False.

  • fallback_endpoints (Optional[list[str]]) – List of fallback endpoints to use if default or provided network is not available. Defaults to None.

  • retry_forever (bool) – Whether to retry forever on connection errors. Defaults to False.

  • _mock (bool) – Whether this is a mock instance. Mainly for testing purposes. Defaults to False.

  • archive_endpoints (Optional[list[str]]) – 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 (float) – 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:
  • 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(network=”finney”) as subtensor:

block_hash = await subtensor.get_block_hash()

asyncio.run(main())

async add_liquidity(wallet, netuid, liquidity, price_low, price_high, hotkey=None, wait_for_inclusion=True, wait_for_finalization=False, period=None)#

Adds liquidity to the specified price range.

Parameters:
  • wallet (bittensor_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.

  • liquidity (bittensor.utils.balance.Balance) – The amount of liquidity to be added.

  • price_low (bittensor.utils.balance.Balance) – The lower bound of the price tick range. In TAO.

  • price_high (bittensor.utils.balance.Balance) – The upper bound of the price tick range. In TAO.

  • hotkey (Optional[str]) – The hotkey with staked TAO in Alpha. If not passed then the wallet hotkey is used. Defaults to None.

  • wait_for_inclusion (bool) – Whether to wait for the extrinsic to be included in a block. Defaults to True.

  • wait_for_finalization (bool) – 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.

Returns:

  • 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.

Return type:

Tuple[bool, str]

Note: Adding is allowed even when user liquidity is enabled in specified subnet. Call toggle_user_liquidity

method to enable/disable user liquidity.

async add_stake(wallet, hotkey_ss58=None, netuid=None, amount=None, wait_for_inclusion=True, wait_for_finalization=False, safe_staking=False, allow_partial_stake=False, rate_tolerance=0.005, period=None)[source]#

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.

Parameters:
  • wallet (bittensor_wallet.Wallet) – The wallet to be used for staking.

  • hotkey_ss58 (Optional[str]) – 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.

  • netuid (Optional[int]) – The unique identifier of the subnet to which the neuron belongs.

  • amount (Optional[bittensor.utils.balance.Balance]) – The amount of TAO to stake.

  • wait_for_inclusion (bool) – Waits for the transaction to be included in a block. Defaults to True.

  • wait_for_finalization (bool) – Waits for the transaction to be finalized on the blockchain. Defaults to False.

  • safe_staking (bool) – 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.

  • allow_partial_stake (bool) – 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 (float) – 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 (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. Defaults to None.

Returns:

True if the staking is successful, False otherwise.

Return type:

bool

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.

async add_stake_multiple(wallet, hotkey_ss58s, netuids, amounts=None, wait_for_inclusion=True, wait_for_finalization=False)[source]#

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.

Parameters:
  • wallet (bittensor_wallet.Wallet) – The wallet used for staking.

  • hotkey_ss58s (list[str]) – List of SS58 addresses of hotkeys to stake to.

  • netuids (list[int]) – list of subnet UIDs.

  • amounts (Optional[list[bittensor.utils.balance.Balance]]) – Corresponding amounts of TAO to stake for each hotkey.

  • wait_for_inclusion (bool) – Waits for the transaction to be included in a block. Defaults to True.

  • wait_for_finalization (bool) – Waits for the transaction to be finalized on the blockchain. Defaults to False.

Returns:

True if the staking is successful for all specified neurons, False otherwise.

Return type:

bool

This function is essential for managing stakes across multiple neurons, reflecting the dynamic and collaborative nature of the Bittensor network.

async all_subnets(block_number=None, block_hash=None, reuse_block=False)[source]#

Queries the blockchain for comprehensive information about all subnets, including their dynamic parameters and operational status.

Parameters:
  • 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:

A list of DynamicInfo objects, each containing detailed information about a subnet, or None if the query fails.

Return type:

Optional[list[DynamicInfo]]

Example

Get all subnets at current block:

subnets = await subtensor.all_subnets()
property block#

Provides an asynchronous property to retrieve the current block.

async blocks_since_last_step(netuid, block=None, block_hash=None, reuse_block=False)#

Queries the blockchain to determine how many blocks have passed since the last epoch step for a specific subnet.

Parameters:
  • netuid (int) – The unique identifier of the subnetwork.

  • 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:

The number of blocks since the last step in the subnet, or None if the query fails.

Return type:

Optional[int]

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)
async blocks_since_last_update(netuid, uid)[source]#

Returns the number of blocks since the last update, or None if the subnetwork or UID does not exist.

Parameters:
  • netuid (int) – The unique identifier of the subnetwork.

  • uid (int) – The unique identifier of the neuron.

Returns:

The number of blocks since the last update, or None if the subnetwork or UID does not exist.

Return type:

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)
async bonds(netuid, block=None, block_hash=None, reuse_block=False)[source]#

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.

Parameters:
  • 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 (bool) – 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.

Return type:

list[tuple[int, list[tuple[int, int]]]]

Example

Get bonds for subnet 1 at block 1000000:

bonds = await subtensor.bonds(netuid=1, block=1000000)
async burned_register(wallet, netuid, wait_for_inclusion=False, wait_for_finalization=True, period=None)[source]#

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.

Parameters:
  • 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.

  • 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.

Returns:

True if the registration is successful, False otherwise.

Return type:

bool

async close()[source]#

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()

balance = await subtensor.get_balance(address="5F...")

await subtensor.close()
async commit(wallet, netuid, data, period=None)[source]#

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.

Parameters:
  • wallet (bittensor_wallet.Wallet) – The wallet associated with the neuron committing the data.

  • netuid (int) – The unique identifier of the subnet.

  • 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.

Returns:

True if the commit was successful, False otherwise.

Return type:

bool

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 <https://docs.learnbittensor.org/glossary#commit-reveal>

async commit_reveal_enabled(netuid, block=None, block_hash=None, reuse_block=False)[source]#

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.

Parameters:
  • netuid (int) – The unique identifier of the subnet for which to check the commit-reveal mechanism.

  • block (Optional[int]) – The block number to query. Do not specify if using block_hash or reuse_block.

  • block_hash (Optional[str]) – The block hash at which to check the parameter. Do not set 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.

Returns:

True if commit-reveal mechanism is enabled, False otherwise.

Return type:

bool

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)
async commit_weights(wallet, netuid, salt, uids, weights, version_key=version_as_int, wait_for_inclusion=False, wait_for_finalization=False, max_retries=5, period=16)[source]#

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.

Parameters:
  • 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 (Union[numpy.typing.NDArray[numpy.int64], list]) – NumPy array of subnet miner neuron UIDs for which weights are being committed.

  • weights (Union[numpy.typing.NDArray[numpy.int64], list]) – of weight values corresponding toon_key

  • version_key (int) – Integer representation of version key for compatibility with the network.

  • 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 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 weight commitment is successful, False otherwise. msg is a string value describing the success or potential error.

Return type:

tuple[bool, str]

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.

async determine_block_hash(block, block_hash=None, reuse_block=False)[source]#

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.

Parameters:
  • block (Optional[int]) – The block number to get the hash for. Do not specify if using block_hash or reuse_block.

  • block_hash (Optional[str]) – The hash of the blockchain block. 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 or reuse_block.

Returns:

The block hash if one can be determined, None otherwise.

Return type:

Optional[str]

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)
async difficulty(netuid, block=None, block_hash=None, reuse_block=False)[source]#

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.

Parameters:
  • netuid (int) – The unique identifier of the subnet.

  • block (Optional[int]) – The block number for the query. Do not specify if using block_hash or reuse_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.

Returns:

The value of the ‘Difficulty’ hyperparameter if the subnet exists, None otherwise.

Return type:

Optional[int]

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)
async does_hotkey_exist(hotkey_ss58, block=None, block_hash=None, reuse_block=False)[source]#

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.

Parameters:
  • hotkey_ss58 (str) – The SS58 address of the hotkey.

  • 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 number to check the hotkey against. Do not specify if using reuse_block or block.

  • reuse_block (bool) – 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.

Return type:

bool

Example

Check if hotkey exists:

exists = await subtensor.does_hotkey_exist(hotkey_ss58="5F...")

Check at specific block:

exists = await subtensor.does_hotkey_exist(hotkey_ss58="5F...", block=1000000)
async encode_params(call_definition, params)[source]#

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.

Parameters:
  • call_definition (dict[str, list[bittensor.core.types.ParamWithTypes]]) – A dictionary containing parameter type definitions. Should have a “params” key with a list of parameter definitions.

  • params (Union[list[Any], dict[str, Any]]) – The actual parameter values to encode. Can be either a list (for positional parameters) or a dictionary (for named parameters).

Returns:

A hex-encoded string representation of the parameters.

Return type:

str

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_definition=call_def, params=params_dict)

# Or encode as a list (positional)
params_list = [1000000, "5F..."]
encoded = await subtensor.encode_params(call_definition=call_def, params=params_list)
async filter_netuids_by_registered_hotkeys(all_netuids, filter_for_netuids, all_hotkeys, block=None, block_hash=None, reuse_block=False)[source]#

Filters a given list of all netuids for certain specified netuids and hotkeys

Parameters:
  • 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[bittensor_wallet.Wallet]) – Hotkeys to filter from the main list.

  • block (Optional[int]) – The blockchain block number for the query.

  • block_hash (Optional[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.

Returns:

The filtered list of netuids.

Return type:

list[int]

async get_all_commitments(netuid, block=None, block_hash=None, reuse_block=False)[source]#

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.

Parameters:
  • 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.

  • 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:

A mapping of the ss58:commitment with the commitment as a string.

Return type:

dict[str, str]

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}")
async get_all_metagraphs_info(block=None, block_hash=None, reuse_block=False)[source]#

Retrieves a list of MetagraphInfo objects for all subnets

Parameters:
  • 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 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.

Returns:

MetagraphInfo dataclass

Return type:

list[bittensor.core.chain_data.MetagraphInfo]

async get_all_neuron_certificates(netuid, block=None, block_hash=None, reuse_block=False)#

Retrieves the TLS certificates for neurons within a specified subnet (netuid) of the Bittensor network.

Parameters:
  • 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 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.

Returns:

Certificate} for the key/Certificate pairs on the subnet

Return type:

{ss58

This function is used for certificate discovery for setting up mutual tls communication between neurons.

async get_all_revealed_commitments(netuid, block=None, block_hash=None, reuse_block=False)#

Returns all revealed commitments for a given netuid.

Parameters:
  • 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.

Returns:

A dictionary of all revealed commitments in view {ss58_address: (reveal block, commitment message)}.

Return type:

result

Example of result:
{
    "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY": ( (12, "Alice message 1"), (152, "Alice message 2") ),
    "5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty": ( (12, "Bob message 1"), (147, "Bob message 2") ),
}
async get_all_subnets_info(block=None, block_hash=None, reuse_block=False)[source]#

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:
  • block (Optional[int]) – The block number for the query.

  • block_hash (Optional[str]) – The block hash for the query.

  • reuse_block (bool) – Whether to reuse the last-used block hash.

Returns:

A list of SubnetInfo objects, each containing detailed information about a subnet.

Return type:

list[SubnetInfo]

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.

async get_balance(address, block=None, block_hash=None, reuse_block=False)[source]#

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.

Parameters:
  • address (str) – The coldkey address in SS58 format.

  • block (Optional[int]) – The block number for the query.

  • block_hash (Optional[str]) – The block hash for the query.

  • reuse_block (bool) – Whether to reuse the last-used block hash.

Returns:

The balance object containing the account’s TAO balance.

Return type:

Balance

Example

Get balance for an address:

balance = await subtensor.get_balance(address="5F...")
print(f"Balance: {balance.tao} TAO")

Get balance at specific block:

balance = await subtensor.get_balance(address="5F...", block=1000000)
async get_balances(*addresses, block=None, block_hash=None, reuse_block=False)[source]#

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.

Parameters:
  • *addresses (str) – Variable number of coldkey addresses in SS58 format.

  • block (Optional[int]) – The block number for the query.

  • block_hash (Optional[str]) – The block hash for the query.

  • reuse_block (bool) – Whether to reuse the last-used block hash.

Returns:

A dictionary mapping each address to its Balance object.

Return type:

dict[str, Balance]

Example

Get balances for multiple addresses:

balances = await subtensor.get_balances("5F...", "5G...", "5H...")
async get_block_hash(block=None)[source]#

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.

Parameters:

block (Optional[int]) – The block number for which the hash is to be retrieved. If None, returns the latest block hash.

Returns:

The cryptographic hash of the specified block.

Return type:

str

Example

# Get hash for specific block block_hash = await subtensor.get_block_hash(block=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}”)

async get_children(hotkey, netuid, block=None, block_hash=None, reuse_block=False)[source]#

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.

Parameters:
  • 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.

Returns:

A tuple containing a boolean indicating success or failure, a list of formatted children with their proportions, and an error message (if applicable).

Return type:

tuple[bool, list[tuple[float, str]], str]

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}”)

async get_children_pending(hotkey, netuid, block=None, block_hash=None, reuse_block=False)#

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.

Parameters:
  • 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.

Returns:

A list of children with their proportions. int: The cool-down block number.

Return type:

list[tuple[float, str]]

async get_commitment(netuid, uid, block=None, block_hash=None, reuse_block=False)[source]#

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.

Parameters:
  • 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.

  • 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:

The commitment data as a string.

Return type:

str

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

)

async get_current_block()[source]#

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:

The current chain block number.

Return type:

int

Example

Get current block number:

current_block = await subtensor.get_current_block()
print(f"Current block: {current_block}")

Check if network has progressed past a milestone:

block = await subtensor.get_current_block()
if block > 1000000:
    print("Network has progressed past block 1M")
async get_current_weight_commit_info(netuid, block=None, block_hash=None, reuse_block=False)[source]#

Retrieves CRV3 weight commit information for a specific subnet.

Parameters:
  • 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.

Returns:

A list of commit details, where each entry is a dictionary with keys ‘who’, ‘serialized_commit’, and ‘reveal_round’, or an empty list if no data is found.

Return type:

list

async get_delegate_by_hotkey(hotkey_ss58, block=None, block_hash=None, reuse_block=False)[source]#

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.

Parameters:
  • 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.

Returns:

Detailed information about the delegate neuron, None if not found.

Return type:

Optional[DelegateInfo]

This function is essential for understanding the roles and influence of delegate neurons within the Bittensor network’s consensus and governance structures.

async get_delegate_identities(block=None, block_hash=None, reuse_block=False)[source]#

Fetches delegates identities from the chain.

Parameters:
  • block (Optional[int]) – The blockchain block number for the query.

  • block_hash (Optional[str]) – the hash of the blockchain block for the query

  • reuse_block (bool) – Whether to reuse the last-used blockchain block hash.

Returns:

ChainIdentity, …}

Return type:

Dict {ss58

async get_delegate_take(hotkey_ss58, block=None, block_hash=None, reuse_block=False)[source]#

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.

Parameters:
  • 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.

Returns:

The delegate take percentage.

Return type:

float

The delegate take is a critical parameter in the network’s incentive structure, influencing the distribution of rewards among neurons and their nominators.

async get_delegated(coldkey_ss58, block=None, block_hash=None, reuse_block=False)[source]#

Retrieves a list of delegates and their associated stakes for a given coldkey. This function identifies the delegates that a specific account has staked tokens on.

Parameters:
  • 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.

Returns:

A list of tuples, each containing a delegate’s information and staked amount.

Return type:

list[tuple[bittensor.core.chain_data.DelegateInfo, bittensor.utils.balance.Balance]]

This function is important for account holders to understand their stake allocations and their involvement in the network’s delegation and consensus mechanisms.

async get_delegates(block=None, block_hash=None, reuse_block=False)[source]#

Fetches all delegates on the chain

Parameters:
  • block (Optional[int]) – The blockchain block number for the query.

  • block_hash (Optional[str]) – hash of the blockchain block number for the query.

  • reuse_block (bool) – whether to reuse the last-used block hash.

Returns:

List of DelegateInfo objects, or an empty list if there are no delegates.

Return type:

list[bittensor.core.chain_data.DelegateInfo]

async get_existential_deposit(block=None, block_hash=None, reuse_block=False)[source]#

Retrieves the existential deposit amount for the Bittensor blockchain. The existential deposit is the minimum amount of TAO required for an account to exist on the blockchain. Accounts with balances below this threshold can be reaped to conserve network resources.

Parameters:
  • block (Optional[int]) – The blockchain block number for the query.

  • block_hash (Optional[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.

Returns:

The existential deposit amount.

Return type:

bittensor.utils.balance.Balance

The existential deposit is a fundamental economic parameter in the Bittensor network, ensuring efficient use of storage and preventing the proliferation of dust accounts.

async get_hotkey_owner(hotkey_ss58, block=None, block_hash=None, reuse_block=False)[source]#

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.

Parameters:
  • 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.

Returns:

The SS58 address of the owner if the hotkey exists, or None if it doesn’t.

Return type:

Optional[str]

get_hotkey_stake#
async get_hyperparameter(param_name, netuid, block=None, block_hash=None, reuse_block=False)[source]#

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.

Parameters:
  • param_name (str) – 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 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 (bool) – Whether to reuse the last-used block hash. Do not set if using block_hash or block.

Returns:

The value of the specified hyperparameter if the subnet exists, None otherwise.

Return type:

Optional[Any]

Example

Get difficulty for subnet 1:

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)

Get immunity period using block hash:

immunity = await subtensor.get_hyperparameter(param_name="ImmunityPeriod", netuid=1, block_hash="0x1234...")
async get_last_commitment_bonds_reset_block(netuid, uid)#

Retrieves the last block number when the bonds reset were triggered by publish_metadata for a specific neuron.

Parameters:
  • netuid (int) – The unique identifier of the subnetwork.

  • uid (int) – The unique identifier of the neuron.

Returns:

The block number when the bonds were last reset, or None if not found.

Return type:

Optional[int]

async get_liquidity_list(wallet, netuid, block=None, block_hash=None, reuse_block=False)#

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.

Parameters:
  • wallet (bittensor_wallet.Wallet) – Wallet instance to fetch positions for.

  • netuid (int) – Subnet unique id.

  • block (Optional[int]) – The blockchain block number for the query.

  • 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.

Returns:

List of liquidity positions, or None if subnet does not exist.

Return type:

Optional[list[bittensor.utils.liquidity.LiquidityPosition]]

async get_metagraph_info(netuid, field_indices=None, block=None, block_hash=None, reuse_block=False)[source]#

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.

Parameters:
  • netuid (int) – The unique identifier of the subnet to query.

  • field_indices (Optional[Union[list[bittensor.core.chain_data.SelectiveMetagraphIndex], list[int]]]) – An optional list of SelectiveMetagraphIndex or int values specifying which fields to retrieve. If not provided, all available fields will be returned.

  • 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 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.

Returns:

A MetagraphInfo object containing the requested subnet data, or None if the subnet

with the given netuid does not exist.

Return type:

Optional[MetagraphInfo]

Example

meta_info = await subtensor.get_metagraph_info(netuid=2)

partial_meta_info = await subtensor.get_metagraph_info(

netuid=2, field_indices=[SelectiveMetagraphIndex.Name, SelectiveMetagraphIndex.OwnerHotkeys]

)

async get_minimum_required_stake()[source]#

Returns the minimum required stake for nominators in the Subtensor network.

Returns:

The minimum required stake as a Balance object.

Return type:

Balance

async get_netuids_for_hotkey(hotkey_ss58, block=None, block_hash=None, reuse_block=False)[source]#

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.

Parameters:
  • 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 at which to perform the query.

  • reuse_block (bool) – Whether to reuse the last-used block hash when retrieving info.

Returns:

A list of netuids where the neuron is a member.

Return type:

list[int]

async get_neuron_certificate(hotkey, netuid, block=None, block_hash=None, reuse_block=False)[source]#

Retrieves the TLS certificate for a specific neuron identified by its unique identifier (UID) within a specified subnet (netuid) of the Bittensor network.

Parameters:
  • hotkey (str) – The hotkey to query.

  • 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 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.

Returns:

the certificate of the neuron if found, None otherwise.

Return type:

Optional[bittensor.utils.Certificate]

This function is used for certificate discovery for setting up mutual tls communication between neurons.

async get_neuron_for_pubkey_and_subnet(hotkey_ss58, netuid, block=None, block_hash=None, reuse_block=False)[source]#

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.

Parameters:
  • 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.

  • block_hash (Optional[str]) – The blockchain block number at which to perform the query.

  • reuse_block (bool) – Whether to reuse the last-used blockchain block hash.

Returns:

Detailed information about the neuron if found,

None otherwise.

Return type:

Optional[bittensor.core.chain_data.neuron_info.NeuronInfo]

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.

async get_next_epoch_start_block(netuid, block=None, block_hash=None, reuse_block=False)#

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.

Parameters:
  • netuid (int) – The unique identifier of the subnet.

  • block (Optional[int]) – The reference block to calculate from. If None, uses the current chain block height.

  • block_hash (Optional[str]) – The blockchain block number at which to perform the query.

  • reuse_block (bool) – Whether to reuse the last-used blockchain block hash.

Returns:

The block number at which the next epoch will start.

Return type:

int

async get_owned_hotkeys(coldkey_ss58, block=None, block_hash=None, reuse_block=False)#

Retrieves all hotkeys owned by a specific coldkey address.

Parameters:
  • coldkey_ss58 (str) – The SS58 address of the coldkey 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 block hash.

Returns:

A list of hotkey SS58 addresses owned by the coldkey.

Return type:

list[str]

async get_parents(hotkey, netuid, block=None, block_hash=None, reuse_block=False)#

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.

Parameters:
  • hotkey (str) – The child hotkey SS58.

  • 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.

Returns:

A list of formatted parents [(proportion, parent)]

Return type:

list[tuple[float, str]]

async get_revealed_commitment(netuid, uid, block=None)#

Returns uid related revealed commitment for a given netuid.

Parameters:
  • 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.

Returns:

A tuple of reveal block and commitment message.

Return type:

result (Optional[tuple[int, str]]

Example of result:

( (12, “Alice message 1”), (152, “Alice message 2”) ) ( (12, “Bob message 1”), (147, “Bob message 2”) )

async get_revealed_commitment_by_hotkey(netuid, hotkey_ss58_address=None, block=None, block_hash=None, reuse_block=False)#

Returns hotkey related revealed commitment for a given netuid.

Parameters:
  • netuid (int) – The unique identifier of the subnetwork.

  • block (Optional[int]) – The block number to retrieve the commitment from. Default is None.

  • hotkey_ss58_address (Optional[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.

Returns:

A tuple of reveal block and commitment message.

Return type:

result (tuple[int, str)

async get_stake(coldkey_ss58, hotkey_ss58, netuid, block=None, block_hash=None, reuse_block=False)[source]#

Returns the stake under a coldkey - hotkey pairing.

Parameters:
  • hotkey_ss58 (str) – The SS58 address of the hotkey.

  • coldkey_ss58 (str) – The SS58 address of the coldkey.

  • netuid (int) – 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

  • reuse_block (bool) – Whether to use the last-used block. Do not set if using block_hash or block.

Returns:

The stake under the coldkey - hotkey pairing.

Return type:

Balance

async get_stake_add_fee(amount, netuid, coldkey_ss58, hotkey_ss58, block=None)#

Calculates the fee for adding new stake to a hotkey.

Parameters:
  • amount (bittensor.utils.balance.Balance) – Amount of stake to add in TAO

  • netuid (int) – Netuid of subnet

  • coldkey_ss58 (str) – SS58 address of source coldkey

  • hotkey_ss58 (str) – SS58 address of destination hotkey

  • block (Optional[int]) – Block number at which to perform the calculation

Returns:

The calculated stake fee as a Balance object

Return type:

bittensor.utils.balance.Balance

async get_stake_for_coldkey(coldkey_ss58, block=None, block_hash=None, reuse_block=False)[source]#

Retrieves the stake information for a given coldkey.

Parameters:
  • 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.

Returns:

An optional list of StakeInfo objects, or None if no stake information is found.

Return type:

Optional[list[bittensor.core.chain_data.StakeInfo]]

async get_stake_for_coldkey_and_hotkey(coldkey_ss58, hotkey_ss58, netuids=None, block=None, block_hash=None, reuse_block=False)[source]#

Retrieves all coldkey-hotkey pairing stake across specified (or all) subnets

Parameters:
  • coldkey_ss58 (str) – The SS58 address of the coldkey.

  • hotkey_ss58 (str) – 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 or reuse_block

  • reuse_block (bool) – Whether to use the last-used block. Do not set if using block_hash or block.

Returns:

StakeInfo} pairing of all stakes across all subnets.

Return type:

A {netuid

async get_stake_for_hotkey(hotkey_ss58, netuid, block=None, block_hash=None, reuse_block=False)[source]#

Retrieves the stake information for a given hotkey.

Parameters:
  • hotkey_ss58 (str) – The SS58 address of the hotkey.

  • netuid (int) – The subnet ID to query for.

  • block (Optional[int]) – The block number at which to query the stake information. Do not specify if also specifying block_hash or reuse_block.

  • block_hash (Optional[str]) – The hash of the blockchain block number for the query. Do not specify if also specifying block or reuse_block.

  • reuse_block (bool) – Whether to reuse for this query the last-used block. Do not specify if also specifying block or block_hash.

Return type:

bittensor.utils.balance.Balance

get_stake_info_for_coldkey#
async get_stake_movement_fee(amount, origin_netuid, origin_hotkey_ss58, origin_coldkey_ss58, destination_netuid, destination_hotkey_ss58, destination_coldkey_ss58, block=None)#

Calculates the fee for moving stake between hotkeys/subnets/coldkeys.

Parameters:
  • amount (bittensor.utils.balance.Balance) – Amount of stake to move in TAO

  • origin_netuid (int) – Netuid of source subnet

  • origin_hotkey_ss58 (str) – SS58 address of source hotkey

  • origin_coldkey_ss58 (str) – SS58 address of source coldkey

  • destination_netuid (int) – Netuid of destination subnet

  • destination_hotkey_ss58 (str) – SS58 address of destination hotkey

  • destination_coldkey_ss58 (str) – SS58 address of destination coldkey

  • block (Optional[int]) – Block number at which to perform the calculation

Returns:

The calculated stake fee as a Balance object

Return type:

bittensor.utils.balance.Balance

async get_stake_operations_fee(amount, netuid, block=None, block_hash=None, reuse_block=False)#

Returns fee for any stake operation in specified subnet.

Parameters:
  • amount (bittensor.utils.balance.Balance) – Amount of stake to add in Alpha/TAO.

  • netuid (int) – Netuid of subnet.

  • block (Optional[int]) – The block number at which to query the stake information. Do not specify if also specifying block_hash or reuse_block.

  • block_hash (Optional[str]) – The hash of the blockchain block number for the query. Do not specify if also specifying block or reuse_block.

  • reuse_block (bool) – Whether to reuse for this query the last-used block. Do not specify if also specifying block or block_hash.

Returns:

The calculated stake fee as a Balance object.

async get_subnet_burn_cost(block=None, block_hash=None, reuse_block=False)[source]#
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

Parameters:
  • block (Optional[int]) – The blockchain block number for the query.

  • block_hash (Optional[str]) – The blockchain block_hash of the block id.

  • reuse_block (bool) – Whether to reuse the last-used block hash.

Returns:

The burn cost for subnet registration.

Return type:

int

The subnet burn cost is an important economic parameter, reflecting the network’s mechanisms for controlling

the proliferation of subnets and ensuring their commitment to the network’s long-term viability.

async get_subnet_hyperparameters(netuid, block=None, block_hash=None, reuse_block=False)[source]#

Retrieves the hyperparameters for a specific subnet within the Bittensor network. These hyperparameters define the operational settings and rules governing the subnet’s behavior.

Parameters:
  • 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.

Returns:

The subnet’s hyperparameters, or None if not available.

Return type:

Optional[bittensor.core.chain_data.SubnetHyperparameters]

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.

async get_subnet_info(netuid, block=None, block_hash=None, reuse_block=False)#

Retrieves detailed information about subnet within the Bittensor network. This function provides comprehensive data on subnet, including its characteristics and operational parameters.

Parameters:
  • 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 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.

Returns:

A SubnetInfo objects, each containing detailed information about a subnet.

Return type:

SubnetInfo

Gaining insights into the subnet’s details assists in understanding the network’s composition, the roles of different subnets, and their unique features.

async get_subnet_owner_hotkey(netuid, block=None)#

Retrieves the hotkey of the subnet owner for a given network UID.

This function queries the subtensor network to fetch the hotkey of the owner of a subnet specified by its netuid. If no data is found or the query fails, the function returns None.

Parameters:
  • netuid (int) – The network UID of the subnet to fetch the owner’s hotkey for.

  • block (Optional[int]) – The specific block number to query the data from.

Returns:

The hotkey of the subnet owner if available; None otherwise.

Return type:

Optional[str]

async get_subnet_price(netuid, block=None, block_hash=None, reuse_block=False)#

Gets the current Alpha price in TAO for all subnets.

Parameters:
  • 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 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.

Returns:

The current Alpha price in TAO units for the specified subnet.

Return type:

bittensor.utils.balance.Balance

async get_subnet_prices(block=None, block_hash=None, reuse_block=False)#

Gets the current Alpha price in TAO for a specified subnet.

Parameters:
  • block (Optional[int]) – 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 or reuse_block

  • reuse_block (bool) – Whether to use the last-used block. Do not set if using block_hash or block.

Returns:

  • subnet unique ID

  • The current Alpha price in TAO units for the specified subnet.

Return type:

dict

async get_subnet_reveal_period_epochs(netuid, block=None, block_hash=None)[source]#

Retrieve the SubnetRevealPeriodEpochs hyperparameter.

Parameters:
  • netuid (int)

  • block (Optional[int])

  • block_hash (Optional[str])

Return type:

int

async get_subnet_validator_permits(netuid, block=None)#

Retrieves the list of validator permits for a given subnet as boolean values.

Parameters:
  • netuid (int) – The unique identifier of the subnetwork.

  • block (Optional[int]) – The blockchain block number for the query.

Returns:

A list of boolean values representing validator permits, or None if not available.

Return type:

Optional[list[bool]]

async get_subnets(block=None, block_hash=None, reuse_block=False)[source]#

Retrieves the list of all subnet unique identifiers (netuids) currently present in the Bittensor network.

Parameters:
  • 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.

Returns:

A list of subnet netuids.

Return type:

list[int]

This function provides a comprehensive view of the subnets within the Bittensor network, offering insights into its diversity and scale.

async get_timestamp(block=None, block_hash=None, reuse_block=False)#

Retrieves the datetime timestamp for a given block.

Parameters:
  • block (Optional[int]) – The blockchain block number for the query. Do not specify if specifying block_hash or reuse_block.

  • block_hash (Optional[str]) – The blockchain block_hash representation of the block id. Do not specify if specifying block or reuse_block.

  • reuse_block (bool) – Whether to reuse the last-used blockchain block hash. Do not specify if specifying block or block_hash.

Returns:

datetime object for the timestamp of the block.

Return type:

datetime.datetime

async get_total_subnets(block=None, block_hash=None, reuse_block=False)[source]#

Retrieves the total number of subnets within the Bittensor network as of a specific blockchain block.

Parameters:
  • 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.

Returns:

The total number of subnets in the network.

Return type:

Optional[str]

Understanding the total number of subnets is essential for assessing the network’s growth and the extent of its decentralized infrastructure.

async get_transfer_fee(wallet, dest, value)[source]#

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.

Parameters:
  • wallet (bittensor_wallet.Wallet) – The wallet from which the transfer is initiated.

  • dest (str) – The SS58 address of the destination account.

  • value (bittensor.utils.balance.Balance) – The amount of tokens to be transferred, specified as a Balance object, or in Tao (float) or Rao (int) units.

Returns:

The estimated transaction fee for the transfer, represented as a Balance

object.

Return type:

bittensor.utils.balance.Balance

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.

async get_uid_for_hotkey_on_subnet(hotkey_ss58, netuid, block=None, block_hash=None, reuse_block=False)[source]#

Retrieves the unique identifier (UID) for a neuron’s hotkey on a specific subnet.

Parameters:
  • 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.

  • 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.

Returns:

The UID of the neuron if it is registered on the subnet, None otherwise.

Return type:

Optional[int]

The UID is a critical identifier within the network, linking the neuron’s hotkey to its operational and governance activities on a particular subnet.

async get_unstake_fee(amount, netuid, coldkey_ss58, hotkey_ss58, block=None)#

Calculates the fee for unstaking from a hotkey.

Parameters:
  • amount (bittensor.utils.balance.Balance) – Amount of stake to unstake in TAO

  • netuid (int) – Netuid of subnet

  • coldkey_ss58 (str) – SS58 address of source coldkey

  • hotkey_ss58 (str) – SS58 address of destination hotkey

  • block (Optional[int]) – Block number at which to perform the calculation

Returns:

The calculated stake fee as a Balance object

Return type:

bittensor.utils.balance.Balance

async get_vote_data(proposal_hash, block=None, block_hash=None, reuse_block=False)[source]#

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.

Parameters:
  • 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_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.

Returns:

An object containing the proposal’s voting data, or None if not found.

Return type:

Optional[bittensor.core.chain_data.ProposalVoteData]

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.

async immunity_period(netuid, block=None, block_hash=None, reuse_block=False)[source]#

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.

Parameters:
  • 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.

  • reuse_block (bool) – Whether to reuse the last-used blockchain block hash.

Returns:

The value of the ‘ImmunityPeriod’ hyperparameter if the subnet exists, None otherwise.

Return type:

Optional[int]

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.

async initialize()[source]#

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:

The initialized instance (self) for method chaining.

Return type:

AsyncSubtensor

Raises:

ConnectionError – If unable to connect to the blockchain due to timeout or connection refusal.

Example

Initialize the connection:

subtensor = AsyncSubtensor(network="finney")
await subtensor.initialize()

balance = await subtensor.get_balance(address="5F...")

Or chain the initialization:

subtensor = await AsyncSubtensor(network="finney").initialize()
async is_fast_blocks()#

Returns True if the node is running with fast blocks. False if not.

async is_hotkey_delegate(hotkey_ss58, block=None, block_hash=None, reuse_block=False)[source]#

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.

Parameters:
  • 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.

  • reuse_block (bool) – Whether to reuse the last-used block hash.

Returns:

True if the hotkey is a delegate, False otherwise.

Return type:

bool

Being a delegate is a significant status within the Bittensor network, indicating a neuron’s involvement in consensus and governance processes.

async is_hotkey_registered(hotkey_ss58, netuid=None, block=None, block_hash=None, reuse_block=False)[source]#

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.

Parameters:
  • hotkey_ss58 (str) – The SS58 address of the neuron’s hotkey.

  • netuid (Optional[int]) – The unique identifier of the subnet to check the registration. If None, the registration is checked across all subnets.

  • block (Optional[int]) – The blockchain block number at which to perform the query.

  • block_hash (Optional[str]) – 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.

Returns:

True if the hotkey is registered in the specified context (either any subnet or a specific subnet),

False otherwise.

Return type:

bool

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.

async is_hotkey_registered_any(hotkey_ss58, block=None, block_hash=None, reuse_block=False)[source]#

Checks if a neuron’s hotkey is registered on any subnet within the Bittensor network.

Parameters:
  • 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.

Returns:

True if the hotkey is registered on any subnet, False otherwise.

Return type:

bool

This function is essential for determining the network-wide presence and participation of a neuron.

async is_hotkey_registered_on_subnet(hotkey_ss58, netuid, block=None, block_hash=None, reuse_block=False)[source]#

Checks if the hotkey is registered on a given netuid.

Parameters:
  • hotkey_ss58 (str)

  • netuid (int)

  • block (Optional[int])

  • block_hash (Optional[str])

  • reuse_block (bool)

Return type:

bool

async is_subnet_active(netuid, block=None, block_hash=None, reuse_block=False)#

Verify if subnet with provided netuid is active.

Parameters:
  • 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.

Returns:

True if subnet is active, False otherwise.

Return type:

bool

Note: This means whether the start_call was initiated or not.

async last_drand_round()[source]#

Retrieves the last drand round emitted in bittensor. This corresponds when committed weights will be revealed.

Returns:

The latest Drand round emitted in bittensor.

Return type:

int

log_verbose = False#
async max_weight_limit(netuid, block=None, block_hash=None, reuse_block=False)[source]#

Returns network MaxWeightsLimit hyperparameter.

Parameters:
  • 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.

Returns:

The value of the MaxWeightsLimit hyperparameter, or None if the subnetwork does not

exist or the parameter is not found.

Return type:

Optional[float]

async metagraph(netuid, lite=True, block=None)[source]#

Returns a synced metagraph for a specified subnet within the Bittensor network. The metagraph represents the network’s structure, including neuron connections and interactions.

Parameters:
  • 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.

Returns:

The metagraph representing the subnet’s structure and neuron

relationships.

Return type:

bittensor.core.metagraph.Metagraph

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.

async min_allowed_weights(netuid, block=None, block_hash=None, reuse_block=False)[source]#

Returns network MinAllowedWeights hyperparameter.

Parameters:
  • 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.

Returns:

The value of the MinAllowedWeights hyperparameter, or None if the subnetwork does not

exist or the parameter is not found.

Return type:

Optional[int]

async modify_liquidity(wallet, netuid, position_id, liquidity_delta, hotkey=None, wait_for_inclusion=True, wait_for_finalization=False, period=None)#

Modifies liquidity in liquidity position by adding or removing liquidity from it.

Parameters:
  • wallet (bittensor_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.

  • position_id (int) – The id of the position record in the pool.

  • liquidity_delta (bittensor.utils.balance.Balance) – The amount of liquidity to be added or removed (add if positive or remove if negative).

  • hotkey (Optional[str]) – The hotkey with staked TAO in Alpha. If not passed then the wallet hotkey is used. Defaults to None.

  • wait_for_inclusion (bool) – Whether to wait for the extrinsic to be included in a block. Defaults to True.

  • wait_for_finalization (bool) – 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.

Returns:

  • 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.

Return type:

Tuple[bool, str]

Example

import bittensor as bt

subtensor = bt.AsyncSubtensor(network="local")
await subtensor.initialize()

my_wallet = bt.Wallet()

# if `liquidity_delta` is negative
my_liquidity_delta = Balance.from_tao(100) * -1
await subtensor.modify_liquidity(
    wallet=my_wallet,
    netuid=123,
    position_id=2,
    liquidity_delta=my_liquidity_delta
)

# if `liquidity_delta` is positive
my_liquidity_delta = Balance.from_tao(120)
await subtensor.modify_liquidity(
    wallet=my_wallet,
    netuid=123,
    position_id=2,
    liquidity_delta=my_liquidity_delta
)
Note: Modifying is allowed even when user liquidity is enabled in specified subnet. Call toggle_user_liquidity

to enable/disable user liquidity.

async move_stake(wallet, origin_hotkey, origin_netuid, destination_hotkey, destination_netuid, amount, wait_for_inclusion=True, wait_for_finalization=False, period=None)[source]#

Moves stake to a different hotkey and/or subnet.

Parameters:
  • wallet (bittensor_wallet.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 (bittensor.utils.balance.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 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 stake movement was successful.

Return type:

success

async neuron_for_uid(uid, netuid, block=None, block_hash=None, reuse_block=False)[source]#

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.

Parameters:
  • uid (Optional[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 (Optional[str]) – The hash of the blockchain block number for the query.

  • reuse_block (bool) – Whether to reuse the last-used blockchain block hash.

Returns:

Detailed information about the neuron if found, a null neuron otherwise

Return type:

bittensor.core.chain_data.NeuronInfo

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.

async neurons(netuid, block=None, block_hash=None, reuse_block=False)[source]#

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.

Parameters:
  • 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 for the query.

  • reuse_block (bool) – Whether to reuse the last-used blockchain block hash.

Returns:

A list of NeuronInfo objects detailing each neuron’s characteristics in the subnet.

Return type:

list[bittensor.core.chain_data.NeuronInfo]

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.

async neurons_lite(netuid, block=None, block_hash=None, reuse_block=False)[source]#

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.

Parameters:
  • 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 for the query.

  • reuse_block (bool) – Whether to reuse the last-used blockchain block hash.

Returns:

A list of simplified neuron information for the subnet.

Return type:

list[bittensor.core.chain_data.NeuronInfoLite]

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.

async query_constant(module_name, constant_name, block=None, block_hash=None, reuse_block=False)[source]#

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.

Parameters:
  • module_name (str) – The name of the module containing the constant (e.g., “Balances”, “SubtensorModule”).

  • constant_name (str) – 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:

The value of the constant if found, None otherwise.

Return type:

Optional[async_substrate_interface.types.ScaleObj]

Example

Get existential deposit constant:

existential_deposit = await subtensor.query_constant(
    module_name="Balances",
    constant_name="ExistentialDeposit"
)

Get constant at specific block:

constant = await subtensor.query_constant(
    module_name="SubtensorModule",
    constant_name="SomeConstant",
    block=1000000
)
async query_identity(coldkey_ss58, block=None, block_hash=None, reuse_block=False)[source]#

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.

Parameters:
  • coldkey_ss58 (str) – 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 (Optional[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.

Returns:

An object containing the identity information of the neuron if found, None otherwise.

Return type:

Optional[bittensor.core.chain_data.chain_identity.ChainIdentity]

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 parameters.

async query_map(module, name, block=None, block_hash=None, reuse_block=False, params=None)[source]#

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.

Parameters:
  • module (str) – The name of the module from which to query the map storage (e.g., “SubtensorModule”, “System”).

  • name (str) – 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:

A data structure representing the map storage if found, None otherwise.

Return type:

AsyncQueryMapResult

Example

Query bonds for subnet 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)
async query_map_subtensor(name, block=None, block_hash=None, reuse_block=False, params=None)[source]#

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.

Parameters:
  • name (str) – The name of the map storage function to query.

  • block (Optional[int]) – The blockchain block number at which to perform the query.

  • 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.

  • params (Optional[list]) – A list of parameters to pass to the query function.

Returns:

An object containing the map-like data structure, or None if not found.

Return type:

async_substrate_interface.AsyncQueryMapResult

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.

async query_module(module, name, block=None, block_hash=None, reuse_block=False, params=None)[source]#

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.

Parameters:
  • 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.

  • 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.

  • params (Optional[list]) – A list of parameters to pass to the query function.

Returns:

An object containing the requested data if found, None otherwise.

Return type:

Optional[Union[async_substrate_interface.types.ScaleObj, Any]]

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.

async query_runtime_api(runtime_api, method, params, block=None, block_hash=None, reuse_block=False)[source]#

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.

Parameters:
  • runtime_api (str) – The name of the runtime API to query.

  • method (str) – The specific method within the runtime API to call.

  • params (Optional[Union[list[Any], dict[str, Any]]]) – The parameters to pass to the method call.

  • 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 at which to perform 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.

Returns:

The decoded result from the runtime API call, or None if the call fails.

Return type:

Optional[Any]

This function enables access to the deeper layers of the Bittensor blockchain, allowing for detailed and specific interactions with the network’s runtime environment.

async query_subtensor(name, block=None, block_hash=None, reuse_block=False, params=None)[source]#

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.

Parameters:
  • name (str) – The name of the storage function to query.

  • block (Optional[int]) – The blockchain block number at which to perform the query.

  • 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.

  • params (Optional[list]) – A list of parameters to pass to the query function.

Returns:

An object containing the requested data.

Return type:

query_response

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.

async recycle(netuid, block=None, block_hash=None, reuse_block=False)[source]#

Retrieves the ‘Burn’ hyperparameter for a specified subnet. The ‘Burn’ parameter represents the amount of Tao that is effectively recycled within the Bittensor network.

Parameters:
  • 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 for the query.

  • reuse_block (bool) – Whether to reuse the last-used blockchain block hash.

Returns:

The value of the ‘Burn’ hyperparameter if the subnet exists, None otherwise.

Return type:

Optional[Balance]

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.

async register(wallet, netuid, wait_for_inclusion=False, wait_for_finalization=True, max_allowed_attempts=3, output_in_place=False, cuda=False, dev_id=0, tpb=256, num_processes=None, update_interval=None, log_verbose=False, period=None)[source]#

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.

Parameters:
  • wallet (bittensor_wallet.Wallet) – The wallet associated with the neuron to be registered.

  • netuid (int) – 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

  • 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 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 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 registration is successful, False otherwise.

Return type:

bool

This function facilitates the entry of new neurons into the network, supporting the decentralized growth and scalability of the Bittensor ecosystem.

async register_subnet(wallet, wait_for_inclusion=False, wait_for_finalization=True, period=None)[source]#

Registers a new subnetwork on the Bittensor network.

Parameters:
  • 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, os 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 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.

Returns:

True if the subnet registration was successful, False otherwise.

Return type:

bool

async remove_liquidity(wallet, netuid, position_id, hotkey=None, wait_for_inclusion=True, wait_for_finalization=False, period=None)#

Remove liquidity and credit balances back to wallet’s hotkey stake.

Parameters:
  • wallet (bittensor_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.

  • position_id (int) – The id of the position record in the pool.

  • hotkey (Optional[str]) – The hotkey with staked TAO in Alpha. If not passed then the wallet hotkey is used. Defaults to None.

  • wait_for_inclusion (bool) – Whether to wait for the extrinsic to be included in a block. Defaults to True.

  • wait_for_finalization (bool) – 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.

Returns:

  • 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.

Return type:

Tuple[bool, str]

Note

  • Adding is allowed even when user liquidity is enabled in specified subnet. Call toggle_user_liquidity

    extrinsic to enable/disable user liquidity.

  • To get the position_id use get_liquidity_list method.

async reveal_weights(wallet, netuid, uids, weights, salt, version_key=version_as_int, wait_for_inclusion=False, wait_for_finalization=False, max_retries=5, period=None)[source]#

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.

Parameters:
  • wallet (bittensor_wallet.Wallet) – The wallet associated with the subnet validator revealing the weights.

  • netuid (int) – unique identifier of the subnet.

  • uids (Union[numpy.typing.NDArray[numpy.int64], list]) – NumPy array of subnet miner neuron UIDs for which weights are being revealed.

  • weights (Union[numpy.typing.NDArray[numpy.int64], list]) – NumPy array of weight values corresponding to each UID.

  • salt (Union[numpy.typing.NDArray[numpy.int64], list]) – NumPy array of salt values

  • 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 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 weight revelation is successful, False otherwise. And msg, a string

value describing the success or potential error.

Return type:

tuple[bool, str]

This function allows subnet validators to reveal their previously committed weight vector.

See also: <https://docs.learnbittensor.org/glossary#commit-reveal>,

async root_register(wallet, block_hash=None, wait_for_inclusion=True, wait_for_finalization=True, period=None)[source]#

Register neuron by recycling some TAO.

Parameters:
  • wallet (bittensor_wallet.Wallet) – Bittensor wallet instance.

  • block_hash (Optional[str]) – 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 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 registration was successful, otherwise False.

Return type:

bool

async root_set_pending_childkey_cooldown(wallet, cooldown, wait_for_inclusion=True, wait_for_finalization=True, period=None)#

Sets the pending childkey cooldown.

Parameters:
  • wallet (bittensor_wallet.Wallet) – bittensor wallet instance.

  • cooldown (int) – 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 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:

A tuple where the first element is a boolean indicating success or failure of the

operation, and the second element is a message providing additional information.

Return type:

tuple[bool, str]

Note: This operation can only be successfully performed if your wallet has root privileges.

async root_set_weights(wallet, netuids, weights, version_key=0, wait_for_inclusion=True, wait_for_finalization=True, period=None)[source]#

Set weights for the root network.

Parameters:
  • 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) – Version key for compatibility with the network. Default is 0.

  • 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. Defaults to False.

  • period (Optional[int]) – The number of blocks during which the transaction will remain valid after it’s submitted. If the

  • blocks (transaction is not included in a block within that number of)

  • rejected. (it will expire and be)

  • transaction. (You can think of it as an expiration date for the)

Returns:

True if the setting of weights is successful, False otherwise.

Return type:

bool

async serve_axon(netuid, axon, wait_for_inclusion=False, wait_for_finalization=True, certificate=None, period=None)[source]#

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.

Parameters:
  • 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.

  • wait_for_finalization (bool) – Waits for the transaction to be finalized on the blockchain. Default is True.

  • certificate (Optional[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 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 Axon serve registration is successful, False otherwise.

Return type:

bool

By registering an Axon, the neuron becomes an active part of the network’s distributed computing infrastructure, contributing to the collective intelligence of Bittensor.

async set_children(wallet, hotkey, netuid, children, wait_for_inclusion=True, wait_for_finalization=True, raise_error=False, period=None)#

Allows a coldkey to set children-keys.

Parameters:
  • 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.

  • raise_error (bool) – 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 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:

A tuple where the first element is a boolean indicating success or failure of the

operation, and the second element is a message providing additional information.

Return type:

tuple[bool, str]

Raises:
set_commitment#
async set_delegate_take(wallet, hotkey_ss58, take, wait_for_inclusion=True, wait_for_finalization=True, raise_error=False, period=None)#

Sets 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.

Parameters:
  • 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_error: Raises a relevant exception rather than returning False if unsuccessful.

  • raise_error (bool) – 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 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:

A tuple where the first element is a boolean indicating success or failure of the

operation, and the second element is a message providing additional information.

Return type:

tuple[bool, str]

Raises:
  • DelegateTakeTooHigh – Delegate take is too high.

  • DelegateTakeTooLow – Delegate take is too low.

  • DelegateTxRateLimitExceeded – A transactor exceeded the rate limit for delegate transaction.

  • HotKeyAccountNotExists – The hotkey does not exist.

  • NonAssociatedColdKey – Request to stake, unstake, or subscribe is made by a coldkey that is not associated with the hotkey account.

  • bittensor_wallet.errors.PasswordError – Decryption failed or wrong password for decryption provided.

  • 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.

async set_reveal_commitment(wallet, netuid, data, blocks_until_reveal=360, block_time=12, period=None)#

Commits arbitrary data to the Bittensor network by publishing metadata.

Parameters:
  • 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. 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 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 commitment was successful, False otherwise.

Return type:

bool

Note: A commitment can be set once per subnet epoch and is reset at the next epoch in the chain automatically.

async set_subnet_identity(wallet, netuid, subnet_identity, wait_for_inclusion=False, wait_for_finalization=True, period=None)[source]#

Sets the identity of a subnet for a specific wallet and network.

Parameters:
  • wallet (bittensor_wallet.Wallet) – The wallet instance that will authorize the transaction.

  • netuid (int) – The unique ID of the network on which the operation takes place.

  • subnet_identity (bittensor.core.chain_data.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 block.

  • wait_for_finalization (bool) – 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 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:

A tuple where the first element is a boolean indicating success or failure of the

operation, and the second element is a message providing additional information.

Return type:

tuple[bool, str]

async set_weights(wallet, netuid, uids, weights, version_key=version_as_int, wait_for_inclusion=False, wait_for_finalization=False, max_retries=5, block_time=12.0, period=8)[source]#

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.

Parameters:
  • wallet (bittensor_wallet.Wallet) – The wallet associated with the subnet validator setting the weights.

  • netuid (int) – The unique identifier of the subnet.

  • uids (Union[numpy.typing.NDArray[numpy.int64], bittensor.utils.torch.LongTensor, list]) – The list of subnet miner neuron UIDs that the weights are being set for.

  • weights (Union[numpy.typing.NDArray[numpy.float32], bittensor.utils.torch.FloatTensor, list]) – The corresponding weights to be set for each 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.

  • 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 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:

True if the setting of weights is successful, False otherwise. And msg, a string

value describing the success or potential error.

Return type:

tuple[bool, str]

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.

async sign_and_send_extrinsic(call, wallet, wait_for_inclusion=True, wait_for_finalization=False, sign_with='coldkey', use_nonce=False, period=None, nonce_key='hotkey', raise_error=False)[source]#

Helper method to sign and submit an extrinsic call to chain.

Parameters:
  • call (scalecodec.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

  • sign_with (str) – the wallet’s keypair to use for the signing. Options are “coldkey”, “hotkey”, “coldkeypub”

  • use_nonce (bool) – 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 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 (str) – 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 (bool) – raises a relevant exception rather than returning False if unsuccessful.

Returns:

(success, error message)

Raises:

SubstrateRequestException – Substrate request exception.

Return type:

tuple[bool, str]

async start_call(wallet, netuid, wait_for_inclusion=True, wait_for_finalization=False, period=None)#

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).

Parameters:
  • wallet (bittensor_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) – Whether to wait for the extrinsic to be included in a block. Defaults to True.

  • wait_for_finalization (bool) – 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

  • blocks (transaction is not included in a block within that number of)

  • You (it will expire and be rejected.)

  • transaction. (can think of it as an expiration date for the)

Returns:

  • 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.

Return type:

Tuple[bool, str]

async state_call(method, data, block=None, block_hash=None, reuse_block=False)[source]#

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.

Parameters:
  • method (str) – The method name for the state call.

  • data (str) – The data to be passed to the method.

  • block (Optional[int]) – The blockchain block number at which to perform the state call.

  • 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.

Returns:

The result of the rpc call.

Return type:

result (dict[Any, Any])

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.

async subnet(netuid, block=None, block_hash=None, reuse_block=False)[source]#

Retrieves the subnet information for a single subnet in the Bittensor network.

Parameters:
  • 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.

Returns:

A DynamicInfo object, containing detailed information about a subnet.

Return type:

Optional[DynamicInfo]

async subnet_exists(netuid, block=None, block_hash=None, reuse_block=False)[source]#

Checks if a subnet with the specified unique identifier (netuid) exists within the Bittensor network.

Parameters:
  • 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.

Returns:

True if the subnet exists, False otherwise.

Return type:

bool

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.

async subnetwork_n(netuid, block=None, block_hash=None, reuse_block=False)[source]#

Returns network SubnetworkN hyperparameter.

Parameters:
  • 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.

Returns:

The value of the SubnetworkN hyperparameter, or None if the subnetwork does not exist or

the parameter is not found.

Return type:

Optional[int]

substrate#
async swap_stake(wallet, hotkey_ss58, origin_netuid, destination_netuid, amount, wait_for_inclusion=True, wait_for_finalization=False, safe_staking=False, allow_partial_stake=False, rate_tolerance=0.005, period=None)[source]#

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.

Parameters:
  • wallet (bittensor_wallet.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 (bittensor.utils.balance.Balance) – 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 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 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 (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 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 extrinsic was successful.

Return type:

success

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.

async tempo(netuid, block=None, block_hash=None, reuse_block=False)[source]#

Returns network Tempo hyperparameter.

Parameters:
  • 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.

Returns:

The value of the Tempo hyperparameter, or None if the subnetwork does not exist or the

parameter is not found.

Return type:

Optional[int]

async toggle_user_liquidity(wallet, netuid, enable, wait_for_inclusion=True, wait_for_finalization=False, period=None)#

Allow to toggle user liquidity for specified subnet.

Parameters:
  • wallet (bittensor_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.

  • enable (bool) – Boolean indicating whether to enable user liquidity.

  • wait_for_inclusion (bool) – Whether to wait for the extrinsic to be included in a block. Defaults to True.

  • wait_for_finalization (bool) – 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.

Returns:

  • 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.

Return type:

Tuple[bool, str]

Note: The call can be executed successfully by the subnet owner only.

async transfer(wallet, dest, amount, transfer_all=False, wait_for_inclusion=True, wait_for_finalization=False, keep_alive=True, period=None)[source]#

Transfer token of amount to destination.

Parameters:
  • wallet (bittensor_wallet.Wallet) – Source wallet for the transfer.

  • dest (str) – Destination address for the transfer.

  • amount (bittensor.utils.balance.Balance) – 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. Defaults to True.

  • wait_for_finalization (bool) – Waits for the transaction to be finalized on the blockchain. Defaults to 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 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.

Return type:

bool

async transfer_stake(wallet, destination_coldkey_ss58, hotkey_ss58, origin_netuid, destination_netuid, amount, wait_for_inclusion=True, wait_for_finalization=False, period=None)[source]#

Transfers stake from one subnet to another while changing the coldkey owner.

Parameters:
  • wallet (bittensor_wallet.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 (bittensor.utils.balance.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 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 transfer was successful.

Return type:

success

async tx_rate_limit(block=None, block_hash=None, reuse_block=False)[source]#

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.

Parameters:
  • 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.

Returns:

The transaction rate limit of the network, None if not available.

Return type:

Optional[int]

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.

async unstake(wallet, hotkey_ss58=None, netuid=None, amount=None, wait_for_inclusion=True, wait_for_finalization=False, safe_staking=False, allow_partial_stake=False, rate_tolerance=0.005, period=None, unstake_all=False)[source]#

Removes a specified amount of stake from a single hotkey account. This function is critical for adjusting individual neuron stakes within the Bittensor network.

Parameters:
  • 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.

  • netuid (Optional[int]) – The unique identifier of the subnet.

  • amount (Optional[bittensor.utils.balance.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. Defaults to True.

  • wait_for_finalization (bool) – Waits for the transaction to be finalized on the blockchain. Defaults to False.

  • safe_staking (bool) – 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 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, 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 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 (bool) – If True, unstakes all tokens and amount is ignored. Default is False

Returns:

True if the unstaking process is successful, False otherwise.

Return type:

bool

This function supports flexible stake management, allowing neurons to adjust their network participation and potential reward accruals.

async unstake_all(wallet, hotkey, netuid, rate_tolerance=0.005, wait_for_inclusion=True, wait_for_finalization=False, period=None)#

Unstakes all TAO/Alpha associated with a hotkey from the specified subnets on the Bittensor network.

Parameters:
  • wallet (bittensor_wallet.Wallet) – The wallet of the stake owner.

  • hotkey (str) – The SS58 address of the hotkey to unstake from.

  • netuid (int) – The unique identifier of the subnet.

  • rate_tolerance (Optional[float]) – The maximum allowed price change ratio when unstaking. For example, 0.005 = 0.5% maximum price decrease. If not passed (None), then unstaking goes without price limit. Default is 0.005.

  • 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.

  • 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. Default is None.

Returns:

A tuple containing: - True and a success message if the unstake operation succeeded; - False and an error message otherwise.

Return type:

tuple[bool, str]

Example

To unstake all stakes in all subnets safely, use default rate_tolerance or pass your value: .. code-block:: python

import bittensor as bt

subtensor = bt.AsyncSubtensor() wallet = bt.Wallet(“my_wallet”) netuid = 14 hotkey = “5%SOME_HOTKEY_WHERE_IS_YOUR_STAKE_NOW%”

wallet_stakes = await subtensor.get_stake_info_for_coldkey(coldkey_ss58=wallet.coldkey.ss58_address)

for stake in wallet_stakes:
result = await subtensor.unstake_all(

wallet=wallet, hotkey_ss58=stake.hotkey_ss58, netuid=stake.netuid,

) print(result)

# If you would like to unstake all stakes in all subnets unsafely, use rate_tolerance=None: import bittensor as bt

subtensor = bt.AsyncSubtensor() wallet = bt.Wallet(“my_wallet”) netuid = 14 hotkey = “5%SOME_HOTKEY_WHERE_IS_YOUR_STAKE_NOW%”

wallet_stakes = await subtensor.get_stake_info_for_coldkey(coldkey_ss58=wallet.coldkey.ss58_address)

for stake in wallet_stakes:
result = await subtensor.unstake_all(

wallet=wallet, hotkey_ss58=stake.hotkey_ss58, netuid=stake.netuid, rate_tolerance=None,

) print(result)

async unstake_multiple(wallet, hotkey_ss58s, netuids, amounts=None, wait_for_inclusion=True, wait_for_finalization=False, period=None, unstake_all=False)[source]#

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.

Parameters:
  • 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 (Optional[list[bittensor.utils.balance.Balance]]) – The amounts of TAO to unstake from each hotkey. If not provided, 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.

  • 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 (bool) – If true, unstakes all tokens. Default is False. If True amounts are ignored.

Returns:

True if the batch unstaking is successful, False otherwise.

Return type:

bool

This function allows for strategic reallocation or withdrawal of stakes, aligning with the dynamic stake management aspect of the Bittensor network.

async wait_for_block(block=None)[source]#

Waits until a specific block is reached on the chain. If no block is specified, waits for the next block.

Parameters:

block (Optional[int]) – The block number to wait for. If None, waits for the next block.

Returns:

True if the target block was reached, False if timeout occurred.

Return type:

bool

Example

import bittensor as bt subtensor = bt.Subtensor()

await subtensor.wait_for_block() # Waits for next block await subtensor.wait_for_block(block=1234) # Waits for a specific block

async weights(netuid, block=None, block_hash=None, reuse_block=False)[source]#

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.

Parameters:
  • 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 (Optional[str]) – The hash of the blockchain block for the query.

  • reuse_block (bool) – reuse the last-used blockchain block hash.

Returns:

A list of tuples mapping each neuron’s UID to its assigned weights.

Return type:

list[tuple[int, list[tuple[int, int]]]]

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.

async weights_rate_limit(netuid, block=None, block_hash=None, reuse_block=False)[source]#

Returns network WeightsSetRateLimit hyperparameter.

Parameters:
  • 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 the block id.

  • reuse_block (bool) – Whether to reuse the last-used blockchain block hash.

Returns:

The value of the WeightsSetRateLimit hyperparameter, or None if the subnetwork does not

exist or the parameter is not found.

Return type:

Optional[int]

async bittensor.core.async_subtensor.get_async_subtensor(network=None, config=None, _mock=False, log_verbose=False)[source]#

Factory method to create an initialized AsyncSubtensor. Mainly useful for when you don’t want to run await subtensor.initialize() after instantiation.

Parameters:
Return type:

AsyncSubtensor