bittensor

Contents

bittensor#

Subpackages#

Submodules#

Attributes#

Exceptions#

BlacklistedException

This exception is raised when the request is blacklisted.

ChainConnectionError

Error for any chain connection related errors.

ChainError

Base error for any chain related errors.

ChainQueryError

Error for any chain query related errors.

ChainTransactionError

Error for any chain transaction related errors.

IdentityError

Error raised when an identity transaction fails.

InternalServerError

This exception is raised when the requested function fails on the server. Indicates a server error.

InvalidRequestNameError

This exception is raised when the request name is invalid. Ususally indicates a broken URL.

KeyFileError

Error thrown when the keyfile is corrupt, non-writable, non-readable or the password used to decrypt is invalid.

MetadataError

Error raised when metadata commitment transaction fails.

NominationError

Error raised when a nomination transaction fails.

NotDelegateError

Error raised when a hotkey you are trying to stake to is not a delegate.

NotRegisteredError

Error raised when a neuron is not registered, and the transaction requires it to be.

NotVerifiedException

This exception is raised when the request is not verified.

PostProcessException

This exception is raised when the response headers cannot be updated.

PriorityException

This exception is raised when the request priority is not met.

RegistrationError

Error raised when a neuron registration transaction fails.

RunException

This exception is raised when the requested function cannot be executed. Indicates a server error.

StakeError

Error raised when a stake transaction fails.

SynapseDendriteNoneException

Common base class for all non-exit exceptions.

SynapseParsingError

This exception is raised when the request headers are unable to be parsed into the synapse type.

TransferError

Error raised when a transfer transaction fails.

UnknownSynapseError

This exception is raised when the request name is not found in the Axon's forward_fns dictionary.

UnstakeError

Error raised when an unstake transaction fails.

InvalidConfigFile

In place of YAMLError

Classes#

DefaultConfig

A Config with a set of default values.

config

Implementation of the config class, which manages the configuration of different Bittensor modules.

keyfile

Defines an interface for a substrate interface keypair stored on device.

Mockkeyfile

The Mockkeyfile is a mock object representing a keyfile that does not exist on the device.

wallet

The wallet class in the Bittensor framework handles wallet functionality, crucial for participating in the Bittensor network.

Balance

Represents the bittensor balance of the wallet, stored as rao (int).

AxonInfo

NeuronInfo

Dataclass for neuron metadata.

NeuronInfoLite

Dataclass for neuron metadata, but without the weights and bonds.

PrometheusInfo

Dataclass for prometheus info.

DelegateInfo

Dataclass for delegate information. For a lighter version of this class, see DelegateInfoLite().

StakeInfo

Dataclass for stake info.

SubnetInfo

Dataclass for subnet info.

SubnetHyperparameters

Dataclass for subnet hyperparameters.

IPInfo

Dataclass for associated IP Info.

ProposalVoteData

dict() -> new empty dictionary

Subtensor

The Subtensor class in Bittensor serves as a crucial interface for interacting with the Bittensor blockchain,

subtensor

The Subtensor class in Bittensor serves as a crucial interface for interacting with the Bittensor blockchain,

cli

Implementation of the Command Line Interface (CLI) class for the Bittensor protocol.

PriorityThreadPoolExecutor

Base threadpool executor with a priority queue

TerminalInfo

TerminalInfo encapsulates detailed information about a network synapse (node) involved in a communication process.

Synapse

Represents a Synapse in the Bittensor network, serving as a communication schema between neurons (nodes).

StreamingSynapse

The StreamingSynapse() class is designed to be subclassed for handling streaming responses in the Bittensor network.

tensor

Tensor

Represents a Tensor object.

axon

The axon class in Bittensor is a fundamental component that serves as the server-side interface for a neuron within the Bittensor network.

dendrite

The Dendrite class represents the abstracted implementation of a network client module.

MockKeyfile

Defines an interface to a mocked keyfile object (nothing is created on device) keypair is treated as non encrypted and the data is just the string version.

MockSubtensor

A Mock Subtensor class for running tests.

MockWallet

Mocked Version of the bittensor wallet class, meant to be used for testing

SubnetsAPI

Helper class that provides a standard way to create an ABC using

Functions#

__getattr__(name)

turn_console_off()

turn_console_on()

trace([on])

debug([on])

serialized_keypair_to_keyfile_data(keypair)

Serializes keypair object into keyfile data.

deserialize_keypair_from_keyfile_data(keyfile_data)

Deserializes Keypair object from passed keyfile data.

validate_password(password)

Validates the password against a password policy.

ask_password_to_encrypt()

Prompts the user to enter a password for key encryption.

keyfile_data_is_encrypted_nacl(keyfile_data)

Returns true if the keyfile data is NaCl encrypted.

keyfile_data_is_encrypted_ansible(keyfile_data)

Returns true if the keyfile data is ansible encrypted.

keyfile_data_is_encrypted_legacy(keyfile_data)

Returns true if the keyfile data is legacy encrypted.

keyfile_data_is_encrypted(keyfile_data)

Returns true if the keyfile data is encrypted.

keyfile_data_encryption_method(keyfile_data)

Returns true if the keyfile data is encrypted.

legacy_encrypt_keyfile_data(keyfile_data[, password])

encrypt_keyfile_data(keyfile_data[, password])

Encrypts the passed keyfile data using ansible vault.

get_coldkey_password_from_environment(coldkey_name)

Retrieves the cold key password from the environment variables.

decrypt_keyfile_data(keyfile_data[, password, ...])

Decrypts the passed keyfile data using ansible vault.

display_mnemonic_msg(keypair, key_type)

Display the mnemonic and a warning message to keep the mnemonic safe.

ss58_to_vec_u8(ss58_address)

unbiased_topk(values, k[, dim, sorted, largest, axis])

Selects topk as in torch.topk but does not bias lower indices when values are equal.

version_checking([timeout])

Deprecated, kept for backwards compatibility. Use check_version() instead.

strtobool(val)

Converts a string to a boolean value.

strtobool_with_default(default)

Creates a strtobool function with a default value.

get_explorer_root_url_by_network_from_map(network, ...)

Returns the explorer root url for the given network name from the given network map.

get_explorer_url_for_network(network, block_hash, ...)

Returns the explorer url for the given block hash and network.

ss58_address_to_bytes(ss58_address)

Converts a ss58 address to a bytes object.

U16_NORMALIZED_FLOAT(x)

U64_NORMALIZED_FLOAT(x)

u8_key_to_ss58(u8_key)

Converts a u8-encoded account key to an ss58 address.

hash(content[, encoding])

Package Contents#

bittensor.__version__ = '7.4.0'#
bittensor._version_split#
bittensor.__version_info__#
bittensor._version_int_base = 1000#
bittensor.__version_as_int__: int#
bittensor.__new_signature_version__ = 360#
bittensor.__console__#
bittensor.__use_console__ = True#
bittensor.__getattr__(name)[source]#
bittensor.turn_console_off()[source]#
bittensor.turn_console_on()[source]#
bittensor.trace(on=True)[source]#
Parameters:

on (bool)

bittensor.debug(on=True)[source]#
Parameters:

on (bool)

bittensor.__blocktime__ = 12#
bittensor.__pipaddress__ = 'https://pypi.org/pypi/bittensor/json'#
bittensor.__delegates_details_url__: str = 'https://raw.githubusercontent.com/opentensor/bittensor-delegates/main/public/delegates.json'#
bittensor.__ss58_format__ = 42#
bittensor.__ss58_address_length__ = 48#
bittensor.__networks__ = ['local', 'finney', 'test', 'archive']#
bittensor.__finney_entrypoint__ = 'wss://entrypoint-finney.opentensor.ai:443'#
bittensor.__finney_test_entrypoint__ = 'wss://test.finney.opentensor.ai:443/'#
bittensor.__archive_entrypoint__ = 'wss://archive.chain.opentensor.ai:443/'#
bittensor.__bellagene_entrypoint__ = 'wss://parachain.opentensor.ai:443'#
bittensor.__local_entrypoint__#
bittensor.__tao_symbol__: str#
bittensor.__rao_symbol__: str#
bittensor.__network_explorer_map__#
bittensor.__type_registry__#
exception bittensor.BlacklistedException(message='Synapse Exception', synapse=None)[source]#

Bases: SynapseException

This exception is raised when the request is blacklisted.

Initialize self. See help(type(self)) for accurate signature.

Parameters:

synapse (bittensor.Synapse | None)

exception bittensor.ChainConnectionError[source]#

Bases: ChainError

Error for any chain connection related errors.

Initialize self. See help(type(self)) for accurate signature.

exception bittensor.ChainError[source]#

Bases: BaseException

Base error for any chain related errors.

Initialize self. See help(type(self)) for accurate signature.

exception bittensor.ChainQueryError[source]#

Bases: ChainError

Error for any chain query related errors.

Initialize self. See help(type(self)) for accurate signature.

exception bittensor.ChainTransactionError[source]#

Bases: ChainError

Error for any chain transaction related errors.

Initialize self. See help(type(self)) for accurate signature.

exception bittensor.IdentityError[source]#

Bases: ChainTransactionError

Error raised when an identity transaction fails.

Initialize self. See help(type(self)) for accurate signature.

exception bittensor.InternalServerError(message='Synapse Exception', synapse=None)[source]#

Bases: SynapseException

This exception is raised when the requested function fails on the server. Indicates a server error.

Initialize self. See help(type(self)) for accurate signature.

Parameters:

synapse (bittensor.Synapse | None)

exception bittensor.InvalidRequestNameError[source]#

Bases: Exception

This exception is raised when the request name is invalid. Ususally indicates a broken URL.

Initialize self. See help(type(self)) for accurate signature.

exception bittensor.KeyFileError[source]#

Bases: Exception

Error thrown when the keyfile is corrupt, non-writable, non-readable or the password used to decrypt is invalid.

Initialize self. See help(type(self)) for accurate signature.

exception bittensor.MetadataError[source]#

Bases: ChainTransactionError

Error raised when metadata commitment transaction fails.

Initialize self. See help(type(self)) for accurate signature.

exception bittensor.NominationError[source]#

Bases: ChainTransactionError

Error raised when a nomination transaction fails.

Initialize self. See help(type(self)) for accurate signature.

exception bittensor.NotDelegateError[source]#

Bases: StakeError

Error raised when a hotkey you are trying to stake to is not a delegate.

Initialize self. See help(type(self)) for accurate signature.

exception bittensor.NotRegisteredError[source]#

Bases: ChainTransactionError

Error raised when a neuron is not registered, and the transaction requires it to be.

Initialize self. See help(type(self)) for accurate signature.

exception bittensor.NotVerifiedException(message='Synapse Exception', synapse=None)[source]#

Bases: SynapseException

This exception is raised when the request is not verified.

Initialize self. See help(type(self)) for accurate signature.

Parameters:

synapse (bittensor.Synapse | None)

exception bittensor.PostProcessException(message='Synapse Exception', synapse=None)[source]#

Bases: SynapseException

This exception is raised when the response headers cannot be updated.

Initialize self. See help(type(self)) for accurate signature.

Parameters:

synapse (bittensor.Synapse | None)

exception bittensor.PriorityException(message='Synapse Exception', synapse=None)[source]#

Bases: SynapseException

This exception is raised when the request priority is not met.

Initialize self. See help(type(self)) for accurate signature.

Parameters:

synapse (bittensor.Synapse | None)

exception bittensor.RegistrationError[source]#

Bases: ChainTransactionError

Error raised when a neuron registration transaction fails.

Initialize self. See help(type(self)) for accurate signature.

exception bittensor.RunException(message='Synapse Exception', synapse=None)[source]#

Bases: SynapseException

This exception is raised when the requested function cannot be executed. Indicates a server error.

Initialize self. See help(type(self)) for accurate signature.

Parameters:

synapse (bittensor.Synapse | None)

exception bittensor.StakeError[source]#

Bases: ChainTransactionError

Error raised when a stake transaction fails.

Initialize self. See help(type(self)) for accurate signature.

exception bittensor.SynapseDendriteNoneException(message='Synapse Dendrite is None', synapse=None)[source]#

Bases: SynapseException

Common base class for all non-exit exceptions.

Initialize self. See help(type(self)) for accurate signature.

Parameters:

synapse (bittensor.Synapse | None)

message#
exception bittensor.SynapseParsingError[source]#

Bases: Exception

This exception is raised when the request headers are unable to be parsed into the synapse type.

Initialize self. See help(type(self)) for accurate signature.

exception bittensor.TransferError[source]#

Bases: ChainTransactionError

Error raised when a transfer transaction fails.

Initialize self. See help(type(self)) for accurate signature.

exception bittensor.UnknownSynapseError(message='Synapse Exception', synapse=None)[source]#

Bases: SynapseException

This exception is raised when the request name is not found in the Axon’s forward_fns dictionary.

Initialize self. See help(type(self)) for accurate signature.

Parameters:

synapse (bittensor.Synapse | None)

exception bittensor.UnstakeError[source]#

Bases: ChainTransactionError

Error raised when an unstake transaction fails.

Initialize self. See help(type(self)) for accurate signature.

exception bittensor.InvalidConfigFile[source]#

Bases: Exception

In place of YAMLError

Initialize self. See help(type(self)) for accurate signature.

class bittensor.DefaultConfig(parser=None, args=None, strict=False, default=None)[source]#

Bases: config

A Config with a set of default values.

Construct a new DefaultMunch. Like collections.defaultdict, the first argument is the default value; subsequent arguments are the same as those for dict.

Parameters:
classmethod default()[source]#
Abstractmethod:

Return type:

T

Get default config.

class bittensor.config(parser=None, args=None, strict=False, default=None)[source]#

Bases: munch.DefaultMunch

Implementation of the config class, which manages the configuration of different Bittensor modules.

Construct a new DefaultMunch. Like collections.defaultdict, the first argument is the default value; subsequent arguments are the same as those for dict.

Parameters:
__is_set: Dict[str, bool]#

Translates the passed parser into a nested Bittensor config.

Parameters:
  • parser (argparse.ArgumentParser) – Command line parser object.

  • strict (bool) – If true, the command line arguments are strictly parsed.

  • args (list of str) – Command line arguments.

  • default (Optional[Any]) – Default value for the Config. Defaults to None. This default will be returned for attributes that are undefined.

Returns:

Nested config object created from parser arguments.

Return type:

config (bittensor.config)

missing_required_args#
config_params#
strict#
params#
_config#
parser_no_defaults#
default_param_args#
default_params#
all_default_args#
defaults_as_suppress#
params_no_defaults#
static __split_params__(params, _config)[source]#
Parameters:
static __parse_args__(args, parser=None, strict=False)[source]#

Parses the passed args use the passed parser.

Parameters:
  • args (List[str]) – List of arguments to parse.

  • parser (argparse.ArgumentParser) – Command line parser object.

  • strict (bool) – If true, the command line arguments are strictly parsed.

Returns:

Namespace object created from parser arguments.

Return type:

Namespace

__deepcopy__(memo)[source]#
Return type:

config

__repr__()[source]#

Invertible* string-form of a Munch.

>>> b = Munch(foo=Munch(lol=True), hello=42, ponies='are pretty!')
>>> print (repr(b))
Munch({'ponies': 'are pretty!', 'foo': Munch({'lol': True}), 'hello': 42})
>>> eval(repr(b))
Munch({'ponies': 'are pretty!', 'foo': Munch({'lol': True}), 'hello': 42})
>>> with_spaces = Munch({1: 2, 'a b': 9, 'c': Munch({'simple': 5})})
>>> print (repr(with_spaces))
Munch({'a b': 9, 1: 2, 'c': Munch({'simple': 5})})
>>> eval(repr(with_spaces))
Munch({'a b': 9, 1: 2, 'c': Munch({'simple': 5})})

(*) Invertible so long as collection contents are each repr-invertible.

Return type:

str

static _remove_private_keys(d)[source]#
__str__()[source]#

Return str(self).

Return type:

str

copy()[source]#

D.copy() -> a shallow copy of D

Return type:

config

to_string(items)[source]#

Get string from items

Return type:

str

update_with_kwargs(kwargs)[source]#

Add config to self

classmethod _merge(a, b)[source]#

Merge two configurations recursively. If there is a conflict, the value from the second configuration will take precedence.

merge(b)[source]#

Merges the current config with another config.

Parameters:

b – Another config to merge.

classmethod merge_all(configs)[source]#

Merge all configs in the list into one config. If there is a conflict, the value from the last configuration in the list will take precedence.

Parameters:

configs (list of config) – List of configs to be merged.

Returns:

Merged config object.

Return type:

config

is_set(param_name)[source]#

Returns a boolean indicating whether the parameter has been set or is still the default.

Parameters:

param_name (str)

Return type:

bool

__check_for_missing_required_args(parser, args)#
Parameters:
Return type:

List[str]

static __get_required_args_from_parser(parser)#
Parameters:

parser (argparse.ArgumentParser)

Return type:

List[str]

bittensor.T#
bittensor.serialized_keypair_to_keyfile_data(keypair)[source]#

Serializes keypair object into keyfile data.

Parameters:

keypair (bittensor.Keypair) – The keypair object to be serialized.

Returns:

Serialized keypair data.

Return type:

data (bytes)

bittensor.deserialize_keypair_from_keyfile_data(keyfile_data)[source]#

Deserializes Keypair object from passed keyfile data.

Parameters:

keyfile_data (bytes) – The keyfile data as bytes to be loaded.

Returns:

The Keypair loaded from bytes.

Return type:

keypair (bittensor.Keypair)

Raises:

KeyFileError – Raised if the passed bytes cannot construct a keypair object.

bittensor.validate_password(password)[source]#

Validates the password against a password policy.

Parameters:

password (str) – The password to verify.

Returns:

True if the password meets validity requirements.

Return type:

valid (bool)

bittensor.ask_password_to_encrypt()[source]#

Prompts the user to enter a password for key encryption.

Returns:

The valid password entered by the user.

Return type:

password (str)

bittensor.keyfile_data_is_encrypted_nacl(keyfile_data)[source]#

Returns true if the keyfile data is NaCl encrypted.

Parameters:

keyfile_data (bytes, required) – Bytes to validate.

Returns:

True if data is ansible encrypted.

Return type:

is_nacl (bool)

bittensor.keyfile_data_is_encrypted_ansible(keyfile_data)[source]#

Returns true if the keyfile data is ansible encrypted.

Parameters:

keyfile_data (bytes) – The bytes to validate.

Returns:

True if the data is ansible encrypted.

Return type:

is_ansible (bool)

bittensor.keyfile_data_is_encrypted_legacy(keyfile_data)[source]#

Returns true if the keyfile data is legacy encrypted. :param keyfile_data: The bytes to validate. :type keyfile_data: bytes

Returns:

True if the data is legacy encrypted.

Return type:

is_legacy (bool)

Parameters:

keyfile_data (bytes)

bittensor.keyfile_data_is_encrypted(keyfile_data)[source]#

Returns true if the keyfile data is encrypted.

Parameters:

keyfile_data (bytes) – The bytes to validate.

Returns:

True if the data is encrypted.

Return type:

is_encrypted (bool)

bittensor.keyfile_data_encryption_method(keyfile_data)[source]#

Returns true if the keyfile data is encrypted.

Parameters:

keyfile_data (bytes, required) – Bytes to validate

Returns:

True if data is encrypted.

Return type:

encryption_method (bool)

bittensor.legacy_encrypt_keyfile_data(keyfile_data, password=None)[source]#
Parameters:
Return type:

bytes

bittensor.encrypt_keyfile_data(keyfile_data, password=None)[source]#

Encrypts the passed keyfile data using ansible vault.

Parameters:
  • keyfile_data (bytes) – The bytes to encrypt.

  • password (str, optional) – The password used to encrypt the data. If None, asks for user input.

Returns:

The encrypted data.

Return type:

encrypted_data (bytes)

bittensor.get_coldkey_password_from_environment(coldkey_name)[source]#

Retrieves the cold key password from the environment variables.

Parameters:

coldkey_name (str) – The name of the cold key.

Returns:

The password retrieved from the environment variables, or None if not found.

Return type:

password (str)

bittensor.decrypt_keyfile_data(keyfile_data, password=None, coldkey_name=None)[source]#

Decrypts the passed keyfile data using ansible vault.

Parameters:
  • keyfile_data (bytes) – The bytes to decrypt.

  • password (str, optional) – The password used to decrypt the data. If None, asks for user input.

  • coldkey_name (str, optional) – The name of the cold key. If provided, retrieves the password from environment variables.

Returns:

The decrypted data.

Return type:

decrypted_data (bytes)

Raises:

KeyFileError – Raised if the file is corrupted or if the password is incorrect.

class bittensor.keyfile(path)[source]#

Defines an interface for a substrate interface keypair stored on device.

Parameters:

path (str)

path#
name#
__str__()[source]#
__repr__()[source]#
property keypair: bittensor.Keypair#

Returns the keypair from path, decrypts data if the file is encrypted.

Returns:

The keypair stored under the path.

Return type:

keypair (bittensor.Keypair)

Raises:

KeyFileError – Raised if the file does not exist, is not readable, writable, corrupted, or if the password is incorrect.

property data: bytes#

Returns the keyfile data under path.

Returns:

The keyfile data stored under the path.

Return type:

keyfile_data (bytes)

Raises:

KeyFileError – Raised if the file does not exist, is not readable, or writable.

property keyfile_data: bytes#

Returns the keyfile data under path.

Returns:

The keyfile data stored under the path.

Return type:

keyfile_data (bytes)

Raises:

KeyFileError – Raised if the file does not exist, is not readable, or writable.

set_keypair(keypair, encrypt=True, overwrite=False, password=None)[source]#

Writes the keypair to the file and optionally encrypts data.

Parameters:
  • keypair (bittensor.Keypair) – The keypair to store under the path.

  • encrypt (bool, optional) – If True, encrypts the file under the path. Default is True.

  • overwrite (bool, optional) – If True, forces overwrite of the current file. Default is False.

  • password (str, optional) – The password used to encrypt the file. If None, asks for user input.

Raises:

KeyFileError – Raised if the file does not exist, is not readable, writable, or if the password is incorrect.

get_keypair(password=None)[source]#

Returns the keypair from the path, decrypts data if the file is encrypted.

Parameters:

password (str, optional) – The password used to decrypt the file. If None, asks for user input.

Returns:

The keypair stored under the path.

Return type:

keypair (bittensor.Keypair)

Raises:

KeyFileError – Raised if the file does not exist, is not readable, writable, corrupted, or if the password is incorrect.

make_dirs()[source]#

Creates directories for the path if they do not exist.

exists_on_device()[source]#

Returns True if the file exists on the device.

Returns:

True if the file is on the device.

Return type:

on_device (bool)

is_readable()[source]#

Returns True if the file under path is readable.

Returns:

True if the file is readable.

Return type:

readable (bool)

is_writable()[source]#

Returns True if the file under path is writable.

Returns:

True if the file is writable.

Return type:

writable (bool)

is_encrypted()[source]#

Returns True if the file under path is encrypted.

Returns:

True if the file is encrypted.

Return type:

encrypted (bool)

_may_overwrite()[source]#

Asks the user if it is okay to overwrite the file.

Returns:

True if the user allows overwriting the file.

Return type:

may_overwrite (bool)

check_and_update_encryption(print_result=True, no_prompt=False)[source]#

Check the version of keyfile and update if needed.

Parameters:
  • print_result (bool) – Print the checking result or not.

  • no_prompt (bool) – Skip if no prompt.

Raises:

KeyFileError – Raised if the file does not exists, is not readable, writable.

Returns:

Return True if the keyfile is the most updated with nacl, else False.

Return type:

result (bool)

encrypt(password=None)[source]#

Encrypts the file under the path.

Parameters:

password (str, optional) – The password for encryption. If None, asks for user input.

Raises:

KeyFileError – Raised if the file does not exist, is not readable, or writable.

decrypt(password=None)[source]#

Decrypts the file under the path.

Parameters:

password (str, optional) – The password for decryption. If None, asks for user input.

Raises:

KeyFileError – Raised if the file does not exist, is not readable, writable, corrupted, or if the password is incorrect.

_read_keyfile_data_from_file()[source]#

Reads the keyfile data from the file.

Returns:

The keyfile data stored under the path.

Return type:

keyfile_data (bytes)

Raises:

KeyFileError – Raised if the file does not exist or is not readable.

_write_keyfile_data_to_file(keyfile_data, overwrite=False)[source]#

Writes the keyfile data to the file.

Parameters:
  • keyfile_data (bytes) – The byte data to store under the path.

  • overwrite (bool, optional) – If True, overwrites the data without asking for permission from the user. Default is False.

Raises:

KeyFileError – Raised if the file is not writable or the user responds No to the overwrite prompt.

class bittensor.Mockkeyfile(path)[source]#

The Mockkeyfile is a mock object representing a keyfile that does not exist on the device.

It is designed for use in testing scenarios and simulations where actual filesystem operations are not required. The keypair stored in the Mockkeyfile is treated as non-encrypted and the data is stored as a serialized string.

Initializes a Mockkeyfile object.

Parameters:

path (str) – The path of the mock keyfile.

path#
_mock_keypair = None#
_mock_data = None#
__str__()[source]#

Returns a string representation of the Mockkeyfile. The representation will indicate if the keyfile is empty, encrypted, or decrypted.

Returns:

The string representation of the Mockkeyfile.

Return type:

str

__repr__()[source]#

Returns a string representation of the Mockkeyfile, same as __str__().

Returns:

The string representation of the Mockkeyfile.

Return type:

str

property keypair#
Returns the mock keypair stored in the keyfile.
Returns:

The mock keypair.

Return type:

bittensor.Keypair

property data#
Returns the serialized keypair data stored in the keyfile.
Returns:

The serialized keypair data.

Return type:

bytes

set_keypair(keypair, encrypt=True, overwrite=False, password=None)[source]#

Sets the mock keypair in the keyfile. The encrypt and overwrite parameters are ignored.

Parameters:
  • keypair (bittensor.Keypair) – The mock keypair to be set.

  • encrypt (bool, optional) – Ignored in this context. Defaults to True.

  • overwrite (bool, optional) – Ignored in this context. Defaults to False.

  • password (str, optional) – Ignored in this context. Defaults to None.

get_keypair(password=None)[source]#

Returns the mock keypair stored in the keyfile. The password parameter is ignored.

Parameters:

password (str, optional) – Ignored in this context. Defaults to None.

Returns:

The mock keypair stored in the keyfile.

Return type:

bittensor.Keypair

make_dirs()[source]#

Creates the directories for the mock keyfile. Does nothing in this class, since no actual filesystem operations are needed.

exists_on_device()[source]#

Returns True indicating that the mock keyfile exists on the device (although it is not created on the actual file system).

Returns:

Always returns True for Mockkeyfile.

Return type:

bool

is_readable()[source]#

Returns True indicating that the mock keyfile is readable (although it is not read from the actual file system).

Returns:

Always returns True for Mockkeyfile.

Return type:

bool

is_writable()[source]#

Returns True indicating that the mock keyfile is writable (although it is not written to the actual file system).

Returns:

Always returns True for Mockkeyfile.

Return type:

bool

is_encrypted()[source]#

Returns False indicating that the mock keyfile is not encrypted.

Returns:

Always returns False for Mockkeyfile.

Return type:

bool

encrypt(password=None)[source]#

Raises a ValueError since encryption is not supported for the mock keyfile.

Parameters:

password (str, optional) – Ignored in this context. Defaults to None.

Raises:

ValueError – Always raises this exception for Mockkeyfile.

decrypt(password=None)[source]#

Returns without doing anything since the mock keyfile is not encrypted.

Parameters:

password (str, optional) – Ignored in this context. Defaults to None.

check_and_update_encryption(no_prompt=None, print_result=False)[source]#
bittensor.display_mnemonic_msg(keypair, key_type)[source]#

Display the mnemonic and a warning message to keep the mnemonic safe.

Parameters:
  • keypair (Keypair) – Keypair object.

  • key_type (str) – Type of the key (coldkey or hotkey).

class bittensor.wallet(name=None, hotkey=None, path=None, config=None)[source]#

The wallet class in the Bittensor framework handles wallet functionality, crucial for participating in the Bittensor network.

It manages two types of keys: coldkey and hotkey, each serving different purposes in network operations. Each wallet contains a coldkey and a hotkey.

The coldkey is the user’s primary key for holding stake in their wallet and is the only way that users can access Tao. Coldkeys can hold tokens and should be encrypted on your device.

The coldkey is the primary key used for securing the wallet’s stake in the Bittensor network (Tao) and is critical for financial transactions like staking and unstaking tokens. It’s recommended to keep the coldkey encrypted and secure, as it holds the actual tokens.

The hotkey, in contrast, is used for operational tasks like subscribing to and setting weights in the network. It’s linked to the coldkey through the metagraph and does not directly hold tokens, thereby offering a safer way to interact with the network during regular operations.

Parameters:
  • name (str) – The name of the wallet, used to identify it among possibly multiple wallets.

  • path (str) – File system path where wallet keys are stored.

  • hotkey_str (str) – String identifier for the hotkey.

  • _hotkey (bittensor.Keypair) – Internal representations of the hotkey and coldkey.

  • _coldkey (bittensor.Keypair) – Internal representations of the hotkey and coldkey.

  • _coldkeypub (bittensor.Keypair) – Internal representations of the hotkey and coldkey.

  • hotkey (str)

  • config (bittensor.config)

create_if_non_existent, create, recreate

Methods to handle the creation of wallet keys.

get_coldkey, get_hotkey, get_coldkeypub

Methods to retrieve specific keys.

set_coldkey, set_hotkey, set_coldkeypub

Methods to set or update keys.

hotkey_file, coldkey_file, coldkeypub_file

Properties that return respective key file objects.

regenerate_coldkey, regenerate_hotkey, regenerate_coldkeypub

Methods to regenerate keys from different sources.

config, help, add_args

Utility methods for configuration and assistance.

The wallet class is a fundamental component for users to interact securely with the Bittensor network, facilitating both operational tasks and transactions involving value transfer across the network.

Example Usage:

# Create a new wallet with default coldkey and hotkey names
my_wallet = wallet()

# Access hotkey and coldkey
hotkey = my_wallet.get_hotkey()
coldkey = my_wallet.get_coldkey()

# Set a new coldkey
my_wallet.new_coldkey(n_words=24) # number of seed words to use

# Update wallet hotkey
my_wallet.set_hotkey(new_hotkey)

# Print wallet details
print(my_wallet)

# Access coldkey property, must use password to unlock
my_wallet.coldkey

Initialize the bittensor wallet object containing a hot and coldkey.

Parameters:
  • name (str, optional) – The name of the wallet to unlock for running bittensor. Defaults to default.

  • hotkey (str, optional) – The name of hotkey used to running the miner. Defaults to default.

  • path (str, optional) – The path to your bittensor wallets. Defaults to ~/.bittensor/wallets/.

  • config (bittensor.config, optional) – bittensor.wallet.config(). Defaults to None.

classmethod config()[source]#

Get config from the argument parser.

Returns:

Config object.

Return type:

bittensor.config

classmethod help()[source]#

Print help to stdout.

classmethod add_args(parser, prefix=None)[source]#

Accept specific arguments from parser.

Parameters:
name#
property hotkey: bittensor.Keypair#

Loads the hotkey from wallet.path/wallet.name/hotkeys/wallet.hotkey or raises an error.

Returns:

hotkey loaded from config arguments.

Return type:

hotkey (Keypair)

Raises:
  • KeyFileError – Raised if the file is corrupt of non-existent.

  • CryptoKeyError – Raised if the user enters an incorrec password for an encrypted keyfile.

path#
hotkey_str#
_hotkey = None#
_coldkey = None#
_coldkeypub = None#
__str__()[source]#

Returns the string representation of the Wallet object.

Returns:

The string representation.

Return type:

str

__repr__()[source]#

Returns the string representation of the wallet object.

Returns:

The string representation.

Return type:

str

create_if_non_existent(coldkey_use_password=True, hotkey_use_password=False)[source]#

Checks for existing coldkeypub and hotkeys, and creates them if non-existent.

Parameters:
  • coldkey_use_password (bool, optional) – Whether to use a password for coldkey. Defaults to True.

  • hotkey_use_password (bool, optional) – Whether to use a password for hotkey. Defaults to False.

Returns:

The wallet object.

Return type:

wallet

create(coldkey_use_password=True, hotkey_use_password=False)[source]#

Checks for existing coldkeypub and hotkeys, and creates them if non-existent.

Parameters:
  • coldkey_use_password (bool, optional) – Whether to use a password for coldkey. Defaults to True.

  • hotkey_use_password (bool, optional) – Whether to use a password for hotkey. Defaults to False.

Returns:

The wallet object.

Return type:

wallet

recreate(coldkey_use_password=True, hotkey_use_password=False)[source]#

Checks for existing coldkeypub and hotkeys and creates them if non-existent.

Parameters:
  • coldkey_use_password (bool, optional) – Whether to use a password for coldkey. Defaults to True.

  • hotkey_use_password (bool, optional) – Whether to use a password for hotkey. Defaults to False.

Returns:

The wallet object.

Return type:

wallet

property hotkey_file: bittensor.keyfile#

Property that returns the hotkey file.

Returns:

The hotkey file.

Return type:

bittensor.keyfile

property coldkey_file: bittensor.keyfile#

Property that returns the coldkey file.

Returns:

The coldkey file.

Return type:

bittensor.keyfile

property coldkeypub_file: bittensor.keyfile#

Property that returns the coldkeypub file.

Returns:

The coldkeypub file.

Return type:

bittensor.keyfile

set_hotkey(keypair, encrypt=False, overwrite=False)[source]#

Sets the hotkey for the wallet.

Parameters:
  • keypair (bittensor.Keypair) – The hotkey keypair.

  • encrypt (bool, optional) – Whether to encrypt the hotkey. Defaults to False.

  • overwrite (bool, optional) – Whether to overwrite an existing hotkey. Defaults to False.

Returns:

The hotkey file.

Return type:

bittensor.keyfile

set_coldkeypub(keypair, encrypt=False, overwrite=False)[source]#

Sets the coldkeypub for the wallet.

Parameters:
  • keypair (bittensor.Keypair) – The coldkeypub keypair.

  • encrypt (bool, optional) – Whether to encrypt the coldkeypub. Defaults to False.

  • overwrite (bool, optional) – Whether to overwrite an existing coldkeypub. Defaults to False.

Returns:

The coldkeypub file.

Return type:

bittensor.keyfile

set_coldkey(keypair, encrypt=True, overwrite=False)[source]#

Sets the coldkey for the wallet.

Parameters:
  • keypair (bittensor.Keypair) – The coldkey keypair.

  • encrypt (bool, optional) – Whether to encrypt the coldkey. Defaults to True.

  • overwrite (bool, optional) – Whether to overwrite an existing coldkey. Defaults to False.

Returns:

The coldkey file.

Return type:

bittensor.keyfile

get_coldkey(password=None)[source]#

Gets the coldkey from the wallet.

Parameters:

password (str, optional) – The password to decrypt the coldkey. Defaults to None.

Returns:

The coldkey keypair.

Return type:

bittensor.Keypair

get_hotkey(password=None)[source]#

Gets the hotkey from the wallet.

Parameters:

password (str, optional) – The password to decrypt the hotkey. Defaults to None.

Returns:

The hotkey keypair.

Return type:

bittensor.Keypair

get_coldkeypub(password=None)[source]#

Gets the coldkeypub from the wallet.

Parameters:

password (str, optional) – The password to decrypt the coldkeypub. Defaults to None.

Returns:

The coldkeypub keypair.

Return type:

bittensor.Keypair

property coldkey: bittensor.Keypair#

Loads the hotkey from wallet.path/wallet.name/coldkey or raises an error.

Returns:

coldkey loaded from config arguments.

Return type:

coldkey (Keypair)

Raises:
  • KeyFileError – Raised if the file is corrupt of non-existent.

  • CryptoKeyError – Raised if the user enters an incorrec password for an encrypted keyfile.

property coldkeypub: bittensor.Keypair#

Loads the coldkeypub from wallet.path/wallet.name/coldkeypub.txt or raises an error.

Returns:

coldkeypub loaded from config arguments.

Return type:

coldkeypub (Keypair)

Raises:
  • KeyFileError – Raised if the file is corrupt of non-existent.

  • CryptoKeyError – Raised if the user enters an incorrect password for an encrypted keyfile.

create_coldkey_from_uri(uri, use_password=True, overwrite=False, suppress=False)[source]#

Creates coldkey from suri string, optionally encrypts it with the user-provided password.

Parameters:
  • uri (str) – (str, required): URI string to use i.e., /Alice or /Bob.

  • use_password (bool, optional) – Is the created key password protected.

  • overwrite (bool, optional) – Determines if this operation overwrites the coldkey under the same path <wallet path>/<wallet name>/coldkey.

  • suppress (bool)

Returns:

This object with newly created coldkey.

Return type:

wallet (bittensor.wallet)

create_hotkey_from_uri(uri, use_password=False, overwrite=False, suppress=False)[source]#

Creates hotkey from suri string, optionally encrypts it with the user-provided password.

Parameters:
  • uri (str) – (str, required): URI string to use i.e., /Alice or /Bob

  • use_password (bool, optional) – Is the created key password protected.

  • overwrite (bool, optional) – Determines if this operation overwrites the hotkey under the same path <wallet path>/<wallet name>/hotkeys/<hotkey>.

  • suppress (bool)

Returns:

This object with newly created hotkey.

Return type:

wallet (bittensor.wallet)

new_coldkey(n_words=12, use_password=True, overwrite=False, suppress=False)[source]#

Creates a new coldkey, optionally encrypts it with the user-provided password and saves to disk.

Parameters:
  • n_words (int) – (int, optional): Number of mnemonic words to use.

  • use_password (bool, optional) – Is the created key password protected.

  • overwrite (bool, optional) – Determines if this operation overwrites the coldkey under the same path <wallet path>/<wallet name>/coldkey.

  • suppress (bool)

Returns:

This object with newly created coldkey.

Return type:

wallet (bittensor.wallet)

create_new_coldkey(n_words=12, use_password=True, overwrite=False, suppress=False)[source]#

Creates a new coldkey, optionally encrypts it with the user-provided password and saves to disk.

Parameters:
  • n_words (int) – (int, optional): Number of mnemonic words to use.

  • use_password (bool, optional) – Is the created key password protected.

  • overwrite (bool, optional) – Determines if this operation overwrites the coldkey under the same path <wallet path>/<wallet name>/coldkey.

  • suppress (bool)

Returns:

This object with newly created coldkey.

Return type:

wallet (bittensor.wallet)

new_hotkey(n_words=12, use_password=False, overwrite=False, suppress=False)[source]#

Creates a new hotkey, optionally encrypts it with the user-provided password and saves to disk.

Parameters:
  • n_words (int) – (int, optional): Number of mnemonic words to use.

  • use_password (bool, optional) – Is the created key password protected.

  • overwrite (bool, optional) – Determines if this operation overwrites the hotkey under the same path <wallet path>/<wallet name>/hotkeys/<hotkey>.

  • suppress (bool)

Returns:

This object with newly created hotkey.

Return type:

wallet (bittensor.wallet)

create_new_hotkey(n_words=12, use_password=False, overwrite=False, suppress=False)[source]#

Creates a new hotkey, optionally encrypts it with the user-provided password and saves to disk.

Parameters:
  • n_words (int) – (int, optional): Number of mnemonic words to use.

  • use_password (bool, optional) – Is the created key password protected.

  • overwrite (bool, optional) – Will this operation overwrite the hotkey under the same path <wallet path>/<wallet name>/hotkeys/<hotkey>

  • suppress (bool)

Returns:

This object with newly created hotkey.

Return type:

wallet (bittensor.wallet)

regenerate_coldkeypub(ss58_address=None, public_key=None, overwrite=False, suppress=False)[source]#

Regenerates the coldkeypub from the passed ss58_address or public_key and saves the file. Requires either ss58_address or public_key to be passed.

Parameters:
  • ss58_address (Optional[str]) – (str, optional): Address as ss58 string.

  • public_key (Optional[Union[str, bytes]]) – (str | bytes, optional): Public key as hex string or bytes.

  • overwrite (bool, optional) – False): Determins if this operation overwrites the coldkeypub (if exists) under the same path <wallet path>/<wallet name>/coldkeypub.

  • suppress (bool)

Returns:

Newly re-generated wallet with coldkeypub.

Return type:

wallet (bittensor.wallet)

regen_coldkeypub#
regenerate_coldkey(mnemonic: list | str | None = None, use_password: bool = True, overwrite: bool = False, suppress: bool = False) wallet[source]#
regenerate_coldkey(seed: str | None = None, use_password: bool = True, overwrite: bool = False, suppress: bool = False) wallet
regenerate_coldkey(json: Tuple[str | Dict, str] | None = None, use_password: bool = True, overwrite: bool = False, suppress: bool = False) wallet

Regenerates the coldkey from the passed mnemonic or seed, or JSON encrypts it with the user’s password and saves the file.

Parameters:
  • mnemonic – (Union[list, str], optional): Key mnemonic as list of words or string space separated words.

  • seed – (str, optional): Seed as hex string.

  • json – (Tuple[Union[str, Dict], str], optional): Restore from encrypted JSON backup as (json_data: Union[str, Dict], passphrase: str)

  • use_password (bool, optional) – Is the created key password protected.

  • overwrite (bool, optional) – Determines if this operation overwrites the coldkey under the same path <wallet path>/<wallet name>/coldkey.

Returns:

This object with newly created coldkey.

Return type:

wallet (bittensor.wallet)

Note

Uses priority order: mnemonic > seed > json.

regen_coldkey#
regenerate_hotkey(mnemonic: list | str | None = None, use_password: bool = True, overwrite: bool = False, suppress: bool = False) wallet[source]#
regenerate_hotkey(seed: str | None = None, use_password: bool = True, overwrite: bool = False, suppress: bool = False) wallet
regenerate_hotkey(json: Tuple[str | Dict, str] | None = None, use_password: bool = True, overwrite: bool = False, suppress: bool = False) wallet

Regenerates the hotkey from passed mnemonic or seed, encrypts it with the user’s password and saves the file.

Parameters:
  • mnemonic – (Union[list, str], optional): Key mnemonic as list of words or string space separated words.

  • seed – (str, optional): Seed as hex string.

  • json – (Tuple[Union[str, Dict], str], optional): Restore from encrypted JSON backup as (json_data: Union[str, Dict], passphrase: str).

  • use_password (bool, optional) – Is the created key password protected.

  • overwrite (bool, optional) – Determies if this operation overwrites the hotkey under the same path <wallet path>/<wallet name>/hotkeys/<hotkey>.

Returns:

This object with newly created hotkey.

Return type:

wallet (bittensor.wallet)

regen_hotkey#
bittensor.ss58_to_vec_u8(ss58_address)[source]#
Parameters:

ss58_address (str)

Return type:

List[int]

bittensor.unbiased_topk(values, k, dim=0, sorted=True, largest=True, axis=0)[source]#

Selects topk as in torch.topk but does not bias lower indices when values are equal. :param values: (np.ndarray) if using numpy, (torch.Tensor) if using torch:

Values to index into.

Parameters:
  • k (int) – (int): Number to take.

  • dim (int) – (int): Dimension to index into (used by Torch)

  • sorted (bool) – (bool): Whether to sort indices.

  • largest (bool) – (bool): Whether to take the largest value.

  • axis (int) – (int): Axis along which to index into (used by Numpy)

  • values (wallet_utils.Union[numpy.ndarray, registration.torch.Tensor])

Returns:

(np.ndarray) if using numpy, (torch.Tensor) if using torch:

topk k values.

indices: (np.ndarray) if using numpy, (torch.LongTensor) if using torch:

indices of the topk values.

Return type:

topk

bittensor.version_checking(timeout=15)[source]#

Deprecated, kept for backwards compatibility. Use check_version() instead.

Parameters:

timeout (int)

bittensor.strtobool(val)[source]#

Converts a string to a boolean value.

truth-y values are ‘y’, ‘yes’, ‘t’, ‘true’, ‘on’, and ‘1’; false-y values are ‘n’, ‘no’, ‘f’, ‘false’, ‘off’, and ‘0’.

Raises ValueError if ‘val’ is anything else.

Parameters:

val (str)

Return type:

wallet_utils.Union[bool, Literal[‘==SUPRESS==’]]

bittensor.strtobool_with_default(default)[source]#

Creates a strtobool function with a default value.

Parameters:

default (bool) – The default value to return if the string is empty.

Returns:

The strtobool function with the default value.

Return type:

Callable[[str], wallet_utils.Union[bool, Literal[‘==SUPRESS==’]]]

bittensor.get_explorer_root_url_by_network_from_map(network, network_map)[source]#

Returns the explorer root url for the given network name from the given network map.

Parameters:
  • network (str) – The network to get the explorer url for.

  • network_map (Dict[str, str]) – The network map to get the explorer url from.

Returns:

The explorer url for the given network. Or None if the network is not in the network map.

Return type:

wallet_utils.Optional[Dict[str, str]]

bittensor.get_explorer_url_for_network(network, block_hash, network_map)[source]#

Returns the explorer url for the given block hash and network.

Parameters:
  • network (str) – The network to get the explorer url for.

  • block_hash (str) – The block hash to get the explorer url for.

  • network_map (Dict[str, Dict[str, str]]) – The network maps to get the explorer urls from.

Returns:

The explorer url for the given block hash and network. Or None if the network is not known.

Return type:

wallet_utils.Optional[List[str]]

bittensor.ss58_address_to_bytes(ss58_address)[source]#

Converts a ss58 address to a bytes object.

Parameters:

ss58_address (str)

Return type:

bytes

bittensor.U16_NORMALIZED_FLOAT(x)[source]#
Parameters:

x (int)

Return type:

float

bittensor.U64_NORMALIZED_FLOAT(x)[source]#
Parameters:

x (int)

Return type:

float

bittensor.u8_key_to_ss58(u8_key)[source]#

Converts a u8-encoded account key to an ss58 address.

Parameters:

u8_key (List[int]) – The u8-encoded account key.

Return type:

str

bittensor.hash(content, encoding='utf-8')[source]#
class bittensor.Balance(balance)[source]#

Represents the bittensor balance of the wallet, stored as rao (int). This class provides a way to interact with balances in two different units: rao and tao. It provides methods to convert between these units, as well as to perform arithmetic and comparison operations.

Variables:
  • unit – A string representing the symbol for the tao unit.

  • rao_unit – A string representing the symbol for the rao unit.

  • rao – An integer that stores the balance in rao units.

  • tao – A float property that gives the balance in tao units.

Parameters:

balance (Union[int, float])

Initialize a Balance object. If balance is an int, it’s assumed to be in rao. If balance is a float, it’s assumed to be in tao.

Parameters:

balance (Union[int, float]) – The initial balance, in either rao (if an int) or tao (if a float).

unit: str#
rao_unit: str#
rao: int#
property tao#
__int__()[source]#

Convert the Balance object to an int. The resulting value is in rao.

__float__()[source]#

Convert the Balance object to a float. The resulting value is in tao.

__str__()[source]#

Returns the Balance object as a string in the format “symbolvalue”, where the value is in tao.

__rich__()[source]#
__str_rao__()[source]#
__rich_rao__()[source]#
__repr__()[source]#
__eq__(other)[source]#
Parameters:

other (Union[int, float, Balance])

__ne__(other)[source]#
Parameters:

other (Union[int, float, Balance])

__gt__(other)[source]#
Parameters:

other (Union[int, float, Balance])

__lt__(other)[source]#
Parameters:

other (Union[int, float, Balance])

__le__(other)[source]#
Parameters:

other (Union[int, float, Balance])

__ge__(other)[source]#
Parameters:

other (Union[int, float, Balance])

__add__(other)[source]#
Parameters:

other (Union[int, float, Balance])

__radd__(other)[source]#
Parameters:

other (Union[int, float, Balance])

__sub__(other)[source]#
Parameters:

other (Union[int, float, Balance])

__rsub__(other)[source]#
Parameters:

other (Union[int, float, Balance])

__mul__(other)[source]#
Parameters:

other (Union[int, float, Balance])

__rmul__(other)[source]#
Parameters:

other (Union[int, float, Balance])

__truediv__(other)[source]#
Parameters:

other (Union[int, float, Balance])

__rtruediv__(other)[source]#
Parameters:

other (Union[int, float, Balance])

__floordiv__(other)[source]#
Parameters:

other (Union[int, float, Balance])

__rfloordiv__(other)[source]#
Parameters:

other (Union[int, float, Balance])

__nonzero__()[source]#
Return type:

bool

__neg__()[source]#
__pos__()[source]#
__abs__()[source]#
static from_float(amount)[source]#

Given tao (float), return Balance object with rao(int) and tao(float), where rao = int(tao*pow(10,9)) :param amount: The amount in tao.

Returns:

A Balance object representing the given amount.

Parameters:

amount (float)

static from_tao(amount)[source]#

Given tao (float), return Balance object with rao(int) and tao(float), where rao = int(tao*pow(10,9))

Parameters:

amount (float) – The amount in tao.

Returns:

A Balance object representing the given amount.

static from_rao(amount)[source]#

Given rao (int), return Balance object with rao(int) and tao(float), where rao = int(tao*pow(10,9))

Parameters:

amount (int) – The amount in rao.

Returns:

A Balance object representing the given amount.

class bittensor.AxonInfo[source]#
version: int#
ip: str#
port: int#
ip_type: int#
hotkey: str#
coldkey: str#
protocol: int = 4#
placeholder1: int = 0#
placeholder2: int = 0#
property is_serving: bool#

True if the endpoint is serving.

Return type:

bool

ip_str()[source]#

Return the whole IP as string

Return type:

str

__eq__(other)[source]#
Parameters:

other (AxonInfo)

__str__()[source]#
__repr__()[source]#
to_string()[source]#

Converts the AxonInfo object to a string representation using JSON.

Return type:

str

classmethod from_string(json_string)[source]#

Creates an AxonInfo object from its string representation using JSON.

Parameters:

json_string (str) – The JSON string representation of the AxonInfo object.

Returns:

An instance of AxonInfo created from the JSON string. If decoding fails, returns a default AxonInfo object with default values.

Return type:

AxonInfo

Raises:
  • json.JSONDecodeError – If there is an error in decoding the JSON string.

  • TypeError – If there is a type error when creating the AxonInfo object.

  • ValueError – If there is a value error when creating the AxonInfo object.

classmethod from_neuron_info(neuron_info)[source]#

Converts a dictionary to an AxonInfo object.

Parameters:

neuron_info (dict) – A dictionary containing the neuron information.

Returns:

An instance of AxonInfo created from the dictionary.

Return type:

instance (AxonInfo)

to_parameter_dict()[source]#

Returns a torch tensor or dict of the subnet info, depending on the USE_TORCH flag set.

Return type:

Union[dict[str, Union[int, str]], bittensor.utils.registration.torch.nn.ParameterDict]

classmethod from_parameter_dict(parameter_dict)[source]#

Returns an axon_info object from a torch parameter_dict or a parameter dict.

Parameters:

parameter_dict (Union[dict[str, Any], bittensor.utils.registration.torch.nn.ParameterDict])

Return type:

AxonInfo

class bittensor.NeuronInfo[source]#

Dataclass for neuron metadata.

hotkey: str#
coldkey: str#
uid: int#
netuid: int#
active: int#
stake: bittensor.utils.balance.Balance#
stake_dict: Dict[str, bittensor.utils.balance.Balance]#
total_stake: bittensor.utils.balance.Balance#
rank: float#
emission: float#
incentive: float#
consensus: float#
trust: float#
validator_trust: float#
dividends: float#
last_update: int#
validator_permit: bool#
weights: List[List[int]]#
bonds: List[List[int]]#
pruning_score: int#
prometheus_info: PrometheusInfo | None = None#
axon_info: AxonInfo | None = None#
is_null: bool = False#
classmethod fix_decoded_values(neuron_info_decoded)[source]#

Fixes the values of the NeuronInfo object.

Parameters:

neuron_info_decoded (Any)

Return type:

NeuronInfo

classmethod from_vec_u8(vec_u8)[source]#

Returns a NeuronInfo object from a vec_u8.

Parameters:

vec_u8 (List[int])

Return type:

NeuronInfo

classmethod list_from_vec_u8(vec_u8)[source]#

Returns a list of NeuronInfo objects from a vec_u8

Parameters:

vec_u8 (List[int])

Return type:

List[NeuronInfo]

static get_null_neuron()[source]#
Return type:

NeuronInfo

classmethod from_weights_bonds_and_neuron_lite(neuron_lite, weights_as_dict, bonds_as_dict)[source]#
Parameters:
Return type:

NeuronInfo

class bittensor.NeuronInfoLite[source]#

Dataclass for neuron metadata, but without the weights and bonds.

hotkey: str#
coldkey: str#
uid: int#
netuid: int#
active: int#
stake: bittensor.utils.balance.Balance#
stake_dict: Dict[str, bittensor.utils.balance.Balance]#
total_stake: bittensor.utils.balance.Balance#
rank: float#
emission: float#
incentive: float#
consensus: float#
trust: float#
validator_trust: float#
dividends: float#
last_update: int#
validator_permit: bool#
prometheus_info: PrometheusInfo | None#
axon_info: NeuronInfoLite.axon_info#
pruning_score: int#
is_null: bool = False#
classmethod fix_decoded_values(neuron_info_decoded)[source]#

Fixes the values of the NeuronInfoLite object.

Parameters:

neuron_info_decoded (Any)

Return type:

NeuronInfoLite

classmethod from_vec_u8(vec_u8)[source]#

Returns a NeuronInfoLite object from a vec_u8.

Parameters:

vec_u8 (List[int])

Return type:

NeuronInfoLite

classmethod list_from_vec_u8(vec_u8)[source]#

Returns a list of NeuronInfoLite objects from a vec_u8.

Parameters:

vec_u8 (List[int])

Return type:

List[NeuronInfoLite]

static get_null_neuron()[source]#
Return type:

NeuronInfoLite

class bittensor.PrometheusInfo[source]#

Dataclass for prometheus info.

block: int#
version: int#
ip: str#
port: int#
ip_type: int#
classmethod fix_decoded_values(prometheus_info_decoded)[source]#

Returns a PrometheusInfo object from a prometheus_info_decoded dictionary.

Parameters:

prometheus_info_decoded (Dict)

Return type:

PrometheusInfo

class bittensor.DelegateInfo[source]#

Dataclass for delegate information. For a lighter version of this class, see DelegateInfoLite().

Parameters:
  • hotkey_ss58 (str) – Hotkey of the delegate for which the information is being fetched.

  • total_stake (int) – Total stake of the delegate.

  • nominators (list[Tuple[str, int]]) – List of nominators of the delegate and their stake.

  • take (float) – Take of the delegate as a percentage.

  • owner_ss58 (str) – Coldkey of the owner.

  • registrations (list[int]) – List of subnets that the delegate is registered on.

  • validator_permits (list[int]) – List of subnets that the delegate is allowed to validate on.

  • return_per_1000 (int) – Return per 1000 TAO, for the delegate over a day.

  • total_daily_return (int) – Total daily return of the delegate.

hotkey_ss58: str#
total_stake: bittensor.utils.balance.Balance#
nominators: List[Tuple[str, bittensor.utils.balance.Balance]]#
owner_ss58: str#
take: float#
validator_permits: List[int]#
registrations: List[int]#
return_per_1000: bittensor.utils.balance.Balance#
total_daily_return: bittensor.utils.balance.Balance#
classmethod fix_decoded_values(decoded)[source]#

Fixes the decoded values.

Parameters:

decoded (Any)

Return type:

DelegateInfo

classmethod from_vec_u8(vec_u8)[source]#

Returns a DelegateInfo object from a vec_u8.

Parameters:

vec_u8 (List[int])

Return type:

Optional[DelegateInfo]

classmethod list_from_vec_u8(vec_u8)[source]#

Returns a list of DelegateInfo objects from a vec_u8.

Parameters:

vec_u8 (List[int])

Return type:

List[DelegateInfo]

classmethod delegated_list_from_vec_u8(vec_u8)[source]#

Returns a list of Tuples of DelegateInfo objects, and Balance, from a vec_u8.

This is the list of delegates that the user has delegated to, and the amount of stake delegated.

Parameters:

vec_u8 (List[int])

Return type:

List[Tuple[DelegateInfo, bittensor.utils.balance.Balance]]

class bittensor.StakeInfo[source]#

Dataclass for stake info.

hotkey_ss58: str#
coldkey_ss58: str#
stake: bittensor.utils.balance.Balance#
classmethod fix_decoded_values(decoded)[source]#

Fixes the decoded values.

Parameters:

decoded (Any)

Return type:

StakeInfo

classmethod from_vec_u8(vec_u8)[source]#

Returns a StakeInfo object from a vec_u8.

Parameters:

vec_u8 (List[int])

Return type:

Optional[StakeInfo]

classmethod list_of_tuple_from_vec_u8(vec_u8)[source]#

Returns a list of StakeInfo objects from a vec_u8.

Parameters:

vec_u8 (List[int])

Return type:

Dict[str, List[StakeInfo]]

classmethod list_from_vec_u8(vec_u8)[source]#

Returns a list of StakeInfo objects from a vec_u8.

Parameters:

vec_u8 (List[int])

Return type:

List[StakeInfo]

class bittensor.SubnetInfo[source]#

Dataclass for subnet info.

netuid: int#
rho: int#
kappa: int#
difficulty: int#
immunity_period: int#
max_allowed_validators: int#
min_allowed_weights: int#
max_weight_limit: float#
scaling_law_power: float#
subnetwork_n: int#
max_n: int#
blocks_since_epoch: int#
tempo: int#
modality: int#
connection_requirements: Dict[str, float]#
emission_value: float#
burn: bittensor.utils.balance.Balance#
owner_ss58: str#
classmethod from_vec_u8(vec_u8)[source]#

Returns a SubnetInfo object from a vec_u8.

Parameters:

vec_u8 (List[int])

Return type:

Optional[SubnetInfo]

classmethod list_from_vec_u8(vec_u8)[source]#

Returns a list of SubnetInfo objects from a vec_u8.

Parameters:

vec_u8 (List[int])

Return type:

List[SubnetInfo]

classmethod fix_decoded_values(decoded)[source]#

Returns a SubnetInfo object from a decoded SubnetInfo dictionary.

Parameters:

decoded (Dict)

Return type:

SubnetInfo

to_parameter_dict()[source]#

Returns a torch tensor or dict of the subnet info.

Return type:

Union[dict[str, Any], bittensor.utils.registration.torch.nn.ParameterDict]

classmethod from_parameter_dict(parameter_dict)[source]#
Parameters:

parameter_dict (Union[dict[str, Any], bittensor.utils.registration.torch.nn.ParameterDict])

Return type:

SubnetInfo

class bittensor.SubnetHyperparameters[source]#

Dataclass for subnet hyperparameters.

rho: int#
kappa: int#
immunity_period: int#
min_allowed_weights: int#
max_weight_limit: float#
tempo: int#
min_difficulty: int#
max_difficulty: int#
weights_version: int#
weights_rate_limit: int#
adjustment_interval: int#
activity_cutoff: int#
registration_allowed: bool#
target_regs_per_interval: int#
min_burn: int#
max_burn: int#
bonds_moving_avg: int#
max_regs_per_block: int#
serving_rate_limit: int#
max_validators: int#
adjustment_alpha: int#
difficulty: int#
commit_reveal_weights_interval: int#
commit_reveal_weights_enabled: bool#
alpha_high: int#
alpha_low: int#
liquid_alpha_enabled: bool#
classmethod from_vec_u8(vec_u8)[source]#

Returns a SubnetHyperparameters object from a vec_u8.

Parameters:

vec_u8 (List[int])

Return type:

Optional[SubnetHyperparameters]

classmethod list_from_vec_u8(vec_u8)[source]#

Returns a list of SubnetHyperparameters objects from a vec_u8.

Parameters:

vec_u8 (List[int])

Return type:

List[SubnetHyperparameters]

classmethod fix_decoded_values(decoded)[source]#

Returns a SubnetInfo object from a decoded SubnetInfo dictionary.

Parameters:

decoded (Dict)

Return type:

SubnetHyperparameters

to_parameter_dict()[source]#

Returns a torch tensor or dict of the subnet hyperparameters.

Return type:

Union[dict[str, Union[int, float, bool]], bittensor.utils.registration.torch.nn.ParameterDict]

classmethod from_parameter_dict(parameter_dict)[source]#
Parameters:

parameter_dict (Union[dict[str, Any], bittensor.utils.registration.torch.nn.ParameterDict])

Return type:

SubnetHyperparameters

class bittensor.IPInfo[source]#

Dataclass for associated IP Info.

ip: str#
ip_type: int#
protocol: int#
encode()[source]#

Returns a dictionary of the IPInfo object that can be encoded.

Return type:

Dict[str, Any]

classmethod from_vec_u8(vec_u8)[source]#

Returns a IPInfo object from a vec_u8.

Parameters:

vec_u8 (List[int])

Return type:

Optional[IPInfo]

classmethod list_from_vec_u8(vec_u8)[source]#

Returns a list of IPInfo objects from a vec_u8.

Parameters:

vec_u8 (List[int])

Return type:

List[IPInfo]

classmethod fix_decoded_values(decoded)[source]#

Returns a SubnetInfo object from a decoded IPInfo dictionary.

Parameters:

decoded (Dict)

Return type:

IPInfo

to_parameter_dict()[source]#

Returns a torch tensor or dict of the subnet IP info.

Return type:

Union[dict[str, Union[str, int]], bittensor.utils.registration.torch.nn.ParameterDict]

classmethod from_parameter_dict(parameter_dict)[source]#
Parameters:

parameter_dict (Union[dict[str, Any], bittensor.utils.registration.torch.nn.ParameterDict])

Return type:

IPInfo

bittensor.ProposalCallData#
class bittensor.ProposalVoteData[source]#

Bases: TypedDict

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object’s

(key, value) pairs

dict(iterable) -> new dictionary initialized as if via:

d = {} for k, v in iterable:

d[k] = v

dict(**kwargs) -> new dictionary initialized with the name=value pairs

in the keyword argument list. For example: dict(one=1, two=2)

Initialize self. See help(type(self)) for accurate signature.

index: int#
threshold: int#
ayes: List[str]#
nays: List[str]#
end: int#
class bittensor.Subtensor(network=None, config=None, _mock=False, log_verbose=True, connection_timeout=600)[source]#

The Subtensor class in Bittensor serves as a crucial interface for interacting with the Bittensor blockchain, facilitating a range of operations essential for the decentralized machine learning network.

This class enables neurons (network participants) to engage in activities such as registering on the network, managing staked weights, setting inter-neuronal weights, and participating in consensus mechanisms.

The Bittensor network operates on a digital ledger where each neuron holds stakes (S) and learns a set of inter-peer weights (W). These weights, set by the neurons themselves, play a critical role in determining the ranking and incentive mechanisms within the network. Higher-ranked neurons, as determined by their contributions and trust within the network, receive more incentives.

The Subtensor class connects to various Bittensor networks like the main finney network or local test networks, providing a gateway to the blockchain layer of Bittensor. It leverages a staked weighted trust system and consensus to ensure fair and distributed incentive mechanisms, where incentives (I) are primarily allocated to neurons that are trusted by the majority of the network.

Additionally, Bittensor introduces a speculation-based reward mechanism in the form of bonds (B), allowing neurons to accumulate bonds in other neurons, speculating on their future value. This mechanism aligns with market-based speculation, incentivizing neurons to make judicious decisions in their inter-neuronal investments.

Example Usage:

# Connect to the main Bittensor network (Finney).
finney_subtensor = subtensor(network='finney')

# Close websocket connection with the Bittensor network.
finney_subtensor.close()

# (Re)creates the websocket connection with the Bittensor network.
finney_subtensor.connect_websocket()

# Register a new neuron on the network.
wallet = bittensor.wallet(...)  # Assuming a wallet instance is created.
success = finney_subtensor.register(wallet=wallet, netuid=netuid)

# Set inter-neuronal weights for collaborative learning.
success = finney_subtensor.set_weights(wallet=wallet, netuid=netuid, uids=[...], weights=[...])

# Speculate by accumulating bonds in other promising neurons.
success = finney_subtensor.delegate(wallet=wallet, delegate_ss58=other_neuron_ss58, amount=bond_amount)

# Get the metagraph for a specific subnet using given subtensor connection
metagraph = subtensor.metagraph(netuid=netuid)

By facilitating these operations, the Subtensor class is instrumental in maintaining the decentralized intelligence and dynamic learning environment of the Bittensor network, as envisioned in its foundational principles and mechanisms described in the NeurIPS paper. paper.

Initializes a Subtensor interface for interacting with the Bittensor blockchain.

Note

Currently subtensor defaults to the finney network. This will change in a future release.

We strongly encourage users to run their own local subtensor node whenever possible. This increases decentralization and resilience of the network. In a future release, local subtensor will become the default and the fallback to finney removed. Please plan ahead for this change. We will provide detailed instructions on how to run a local subtensor node in the documentation in a subsequent release.

Parameters:
  • network (str, optional) – The network name to connect to (e.g., finney, local). This can also be the chain endpoint (e.g., wss://entrypoint-finney.opentensor.ai:443) and will be correctly parsed into the network and chain endpoint. If not specified, defaults to the main Bittensor network.

  • config (bittensor.config, optional) – Configuration object for the subtensor. If not provided, a default configuration is used.

  • _mock (bool, optional) – If set to True, uses a mocked connection for testing purposes.

  • log_verbose (bool)

  • connection_timeout (int)

This initialization sets up the connection to the specified Bittensor network, allowing for various blockchain operations such as neuron registration, stake management, and setting weights.

config[source]#
log_verbose#
_connection_timeout#
_subtensor_errors: Dict[str, Dict[str, str]]#
__str__()[source]#
Return type:

str

__repr__()[source]#
Return type:

str

_get_substrate()[source]#

Establishes a connection to the Substrate node using configured parameters.

classmethod help()[source]#

Print help to stdout.

classmethod add_args(parser, prefix=None)[source]#

Adds command-line arguments to the provided ArgumentParser for configuring the Subtensor settings.

Parameters:
  • parser (argparse.ArgumentParser) – The ArgumentParser object to which the Subtensor arguments will be added.

  • prefix (Optional[str]) – An optional prefix for the argument names. If provided, the prefix is prepended to each argument name.

Arguments added:
–subtensor.network: The Subtensor network flag. Possible values are ‘finney’, ‘test’, ‘archive’, and

‘local’. Overrides the chain endpoint if set.

–subtensor.chain_endpoint: The Subtensor chain endpoint flag. If set, it overrides the network flag. –subtensor._mock: If true, uses a mocked connection to the chain.

Example

parser = argparse.ArgumentParser() Subtensor.add_args(parser)

static determine_chain_endpoint_and_network(network)[source]#

Determines the chain endpoint and network from the passed network or chain_endpoint.

Parameters:

network (str) – The network flag. The choices are: -- finney (main network), -- archive (archive network +300 blocks), -- local (local running network), -- test (test network).

Returns:

The network flag. chain_endpoint (str): The chain endpoint flag. If set, overrides the network argument.

Return type:

network (str)

static setup_config(network, config)[source]#

Sets up and returns the configuration for the Subtensor network and endpoint.

This method determines the appropriate network and chain endpoint based on the provided network string or configuration object. It evaluates the network and endpoint in the following order of precedence: 1. Provided network string. 2. Configured chain endpoint in the config object. 3. Configured network in the config object. 4. Default chain endpoint. 5. Default network.

Parameters:
  • network (str) – The name of the Subtensor network. If None, the network and endpoint will be determined from the config object.

  • config (bittensor.config) – The configuration object containing the network and chain endpoint settings.

Returns:

A tuple containing the formatted WebSocket endpoint URL and the evaluated network name.

Return type:

tuple

close()[source]#

Cleans up resources for this subtensor instance like active websocket connection and active extensions.

nominate(wallet, wait_for_finalization=False, wait_for_inclusion=True)[source]#

Becomes a delegate for the hotkey associated with the given wallet. This method is used to nominate a neuron (identified by the hotkey in the wallet) as a delegate on the Bittensor network, allowing it to participate in consensus and validation processes.

Parameters:
  • wallet (bittensor.wallet) – The wallet containing the hotkey to be nominated.

  • wait_for_finalization (bool, optional) – If True, waits until the transaction is finalized on the blockchain.

  • wait_for_inclusion (bool, optional) – If True, waits until the transaction is included in a block.

Returns:

True if the nomination process is successful, False otherwise.

Return type:

bool

This function is a key part of the decentralized governance mechanism of Bittensor, allowing for the dynamic selection and participation of validators in the network’s consensus process.

delegate(wallet, delegate_ss58=None, amount=None, wait_for_inclusion=True, wait_for_finalization=False, prompt=False)[source]#

Becomes a delegate for the hotkey associated with the given wallet. This method is used to nominate a neuron (identified by the hotkey in the wallet) as a delegate on the Bittensor network, allowing it to participate in consensus and validation processes.

Parameters:
  • wallet (bittensor.wallet) – The wallet containing the hotkey to be nominated.

  • delegate_ss58 (Optional[str]) – The SS58 address of the delegate neuron.

  • amount (Union[Balance, float]) – The amount of TAO to undelegate.

  • wait_for_finalization (bool, optional) – If True, waits until the transaction is finalized on the blockchain.

  • wait_for_inclusion (bool, optional) – If True, waits until the transaction is included in a block.

  • prompt (bool, optional) – If True, prompts for user confirmation before proceeding.

Returns:

True if the nomination process is successful, False otherwise.

Return type:

bool

This function is a key part of the decentralized governance mechanism of Bittensor, allowing for the dynamic selection and participation of validators in the network’s consensus process.

undelegate(wallet, delegate_ss58=None, amount=None, wait_for_inclusion=True, wait_for_finalization=False, prompt=False)[source]#

Removes a specified amount of stake from a delegate neuron using the provided wallet. This action reduces the staked amount on another neuron, effectively withdrawing support or speculation.

Parameters:
  • wallet (bittensor.wallet) – The wallet used for the undelegation process.

  • delegate_ss58 (Optional[str]) – The SS58 address of the delegate neuron.

  • amount (Union[Balance, float]) – The amount of TAO to undelegate.

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

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

  • prompt (bool, optional) – If True, prompts for user confirmation before proceeding.

Returns:

True if the undelegation is successful, False otherwise.

Return type:

bool

This function reflects the dynamic and speculative nature of the Bittensor network, allowing neurons to adjust their stakes and investments based on changing perceptions and performances within the network.

set_take(wallet, delegate_ss58=None, take=0.0, wait_for_inclusion=True, wait_for_finalization=False)[source]#

Set delegate hotkey take :param wallet: The wallet containing the hotkey to be nominated. :type wallet: bittensor.wallet :param delegate_ss58: Hotkey :type delegate_ss58: str, optional :param take: Delegate take on subnet ID :type take: float :param wait_for_finalization: If True, waits until the transaction is finalized on the

blockchain.

Parameters:
  • wait_for_inclusion (bool, optional) – If True, waits until the transaction is included in a block.

  • wallet (bittensor.wallet)

  • delegate_ss58 (Optional[str])

  • take (float)

  • wait_for_finalization (bool, optional)

Returns:

True if the process is successful, False otherwise.

Return type:

bool

This function is a key part of the decentralized governance mechanism of Bittensor, allowing for the dynamic selection and participation of validators in the network’s consensus process.

send_extrinsic(wallet, module, function, params, period=5, wait_for_inclusion=False, wait_for_finalization=False, max_retries=3, wait_time=3, max_wait=20)[source]#

Sends an extrinsic to the Bittensor blockchain using the provided wallet and parameters. This method constructs and submits the extrinsic, handling retries and blockchain communication.

Parameters:
  • wallet (bittensor.wallet) – The wallet associated with the extrinsic.

  • module (str) – The module name for the extrinsic.

  • function (str) – The function name for the extrinsic.

  • params (dict) – The parameters for the extrinsic.

  • period (int, optional) – The number of blocks for the extrinsic to live in the mempool. Defaults to 5.

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

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

  • max_retries (int, optional) – The maximum number of retries for the extrinsic. Defaults to 3.

  • wait_time (int, optional) – The wait time between retries. Defaults to 3.

  • max_wait (int, optional) – The maximum wait time for the extrinsic. Defaults to 20.

Returns:

The receipt of the extrinsic if successful, None otherwise.

Return type:

Optional[ExtrinsicReceipt]

set_weights(wallet, netuid, uids, weights, version_key=bittensor.__version_as_int__, wait_for_inclusion=False, wait_for_finalization=False, prompt=False, max_retries=5)[source]#

Sets the inter-neuronal weights for the specified neuron. This process involves specifying the influence or trust a neuron places on other neurons in the network, which is a fundamental aspect of Bittensor’s decentralized learning architecture.

Parameters:
  • wallet (bittensor.wallet) – The wallet associated with the neuron setting the weights.

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

  • uids (Union[NDArray[np.int64], torch.LongTensor, list]) – The list of neuron UIDs that the weights are being set for.

  • weights (Union[NDArray[np.float32], torch.FloatTensor, list]) – The corresponding weights to be set for each UID.

  • version_key (int, optional) – Version key for compatibility with the network.

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

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

  • prompt (bool, optional) – If True, prompts for user confirmation before proceeding.

  • max_retries (int, optional) – The number of maximum attempts to set weights. (Default: 5)

Returns:

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 shaping the network’s collective intelligence, where each neuron’s learning and contribution are influenced by the weights it sets towards others【81†source】.

_do_set_weights(wallet, uids, vals, netuid, version_key=bittensor.__version_as_int__, wait_for_inclusion=False, wait_for_finalization=False)[source]#

Internal method to send a transaction to the Bittensor blockchain, setting weights for specified neurons. This method constructs and submits the transaction, handling retries and blockchain communication.

Parameters:
  • wallet (bittensor.wallet) – The wallet associated with the neuron setting the weights.

  • uids (List[int]) – List of neuron UIDs for which weights are being set.

  • vals (List[int]) – List of weight values corresponding to each UID.

  • netuid (int) – Unique identifier for the network.

  • version_key (int, optional) – Version key for compatibility with the network.

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

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

Returns:

A tuple containing a success flag and an optional error message.

Return type:

Tuple[bool, Optional[str]]

This method is vital for the dynamic weighting mechanism in Bittensor, where neurons adjust their trust in other neurons based on observed performance and contributions.

commit_weights(wallet, netuid, salt, uids, weights, version_key=bittensor.__version_as_int__, wait_for_inclusion=False, wait_for_finalization=False, prompt=False, max_retries=5)[source]#

Commits a hash of the neuron’s weights to the Bittensor blockchain using the provided wallet. This action serves as a commitment or snapshot of the neuron’s current weight distribution.

Parameters:
  • wallet (bittensor.wallet) – The wallet associated with the neuron committing the weights.

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

  • salt (List[int]) – list of randomly generated integers as salt to generated weighted hash.

  • uids (np.ndarray) – NumPy array of neuron UIDs for which weights are being committed.

  • weights (np.ndarray) – NumPy array of weight values corresponding to each UID.

  • version_key (int, optional) – Version key for compatibility with the network.

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

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

  • prompt (bool, optional) – If True, prompts for user confirmation before proceeding.

  • max_retries (int, optional) – The number of maximum attempts to commit weights. (Default: 5)

Returns:

True if the weight commitment is successful, False otherwise. And msg, a string value describing the success or potential error.

Return type:

Tuple[bool, str]

This function allows neurons to create a tamper-proof record of their weight distribution at a specific point in time, enhancing transparency and accountability within the Bittensor network.

_do_commit_weights(wallet, netuid, commit_hash, wait_for_inclusion=False, wait_for_finalization=False)[source]#

Internal method to send a transaction to the Bittensor blockchain, committing the hash of a neuron’s weights. This method constructs and submits the transaction, handling retries and blockchain communication.

Parameters:
  • wallet (bittensor.wallet) – The wallet associated with the neuron committing the weights.

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

  • commit_hash (str) – The hash of the neuron’s weights to be committed.

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

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

Returns:

A tuple containing a success flag and an optional error message.

Return type:

Tuple[bool, Optional[str]]

This method ensures that the weight commitment is securely recorded on the Bittensor blockchain, providing a verifiable record of the neuron’s weight distribution at a specific point in time.

reveal_weights(wallet, netuid, uids, weights, salt, version_key=bittensor.__version_as_int__, wait_for_inclusion=False, wait_for_finalization=False, prompt=False, max_retries=5)[source]#

Reveals the weights for a specific subnet on the Bittensor blockchain using the provided wallet. This action serves as a revelation of the neuron’s previously committed weight distribution.

Parameters:
  • wallet (bittensor.wallet) – The wallet associated with the neuron revealing the weights.

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

  • uids (np.ndarray) – NumPy array of neuron UIDs for which weights are being revealed.

  • weights (np.ndarray) – NumPy array of weight values corresponding to each UID.

  • salt (np.ndarray) – NumPy array of salt values corresponding to the hash function.

  • version_key (int, optional) – Version key for compatibility with the network.

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

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

  • prompt (bool, optional) – If True, prompts for user confirmation before proceeding.

  • max_retries (int, optional) – The number of maximum attempts to reveal weights. (Default: 5)

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 neurons to reveal their previously committed weight distribution, ensuring transparency and accountability within the Bittensor network.

_do_reveal_weights(wallet, netuid, uids, values, salt, version_key, wait_for_inclusion=False, wait_for_finalization=False)[source]#

Internal method to send a transaction to the Bittensor blockchain, revealing the weights for a specific subnet. This method constructs and submits the transaction, handling retries and blockchain communication.

Parameters:
  • wallet (bittensor.wallet) – The wallet associated with the neuron revealing the weights.

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

  • uids (List[int]) – List of neuron UIDs for which weights are being revealed.

  • values (List[int]) – List of weight values corresponding to each UID.

  • salt (List[int]) – List of salt values corresponding to the hash function.

  • version_key (int) – Version key for compatibility with the network.

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

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

Returns:

A tuple containing a success flag and an optional error message.

Return type:

Tuple[bool, Optional[str]]

This method ensures that the weight revelation is securely recorded on the Bittensor blockchain, providing transparency and accountability for the neuron’s weight distribution.

register(wallet, netuid, wait_for_inclusion=False, wait_for_finalization=True, prompt=False, max_allowed_attempts=3, output_in_place=True, cuda=False, dev_id=0, tpb=256, num_processes=None, update_interval=None, log_verbose=False)[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) – The wallet associated with the neuron to be registered.

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

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

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

  • prompt (bool, optional) – If True, prompts for user confirmation before proceeding.

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

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.

swap_hotkey(wallet, new_wallet, wait_for_inclusion=False, wait_for_finalization=True, prompt=False)[source]#

Swaps an old hotkey with a new hotkey for the specified wallet.

This method initiates an extrinsic to change the hotkey associated with a wallet to a new hotkey. It provides options to wait for inclusion and finalization of the transaction, and to prompt the user for confirmation.

Parameters:
  • wallet (bittensor.wallet) – The wallet whose hotkey is to be swapped.

  • new_wallet (bittensor.wallet) – The new wallet with the hotkey to be set.

  • wait_for_inclusion (bool) – Whether to wait for the transaction to be included in a block. Default is False.

  • wait_for_finalization (bool) – Whether to wait for the transaction to be finalized. Default is True.

  • prompt (bool) – Whether to prompt the user for confirmation before proceeding. Default is False.

Returns:

True if the hotkey swap was successful, False otherwise.

Return type:

bool

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

Facilitates a faucet transaction, allowing new neurons to receive an initial amount of TAO for participating in the network. This function is particularly useful for newcomers to the Bittensor network, enabling them to start with a small stake on testnet only.

Parameters:
  • wallet (bittensor.wallet) – The wallet for which the faucet transaction is to be run.

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

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

  • prompt (bool, optional) – If True, prompts for user confirmation before proceeding.

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

Returns:

True if the faucet transaction is successful, False otherwise.

Return type:

bool

This function is part of Bittensor’s onboarding process, ensuring that new neurons have the necessary resources to begin their journey in the decentralized AI network.

Note

This is for testnet ONLY and is disabled currently. You must build your own staging subtensor chain with the --features pow-faucet argument to enable this.

burned_register(wallet, netuid, wait_for_inclusion=False, wait_for_finalization=True, prompt=False)[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) – The wallet associated with the neuron to be registered.

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

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

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

  • prompt (bool, optional) – If True, prompts for user confirmation before proceeding. Defaults to False.

Returns:

True if the registration is successful, False otherwise.

Return type:

bool

_do_pow_register(netuid, wallet, pow_result, wait_for_inclusion=False, wait_for_finalization=True)[source]#

Sends a (POW) register extrinsic to the chain.

Parameters:
  • netuid (int) – The subnet to register on.

  • wallet (bittensor.wallet) – The wallet to register.

  • pow_result (POWSolution) – The PoW result to register.

  • wait_for_inclusion (bool) – If True, waits for the extrinsic to be included in a block. Default to False.

  • wait_for_finalization (bool) – If True, waits for the extrinsic to be finalized. Default to True.

Returns:

True if the extrinsic was included in a block. error (Optional[str]): None on success or not waiting for inclusion/finalization, otherwise the error

message.

Return type:

success (bool)

_do_burned_register(netuid, wallet, wait_for_inclusion=False, wait_for_finalization=True)[source]#

Performs a burned register extrinsic call to the Subtensor chain.

This method sends a registration transaction to the Subtensor blockchain using the burned register mechanism. It retries the call up to three times with exponential backoff in case of failures.

Parameters:
  • netuid (int) – The network unique identifier to register on.

  • wallet (bittensor.wallet) – The wallet to be registered.

  • wait_for_inclusion (bool) – Whether to wait for the transaction to be included in a block. Default is False.

  • wait_for_finalization (bool) – Whether to wait for the transaction to be finalized. Default is True.

Returns:

A tuple containing a boolean indicating success or failure, and an optional error message.

Return type:

Tuple[bool, Optional[str]]

_do_swap_hotkey(wallet, new_wallet, wait_for_inclusion=False, wait_for_finalization=True)[source]#

Performs a hotkey swap extrinsic call to the Subtensor chain.

Parameters:
  • wallet (bittensor.wallet) – The wallet whose hotkey is to be swapped.

  • new_wallet (bittensor.wallet) – The wallet with the new hotkey to be set.

  • wait_for_inclusion (bool) – Whether to wait for the transaction to be included in a block. Default is

  • False.

  • wait_for_finalization (bool) – Whether to wait for the transaction to be finalized. Default is True.

Returns:

A tuple containing a boolean indicating success or failure, and an optional

error message.

Return type:

Tuple[bool, Optional[str]]

transfer(wallet, dest, amount, wait_for_inclusion=True, wait_for_finalization=False, prompt=False)[source]#

Executes a transfer of funds from the provided wallet to the specified destination address. This function is used to move TAO tokens within the Bittensor network, facilitating transactions between neurons.

Parameters:
  • wallet (bittensor.wallet) – The wallet from which funds are being transferred.

  • dest (str) – The destination public key address.

  • amount (Union[Balance, float]) – The amount of TAO to be transferred.

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

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

  • prompt (bool, optional) – If True, prompts for user confirmation before proceeding.

Returns:

True if the transfer is successful, False otherwise.

Return type:

transfer_extrinsic (bool)

This function is essential for the fluid movement of tokens in the network, supporting various economic activities such as staking, delegation, and reward distribution.

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) – The wallet from which the transfer is initiated.

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

  • value (Union[Balance, float, int]) – 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:

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.

_do_transfer(wallet, dest, transfer_balance, wait_for_inclusion=True, wait_for_finalization=False)[source]#

Sends a transfer extrinsic to the chain.

Parameters:
  • wallet (bittensor.wallet()) – Wallet object.

  • dest (str) – Destination public key address.

  • transfer_balance (Balance()) – Amount to transfer.

  • wait_for_inclusion (bool) – If true, waits for inclusion.

  • wait_for_finalization (bool) – If true, waits for finalization.

Returns:

True if transfer was successful. block_hash (str): Block hash of the transfer. On success and if wait_for_ finalization/inclusion is

True.

error (str): Error message if transfer failed.

Return type:

success (bool)

get_existential_deposit(block=None)[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]) – Block number at which to query the deposit amount. If None, the current block is used.

Returns:

The existential deposit amount, or None if the query fails.

Return type:

Optional[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.

register_subnetwork(wallet, wait_for_inclusion=False, wait_for_finalization=True, prompt=False)[source]#

Registers a new subnetwork on the Bittensor network using the provided wallet. This function is used for the creation and registration of subnetworks, which are specialized segments of the overall Bittensor network.

Parameters:
  • wallet (bittensor.wallet) – The wallet to be used for registration.

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

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

  • prompt (bool, optional) – If True, prompts for user confirmation before proceeding.

Returns:

True if the subnetwork registration is successful, False otherwise.

Return type:

bool

This function allows for the expansion and diversification of the Bittensor network, supporting its decentralized and adaptable architecture.

set_hyperparameter(wallet, netuid, parameter, value, wait_for_inclusion=False, wait_for_finalization=True, prompt=False)[source]#

Sets a specific hyperparameter for a given subnetwork on the Bittensor blockchain. This action involves adjusting network-level parameters, influencing the behavior and characteristics of the subnetwork.

Parameters:
  • wallet (bittensor.wallet) – The wallet used for setting the hyperparameter.

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

  • parameter (str) – The name of the hyperparameter to be set.

  • value – The new value for the hyperparameter.

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

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

  • prompt (bool, optional) – If True, prompts for user confirmation before proceeding.

Returns:

True if the hyperparameter setting is successful, False otherwise.

Return type:

bool

This function plays a critical role in the dynamic governance and adaptability of the Bittensor network, allowing for fine-tuning of network operations and characteristics.

serve(wallet, ip, port, protocol, netuid, placeholder1=0, placeholder2=0, wait_for_inclusion=False, wait_for_finalization=True)[source]#

Registers a neuron’s serving endpoint on the Bittensor network. This function announces the IP address and port where the neuron is available to serve requests, facilitating peer-to-peer communication within the network.

Parameters:
  • wallet (bittensor.wallet) – The wallet associated with the neuron being served.

  • ip (str) – The IP address of the serving neuron.

  • port (int) – The port number on which the neuron is serving.

  • protocol (int) – The protocol type used by the neuron (e.g., GRPC, HTTP).

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

  • placeholder1 (int, optional) – Placeholder parameter for future extensions. Default is 0.

  • placeholder2 (int, optional) – Placeholder parameter for future extensions. Default is 0.

  • wait_for_inclusion (bool, optional) – Waits for the transaction to be included in a block. Default is False.

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

Returns:

True if the serve registration is successful, False otherwise.

Return type:

bool

This function is essential for establishing the neuron’s presence in the network, enabling it to participate in the decentralized machine learning processes of Bittensor.

serve_axon(netuid, axon, wait_for_inclusion=False, wait_for_finalization=True)[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.Axon) – The Axon instance to be registered for serving.

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

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

Returns:

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.

_do_serve_axon(wallet, call_params, wait_for_inclusion=False, wait_for_finalization=True)[source]#

Internal method to submit a serve axon transaction to the Bittensor blockchain. This method creates and submits a transaction, enabling a neuron’s Axon to serve requests on the network.

Parameters:
  • wallet (bittensor.wallet) – The wallet associated with the neuron.

  • call_params (AxonServeCallParams) – Parameters required for the serve axon call.

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

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

Returns:

A tuple containing a success flag and an optional error message.

Return type:

Tuple[bool, Optional[str]]

This function is crucial for initializing and announcing a neuron’s Axon service on the network, enhancing the decentralized computation capabilities of Bittensor.

serve_prometheus(wallet, port, netuid, wait_for_inclusion=False, wait_for_finalization=True)[source]#
Parameters:
  • wallet (bittensor.wallet)

  • port (int)

  • netuid (int)

  • wait_for_inclusion (bool)

  • wait_for_finalization (bool)

Return type:

bool

_do_serve_prometheus(wallet, call_params, wait_for_inclusion=False, wait_for_finalization=True)[source]#

Sends a serve prometheus extrinsic to the chain. :param wallet: Wallet object. :type wallet: bittensor.wallet() :param call_params: Prometheus serve call parameters. :type call_params: PrometheusServeCallParams() :param wait_for_inclusion: If true, waits for inclusion. :type wait_for_inclusion: bool :param wait_for_finalization: If true, waits for finalization. :type wait_for_finalization: bool

Returns:

True if serve prometheus was successful. error (Optional[str]()): Error message if serve prometheus failed, None otherwise.

Return type:

success (bool)

Parameters:
_do_associate_ips(wallet, ip_info_list, netuid, wait_for_inclusion=False, wait_for_finalization=True)[source]#

Sends an associate IPs extrinsic to the chain.

Parameters:
  • wallet (bittensor.wallet()) – Wallet object.

  • ip_info_list (List[IPInfo]()) – List of IPInfo objects.

  • netuid (int) – Netuid to associate IPs to.

  • wait_for_inclusion (bool) – If true, waits for inclusion.

  • wait_for_finalization (bool) – If true, waits for finalization.

Returns:

True if associate IPs was successful. error (Optional[str]()): Error message if associate IPs failed, None otherwise.

Return type:

success (bool)

add_stake(wallet, hotkey_ss58=None, amount=None, wait_for_inclusion=True, wait_for_finalization=False, prompt=False)[source]#

Adds the specified amount of stake to a neuron identified by the hotkey SS58 address. Staking is a fundamental process in the Bittensor network that enables neurons to participate actively and earn incentives.

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

  • hotkey_ss58 (Optional[str]) – The SS58 address of the hotkey associated with the neuron.

  • amount (Union[Balance, float]) – The amount of TAO to stake.

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

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

  • prompt (bool, optional) – If True, prompts for user confirmation before proceeding.

Returns:

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 rewards in line with Bittensor’s consensus and reward mechanisms.

add_stake_multiple(wallet, hotkey_ss58s, amounts=None, wait_for_inclusion=True, wait_for_finalization=False, prompt=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) – The wallet used for staking.

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

  • amounts (List[Union[Balance, float]], optional) – Corresponding amounts of TAO to stake for each hotkey.

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

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

  • prompt (bool, optional) – If True, prompts for user confirmation before proceeding.

Returns:

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.

_do_stake(wallet, hotkey_ss58, amount, wait_for_inclusion=True, wait_for_finalization=False)[source]#

Sends a stake extrinsic to the chain.

Parameters:
  • wallet (bittensor.wallet()) – Wallet object that can sign the extrinsic.

  • hotkey_ss58 (str) – Hotkey ss58 address to stake to.

  • amount (Balance()) – Amount to stake.

  • wait_for_inclusion (bool) – If true, waits for inclusion before returning.

  • wait_for_finalization (bool) – If true, waits for finalization before returning.

Returns:

True if the extrinsic was successful.

Return type:

success (bool)

Raises:

StakeError – If the extrinsic failed.

unstake_multiple(wallet, hotkey_ss58s, amounts=None, wait_for_inclusion=True, wait_for_finalization=False, prompt=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) – 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.

  • amounts (List[Union[Balance, float]], optional) – The amounts of TAO to unstake from each hotkey. If not provided, unstakes all available stakes.

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

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

  • prompt (bool, optional) – If True, prompts for user confirmation before proceeding.

Returns:

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.

unstake(wallet, hotkey_ss58=None, amount=None, wait_for_inclusion=True, wait_for_finalization=False, prompt=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) – 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.

  • amount (Union[Balance, float], optional) – The amount of TAO to unstake. If not specified, unstakes all.

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

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

  • prompt (bool, optional) – If True, prompts for user confirmation before proceeding.

Returns:

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.

_do_unstake(wallet, hotkey_ss58, amount, wait_for_inclusion=True, wait_for_finalization=False)[source]#

Sends an unstake extrinsic to the chain.

Parameters:
  • wallet (bittensor.wallet()) – Wallet object that can sign the extrinsic.

  • hotkey_ss58 (str) – Hotkey ss58 address to unstake from.

  • amount (Balance()) – Amount to unstake.

  • wait_for_inclusion (bool) – If true, waits for inclusion before returning.

  • wait_for_finalization (bool) – If true, waits for finalization before returning.

Returns:

True if the extrinsic was successful.

Return type:

success (bool)

Raises:

StakeError – If the extrinsic failed.

set_childkey_take(wallet, hotkey, take, netuid, wait_for_inclusion=True, wait_for_finalization=False, prompt=False)[source]#

Sets a childkey take extrinsic on the subnet.

Parameters:
  • wallet (bittensor.wallet()) – Wallet object that can sign the extrinsic.

  • hotkey (str) – (str): Hotkey ss58 address of the child for which take is getting set.

  • netuid (int) – Unique identifier of for the subnet.

  • take (float) – Value of childhotkey take on subnet.

  • wait_for_inclusion (bool) – If true, waits for inclusion before returning.

  • wait_for_finalization (bool) – If true, waits for finalization before returning.

  • prompt (bool, optional) – If True, prompts for user confirmation before proceeding.

Returns:

True if the extrinsic was successful.

Return type:

success (bool)

Raises:

ChildHotkeyError – If the extrinsic failed.

_do_set_childkey_take(wallet, hotkey, take, netuid, wait_for_inclusion=True, wait_for_finalization=False)[source]#

Sends a set_children hotkey extrinsic on the chain.

Parameters:
  • wallet (bittensor.wallet()) – Wallet object that can sign the extrinsic.

  • hotkey (str) – (str): Hotkey ss58 address of the wallet for which take is getting set.

  • take (int) – (int): The take that this ss58 hotkey will have if assigned as a child hotkey as u16 value.

  • netuid (int) – Unique identifier for the network.

  • wait_for_inclusion (bool) – If true, waits for inclusion before returning.

  • wait_for_finalization (bool) – If true, waits for finalization before returning.

Returns:

True if the extrinsic was successful.

Return type:

success (bool)

set_children(wallet, hotkey, children_with_proportions, netuid, wait_for_inclusion=True, wait_for_finalization=False, prompt=False)[source]#

Sets a children hotkeys extrinsic on the subnet.

Parameters:
  • wallet (bittensor.wallet()) – Wallet object that can sign the extrinsic.

  • hotkey (str) – (str): Hotkey ss58 address of the parent.

  • netuid (int) – Unique identifier of for the subnet.

  • children_with_proportions (List[Tuple[float, str]]) – List of (proportion, child_ss58) pairs.

  • wait_for_inclusion (bool) – If true, waits for inclusion before returning.

  • wait_for_finalization (bool) – If true, waits for finalization before returning.

  • prompt (bool, optional) – If True, prompts for user confirmation before proceeding.

Returns:

True if the extrinsic was successful.

Return type:

success (bool)

Raises:

ChildHotkeyError – If the extrinsic failed.

_do_set_children(wallet, hotkey, children, netuid, wait_for_inclusion=True, wait_for_finalization=False)[source]#

Sends a set_children hotkey extrinsic on the chain.

Parameters:
  • wallet (bittensor.wallet()) – Wallet object that can sign the extrinsic.

  • hotkey (str) – (str): Hotkey ss58 address of the parent.

  • children (List[Tuple[int, str]]) – (List[Tuple[int, str]]): A list of tuples containing the hotkey ss58 addresses of the children and their proportions as u16 MAX standardized values.

  • netuid (int) – Unique identifier for the network.

  • wait_for_inclusion (bool) – If true, waits for inclusion before returning.

  • wait_for_finalization (bool) – If true, waits for finalization before returning.

Returns:

True if the extrinsic was successful.

Return type:

success (bool)

check_in_arbitration(ss58_address)[source]#

Checks storage function to see if the provided coldkey is in arbitration. If 0, swap has not been called on this key. If 1, swap has been called once, so the key is not in arbitration. If >1, swap has been called with multiple destinations, and the key is thus in arbitration.

Parameters:

ss58_address (str)

Return type:

int

get_remaining_arbitration_period(coldkey_ss58, block=None)[source]#

Retrieves the remaining arbitration period for a given coldkey. :param coldkey_ss58: The SS58 address of the coldkey. :type coldkey_ss58: str :param block: The block number to query. If None, uses the latest block. :type block: Optional[int], optional

Returns:

The remaining arbitration period in blocks, or 0 if not found.

Return type:

Optional[int]

Parameters:
  • coldkey_ss58 (str)

  • block (Optional[int])

register_senate(wallet, wait_for_inclusion=True, wait_for_finalization=False, prompt=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) – The wallet associated with the neuron from which the stake is being removed.

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

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

  • prompt (bool, optional) – If True, prompts for user confirmation before proceeding.

Returns:

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.

leave_senate(wallet, wait_for_inclusion=True, wait_for_finalization=False, prompt=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) – The wallet associated with the neuron from which the stake is being removed.

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

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

  • prompt (bool, optional) – If True, prompts for user confirmation before proceeding.

Returns:

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.

vote_senate(wallet, proposal_hash, proposal_idx, vote, wait_for_inclusion=True, wait_for_finalization=False, prompt=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) – The wallet associated with the neuron from which the stake is being removed.

  • proposal_hash (str) – The hash of the proposal being voted on.

  • proposal_idx (int) – The index of the proposal being voted on.

  • vote (bool) – The vote to be cast (True for yes, False for no).

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

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

  • prompt (bool, optional) – If True, prompts for user confirmation before proceeding.

Returns:

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.

is_senate_member(hotkey_ss58, block=None)[source]#

Checks if a given neuron (identified by its hotkey SS58 address) is a member of the Bittensor senate. The senate is a key governance body within the Bittensor network, responsible for overseeing and approving various network operations and proposals.

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

  • block (Optional[int]) – The blockchain block number at which to check senate membership.

Returns:

True if the neuron is a senate member at the given block, False otherwise.

Return type:

bool

This function is crucial for understanding the governance dynamics of the Bittensor network and for identifying the neurons that hold decision-making power within the network.

get_vote_data(proposal_hash, block=None)[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 to query the voting data.

Returns:

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

Return type:

Optional[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.

get_proposal_vote_data#
get_senate_members(block=None)[source]#

Retrieves the list of current senate members from the Bittensor blockchain. Senate members are responsible for governance and decision-making within the network.

Parameters:

block (Optional[int]) – The blockchain block number at which to retrieve the senate members.

Returns:

A list of SS58 addresses of current senate members, or None if not available.

Return type:

Optional[List[str]]

Understanding the composition of the senate is key to grasping the governance structure and decision-making authority within the Bittensor network.

get_proposal_call_data(proposal_hash, block=None)[source]#

Retrieves the call data of a specific proposal on the Bittensor blockchain. This data provides detailed information about the proposal, including its purpose and specifications.

Parameters:
  • proposal_hash (str) – The hash of the proposal.

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

Returns:

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

Return type:

Optional[GenericCall]

This function is crucial for analyzing the types of proposals made within the network and the specific changes or actions they intend to implement or address.

get_proposal_hashes(block=None)[source]#

Retrieves the list of proposal hashes currently present on the Bittensor blockchain. Each hash uniquely identifies a proposal made within the network.

Parameters:

block (Optional[int]) – The blockchain block number to query the proposal hashes.

Returns:

A list of proposal hashes, or None if not available.

Return type:

Optional[List[str]]

This function enables tracking and reviewing the proposals made in the network, offering insights into the active governance and decision-making processes.

get_proposals(block=None)[source]#

Retrieves all active proposals on the Bittensor blockchain, along with their call and voting data. This comprehensive view allows for a thorough understanding of the proposals and their reception by the senate.

Parameters:

block (Optional[int]) – The blockchain block number to query the proposals.

Returns:

A dictionary mapping

proposal hashes to their corresponding call and vote data, or None if not available.

Return type:

Optional[Dict[str, Tuple[bittensor.ProposalCallData, bittensor.ProposalVoteData]]]

This function is integral for analyzing the governance activity on the Bittensor network, providing a holistic view of the proposals and their impact or potential changes within the network.

root_register(wallet, wait_for_inclusion=False, wait_for_finalization=True, prompt=False)[source]#

Registers the neuron associated with the wallet on the root network. This process is integral for participating in the highest layer of decision-making and governance within the Bittensor network.

Parameters:
  • wallet (bittensor.wallet) – The wallet associated with the neuron to be registered on the root network.

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

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

  • prompt (bool, optional) – If True, prompts for user confirmation before proceeding.

Returns:

True if the registration on the root network is successful, False otherwise.

Return type:

bool

This function enables neurons to engage in the most critical and influential aspects of the network’s governance, signifying a high level of commitment and responsibility in the Bittensor ecosystem.

_do_root_register(wallet, wait_for_inclusion=False, wait_for_finalization=True)[source]#
Parameters:
  • wallet (bittensor.wallet)

  • wait_for_inclusion (bool)

  • wait_for_finalization (bool)

Return type:

Tuple[bool, Optional[str]]

root_set_weights(wallet, netuids, weights, version_key=0, wait_for_inclusion=False, wait_for_finalization=False, prompt=False)[source]#

Sets the weights for neurons on the root network. This action is crucial for defining the influence and interactions of neurons at the root level of the Bittensor network.

Parameters:
  • wallet (bittensor.wallet) – The wallet associated with the neuron setting the weights.

  • netuids (Union[NDArray[np.int64], torch.LongTensor, list]) – The list of neuron UIDs for which weights are being set.

  • weights (Union[NDArray[np.float32], torch.FloatTensor, list]) – The corresponding weights to be set for each UID.

  • version_key (int, optional) – Version key for compatibility with the network.

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

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

  • prompt (bool, optional) – If True, prompts for user confirmation before proceeding.

Returns:

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

Return type:

bool

This function plays a pivotal role in shaping the root network’s collective intelligence and decision-making processes, reflecting the principles of decentralized governance and collaborative learning in Bittensor.

_do_set_root_weights(wallet, uids, vals, netuid=0, version_key=bittensor.__version_as_int__, wait_for_inclusion=False, wait_for_finalization=False)[source]#

Internal method to send a transaction to the Bittensor blockchain, setting weights for specified neurons on root. This method constructs and submits the transaction, handling retries and blockchain communication.

Parameters:
  • wallet (bittensor.wallet) – The wallet associated with the neuron setting the weights.

  • uids (List[int]) – List of neuron UIDs for which weights are being set.

  • vals (List[int]) – List of weight values corresponding to each UID.

  • netuid (int) – Unique identifier for the network.

  • version_key (int, optional) – Version key for compatibility with the network.

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

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

Returns:

A tuple containing a success flag and an optional error message.

Return type:

Tuple[bool, Optional[str]]

This method is vital for the dynamic weighting mechanism in Bittensor, where neurons adjust their trust in other neurons based on observed performance and contributions on the root network.

query_identity(key, block=None)[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.

Note

See the Bittensor CLI documentation for supported identity parameters.

Parameters:
  • key (str) – The key used to query the neuron’s identity, typically the neuron’s SS58 address.

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

Returns:

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

Return type:

result (dict)

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.

update_identity(wallet, identified=None, params=None, wait_for_inclusion=True, wait_for_finalization=False)[source]#

Updates the identity of a neuron on the Bittensor blockchain. This function allows neurons to modify their identity attributes, reflecting changes in their roles, stakes, or other network-specific parameters.

Note

See the Bittensor CLI documentation for supported identity parameters.

Parameters:
  • wallet (bittensor.wallet) – The wallet associated with the neuron whose identity is being updated.

  • identified (str, optional) – The identified SS58 address of the neuron. Defaults to the wallet’s coldkey address.

  • params (dict, optional) – A dictionary of parameters to update in the neuron’s identity.

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

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

Returns:

True if the identity update is successful, False otherwise.

Return type:

bool

This function plays a vital role in maintaining the accuracy and currency of neuron identities in the Bittensor network, ensuring that the network’s governance and consensus mechanisms operate effectively.

commit(wallet, netuid, data)[source]#

Commits arbitrary data to the Bittensor network by publishing metadata.

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

get_commitment(netuid, uid, block=None)[source]#

Retrieves the on-chain commitment for a specific neuron in the Bittensor network.

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.

Returns:

The commitment data as a string.

Return type:

str

query_subtensor(name, block=None, 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.

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

Returns:

An object containing the requested data.

Return type:

query_response (ScaleType)

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.

query_map_subtensor(name, block=None, 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.

  • params (Optional[List[object]], optional) – 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:

QueryMapResult

This function is particularly useful for analyzing and understanding complex network structures and relationships within the Bittensor ecosystem, such as inter-neuronal connections and stake distributions.

query_constant(module_name, constant_name, block=None)[source]#

Retrieves a constant from the specified module on the Bittensor blockchain. This function is used to access fixed parameters or values defined within the blockchain’s modules, which are essential for understanding the network’s configuration and rules.

Parameters:
  • module_name (str) – The name of the module containing the constant.

  • constant_name (str) – The name of the constant to retrieve.

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

Returns:

The value of the constant if found, None otherwise.

Return type:

Optional[ScaleType]

Constants queried through this function can include critical network parameters such as inflation rates, consensus rules, or validation thresholds, providing a deeper understanding of the Bittensor network’s operational parameters.

query_module(module, name, block=None, 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.

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

Returns:

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

Return type:

Optional[ScaleType]

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.

query_map(module, name, block=None, 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.

  • name (str) – The specific storage function within the module to query.

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

  • params (Optional[List[object]], optional) – Parameters to be passed to the query.

Returns:

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

Return type:

result (QueryMapResult)

This function is particularly useful for retrieving detailed and structured data from various blockchain modules, offering insights into the network’s state and the relationships between its different components.

state_call(method, data, block=None)[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.

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.

query_runtime_api(runtime_api, method, params, block=None)[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[List[ParamWithTypes]], optional) – The parameters to pass to the method call.

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

Returns:

The Scale Bytes encoded result from the runtime API call, or None if the call fails.

Return type:

Optional[bytes]

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

_encode_params(call_definition, params)[source]#

Returns a hex encoded string of the params using their types.

Parameters:
Return type:

str

_get_hyperparameter(param_name, netuid, block=None)[source]#

Retrieves a specified hyperparameter for a specific subnet.

Parameters:
  • param_name (str) – The name of the hyperparameter to retrieve.

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

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

Returns:

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

otherwise.

Return type:

Optional[Union[int, float]]

rho(netuid, block=None)[source]#

Retrieves the ‘Rho’ hyperparameter for a specified subnet within the Bittensor network. ‘Rho’ represents the global inflation rate, which directly influences the network’s token emission rate and economic model.

Note

This is currently fixed such that the Bittensor blockchain emmits 7200 Tao per day.

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

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

Returns:

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

Return type:

Optional[int]

Mathematical Context:

Rho (p) is calculated based on the network’s target inflation and actual neuron staking. It adjusts the emission rate of the TAO token to balance the network’s economy and dynamics. The formula for Rho is defined as: p = (Staking_Target / Staking_Actual) * Inflation_Target. Here, Staking_Target and Staking_Actual represent the desired and actual total stakes in the network, while Inflation_Target is the predefined inflation rate goal.

‘Rho’ is essential for understanding the network’s economic dynamics, affecting the reward distribution and incentive structures across the network’s neurons.

kappa(netuid, block=None)[source]#

Retrieves the ‘Kappa’ hyperparameter for a specified subnet. ‘Kappa’ is a critical parameter in the Bittensor network that controls the distribution of stake weights among neurons, impacting their rankings and incentive allocations.

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

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

Returns:

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

Return type:

Optional[float]

Mathematical Context:

Kappa (κ) is used in the calculation of neuron ranks, which determine their share of network incentives. It is derived from the softmax function applied to the inter-neuronal weights set by each neuron. The formula for Kappa is: κ_i = exp(w_i) / Σ(exp(w_j)), where w_i represents the weight set by neuron i, and the denominator is the sum of exponential weights set by all neurons. This mechanism ensures a normalized and probabilistic distribution of ranks based on relative weights.

Understanding ‘Kappa’ is crucial for analyzing stake dynamics and the consensus mechanism within the network, as it plays a significant role in neuron ranking and incentive allocation processes.

difficulty(netuid, block=None)[source]#

Retrieves the ‘Difficulty’ hyperparameter for a specified subnet in the Bittensor network. This parameter is instrumental in determining the computational challenge required for neurons to participate in consensus and validation processes.

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

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

Returns:

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

Return type:

Optional[int]

The ‘Difficulty’ parameter directly impacts the network’s security and integrity by setting the computational effort required for validating transactions and participating in the network’s consensus mechanism.

recycle(netuid, block=None)[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.

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.

immunity_period(netuid, block=None)[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.

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.

validator_batch_size(netuid, block=None)[source]#

Returns network ValidatorBatchSize hyper parameter.

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

  • block (Optional[int]) – The block number to retrieve the parameter from. If None, the latest block is used. Default is None.

Returns:

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

or the parameter is not found.

Return type:

Optional[int]

validator_prune_len(netuid, block=None)[source]#

Returns network ValidatorPruneLen hyper parameter.

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

  • block (Optional[int]) – The block number to retrieve the parameter from. If None, the latest block

  • None. (is used. Default is)

Returns:

The value of the ValidatorPruneLen hyperparameter, or None if the subnetwork does not exist or the parameter is not found.

Return type:

Optional[int]

validator_logits_divergence(netuid, block=None)[source]#

Returns network ValidatorLogitsDivergence hyper parameter.

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

  • block (Optional[int]) – The block number to retrieve the parameter from. If None, the latest block

  • None. (is used. Default is)

Returns:

The value of the ValidatorLogitsDivergence hyperparameter, or None if the subnetwork does not exist or the parameter is not found.

Return type:

Optional[float]

validator_sequence_length(netuid, block=None)[source]#

Returns network ValidatorSequenceLength hyperparameter.

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

  • block (Optional[int], optional) – The block number to retrieve the parameter from. If None, the latest block is used. Default is None.

Returns:

The value of the ValidatorSequenceLength hyperparameter, or None if the subnetwork does

not exist or the parameter is not found.

Return type:

Optional[int]

validator_epochs_per_reset(netuid, block=None)[source]#

Returns network ValidatorEpochsPerReset hyperparameter.

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

  • block (Optional[int], optional) – The block number to retrieve the parameter from. If None, the latest block is used. Default is None.

Returns:

The value of the ValidatorEpochsPerReset hyperparameter, or None if the subnetwork does

not exist or the parameter is not found.

Return type:

Optional[int]

validator_epoch_length(netuid, block=None)[source]#

Returns network ValidatorEpochLen hyperparameter.

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

  • block (Optional[int], optional) – The block number to retrieve the parameter from. If None, the latest block is used. Default is None.

Returns:

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

exist or the parameter is not found.

Return type:

Optional[int]

validator_exclude_quantile(netuid, block=None)[source]#

Returns network ValidatorExcludeQuantile hyperparameter.

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

  • block (Optional[int], optional) – The block number to retrieve the parameter from. If None, the latest block is used. Default is None.

Returns:

The value of the ValidatorExcludeQuantile hyperparameter, or None if the subnetwork does not exist or the parameter is not found.

Return type:

Optional[float]

max_allowed_validators(netuid, block=None)[source]#

Returns network ValidatorExcludeQuantile hyperparameter.

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

  • block (Optional[int], optional) – The block number to retrieve the parameter from. If None, the latest block is used. Default is None.

Returns:

The value of the ValidatorExcludeQuantile hyperparameter, or None if the subnetwork

does not exist or the parameter is not found.

Return type:

Optional[float]

min_allowed_weights(netuid, block=None)[source]#

Returns network MinAllowedWeights hyperparameter.

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

  • block (Optional[int], optional) – The block number to retrieve the parameter from. If None, the latest block is used. Default is None.

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]

max_weight_limit(netuid, block=None)[source]#

Returns network MaxWeightsLimit hyperparameter.

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

  • block (Optional[int], optional) – The block number to retrieve the parameter from. If None, the latest block is used. Default is None.

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]

adjustment_alpha(netuid, block=None)[source]#

Returns network AdjustmentAlpha hyperparameter.

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

  • block (Optional[int], optional) – The block number to retrieve the parameter from. If None, the latest block is used. Default is None.

Returns:

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

exist or the parameter is not found.

Return type:

Optional[float]

bonds_moving_avg(netuid, block=None)[source]#

Returns network BondsMovingAverage hyperparameter.

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

  • block (Optional[int], optional) – The block number to retrieve the parameter from. If None, the latest block is used. Default is None.

Returns:

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

exist or the parameter is not found.

Return type:

Optional[float]

scaling_law_power(netuid, block=None)[source]#

Returns network ScalingLawPower hyper parameter

Parameters:
  • netuid (int)

  • block (Optional[int])

Return type:

Optional[float]

synergy_scaling_law_power(netuid, block=None)[source]#

Returns network ScalingLawPower hyperparameter.

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

  • block (Optional[int], optional) – The block number to retrieve the parameter from. If None, the latest block is used. Default is None.

Returns:

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

exist or the parameter is not found.

Return type:

Optional[float]

subnetwork_n(netuid, block=None)[source]#

Returns network SubnetworkN hyperparameter.

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

  • block (Optional[int], optional) – The block number to retrieve the parameter from. If None, the latest block is used. Default is None.

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]

max_n(netuid, block=None)[source]#

Returns network MaxAllowedUids hyperparameter.

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

  • block (Optional[int], optional) – The block number to retrieve the parameter from. If None, the latest block is used. Default is None.

Returns:

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

exist or the parameter is not found.

Return type:

Optional[int]

blocks_since_epoch(netuid, block=None)[source]#

Returns network BlocksSinceEpoch hyperparameter.

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

  • block (Optional[int], optional) – The block number to retrieve the parameter from. If None, the latest block is used. Default is None.

Returns:

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

exist or the parameter is not found.

Return type:

Optional[int]

blocks_since_last_update(netuid, uid)[source]#

Returns the number of blocks since the last update for a specific UID in the subnetwork.

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]

weights_rate_limit(netuid)[source]#

Returns network WeightsSetRateLimit hyperparameter.

Parameters:

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

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]

tempo(netuid, block=None)[source]#

Returns network Tempo hyperparameter.

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

  • block (Optional[int], optional) – The block number to retrieve the parameter from. If None, the latest block is used. Default is None.

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]

get_total_stake_for_hotkey(ss58_address, block=None)[source]#

Returns the total stake held on a hotkey including delegative.

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

  • block (Optional[int], optional) – The block number to retrieve the stake from. If None, the latest block is used. Default is None.

Returns:

The total stake held on the hotkey, or None if the hotkey does not

exist or the stake is not found.

Return type:

Optional[Balance]

get_total_stake_for_coldkey(ss58_address, block=None)[source]#

Returns the total stake held on a coldkey.

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

  • block (Optional[int], optional) – The block number to retrieve the stake from. If None, the latest block is used. Default is None.

Returns:

The total stake held on the coldkey, or None if the coldkey does not

exist or the stake is not found.

Return type:

Optional[Balance]

get_stake_for_coldkey_and_hotkey(hotkey_ss58, coldkey_ss58, block=None)[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.

  • block (Optional[int], optional) – The block number to retrieve the stake from. If None, the latest block is used. Default is None.

Returns:

The stake under the coldkey - hotkey pairing, or None if the pairing does not

exist or the stake is not found.

Return type:

Optional[Balance]

get_stake(hotkey_ss58, block=None)[source]#

Returns a list of stake tuples (coldkey, balance) for each delegating coldkey including the owner.

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

  • block (Optional[int], optional) – The block number to retrieve the stakes from. If None, the latest block is used. Default is None.

Returns:

A list of tuples, each containing a coldkey SS58 address and the corresponding

balance staked by that coldkey.

Return type:

List[Tuple[str, Balance]]

does_hotkey_exist(hotkey_ss58, block=None)[source]#

Returns true if the hotkey is known by the chain and there are accounts.

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

  • block (Optional[int], optional) – The block number to check the hotkey against. If None, the latest block is used. Default is None.

Returns:

True if the hotkey is known by the chain and there are accounts, False otherwise.

Return type:

bool

get_hotkey_owner(hotkey_ss58, block=None)[source]#

Returns the coldkey owner of the passed hotkey.

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

  • block (Optional[int], optional) – The block number to check the hotkey owner against. If None, the latest block is used. Default is None.

Returns:

The SS58 address of the coldkey owner, or None if the hotkey does not exist or the owner

is not found.

Return type:

Optional[str]

get_axon_info(netuid, hotkey_ss58, block=None)[source]#

Returns the axon information for this hotkey account.

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

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

  • block (Optional[int], optional) – The block number to retrieve the axon information from. If None, the latest block is used. Default is None.

Returns:

An AxonInfo object containing the axon information, or None if the axon information

is not found.

Return type:

Optional[AxonInfo]

get_prometheus_info(netuid, hotkey_ss58, block=None)[source]#

Returns the prometheus information for this hotkey account.

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

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

  • block (Optional[int], optional) – The block number to retrieve the prometheus information from. If None, the latest block is used. Default is None.

Returns:

A PrometheusInfo object containing the prometheus information, or None if the

prometheus information is not found.

Return type:

Optional[PrometheusInfo]

property block: int#

Returns current chain block. :returns: Current chain block. :rtype: block (int)

Return type:

int

total_issuance(block=None)[source]#

Retrieves the total issuance of the Bittensor network’s native token (Tao) as of a specific blockchain block. This represents the total amount of currency that has been issued or mined on the network.

Parameters:

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

Returns:

The total issuance of TAO, represented as a Balance object.

Return type:

Balance

The total issuance is a key economic indicator in the Bittensor network, reflecting the overall supply of the currency and providing insights into the network’s economic health and inflationary trends.

total_stake(block=None)[source]#

Retrieves the total amount of TAO staked on the Bittensor network as of a specific blockchain block. This represents the cumulative stake across all neurons in the network, indicating the overall level of participation and investment by the network’s participants.

Parameters:

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

Returns:

The total amount of TAO staked on the network, represented as a Balance object.

Return type:

Balance

The total stake is an important metric for understanding the network’s security, governance dynamics, and the level of commitment by its participants. It is also a critical factor in the network’s consensus and incentive mechanisms.

serving_rate_limit(netuid, block=None)[source]#

Retrieves the serving rate limit for a specific subnet within the Bittensor network. This rate limit determines how often you can change your node’s IP address on the blockchain. Expressed in number of blocks. Applies to both subnet validator and subnet miner nodes. Used when you move your node to a new machine.

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

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

Returns:

The serving rate limit of the subnet if it exists, None otherwise.

Return type:

Optional[int]

The serving rate limit is a crucial parameter for maintaining network efficiency and preventing overuse of resources by individual neurons. It helps ensure a balanced distribution of service requests across the network.

tx_rate_limit(block=None)[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], optional) – The blockchain block number at which to perform the query.

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.

subnet_exists(netuid, block=None)[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], optional) – The blockchain block number at which to check the subnet’s existence.

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.

get_all_subnet_netuids(block=None)[source]#

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

Parameters:

block (Optional[int], optional) – The blockchain block number at which to retrieve the subnet netuids.

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.

get_total_subnets(block=None)[source]#

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

Parameters:

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

Returns:

The total number of subnets in the network.

Return type:

int

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

get_subnet_modality(netuid, block=None)[source]#

Returns the NetworkModality hyperparameter for a specific subnetwork.

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

  • block (Optional[int], optional) – The block number to retrieve the parameter from. If None, the latest block is used. Default is None.

Returns:

The value of the NetworkModality hyperparameter, or None if the subnetwork does not exist or the parameter is not found.

Return type:

Optional[int]

get_subnet_connection_requirement(netuid_0, netuid_1, block=None)[source]#
Parameters:
  • netuid_0 (int)

  • netuid_1 (int)

  • block (Optional[int])

Return type:

Optional[int]

get_emission_value_by_subnet(netuid, block=None)[source]#

Retrieves the emission value of a specific subnet within the Bittensor network. The emission value represents the rate at which the subnet emits or distributes the network’s native token (Tao).

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

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

Returns:

The emission value of the subnet, None if not available.

Return type:

Optional[float]

The emission value is a critical economic parameter, influencing the incentive distribution and reward mechanisms within the subnet.

get_subnet_connection_requirements(netuid, block=None)[source]#

Retrieves the connection requirements for a specific subnet within the Bittensor network. This function provides details on the criteria that must be met for neurons to connect to the subnet.

Parameters:
  • netuid (int) – The network UID of the subnet to query.

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

Returns:

A dictionary detailing the connection requirements for the subnet.

Return type:

Dict[str, int]

Understanding these requirements is crucial for neurons looking to participate in or interact with specific subnets, ensuring compliance with their connection standards.

get_subnets(block=None)[source]#

Retrieves a list of all subnets currently active within the Bittensor network. This function provides an overview of the various subnets and their identifiers.

Parameters:

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

Returns:

A list of network UIDs representing each active subnet.

Return type:

List[int]

This function is valuable for understanding the network’s structure and the diversity of subnets available for neuron participation and collaboration.

get_all_subnets_info(block=None)[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], optional) – The blockchain block number for the query.

Returns:

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

Return type:

List[SubnetInfo]

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

get_subnet_info(netuid, block=None)[source]#

Retrieves detailed information about a specific subnet within the Bittensor network. This function provides key data on the subnet, including its operational parameters and network status.

Parameters:
  • netuid (int) – The network UID of the subnet to query.

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

Returns:

Detailed information about the subnet, or None if not found.

Return type:

Optional[SubnetInfo]

This function is essential for neurons and stakeholders interested in the specifics of a particular subnet, including its governance, performance, and role within the broader network.

get_subnet_hyperparameters(netuid, block=None)[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], optional) – The blockchain block number for the query.

Returns:

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

Return type:

Optional[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.

get_subnet_owner(netuid, block=None)[source]#

Retrieves the owner’s address of a specific subnet within the Bittensor network. The owner is typically the entity responsible for the creation and maintenance of the subnet.

Parameters:
  • netuid (int) – The network UID of the subnet to query.

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

Returns:

The SS58 address of the subnet’s owner, or None if not available.

Return type:

Optional[str]

Knowing the subnet owner provides insights into the governance and operational control of the subnet, which can be important for decision-making and collaboration within the network.

is_hotkey_delegate(hotkey_ss58, block=None)[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], optional) – The blockchain block number for the query.

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.

get_delegate_take(hotkey_ss58, block=None)[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], optional) – The blockchain block number for the query.

Returns:

The delegate take percentage, None if not available.

Return type:

Optional[float]

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

get_nominators_for_hotkey(hotkey_ss58, block=None)[source]#

Retrieves a list of nominators and their stakes for a neuron identified by its hotkey. Nominators are neurons that stake their tokens on a delegate to support its operations.

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

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

Returns:

A list of tuples containing each nominator’s address and staked amount or 0.

Return type:

Union[List[Tuple[str, Balance]], int]

This function provides insights into the neuron’s support network within the Bittensor ecosystem, indicating its trust and collaboration relationships.

get_delegate_by_hotkey(hotkey_ss58, block=None)[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], optional) – The blockchain block number for the query.

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.

get_delegates_lite(block=None)[source]#

Retrieves a lighter list of all delegate neurons within the Bittensor network. This function provides an overview of the neurons that are actively involved in the network’s delegation system.

Analyzing the delegate population offers insights into the network’s governance dynamics and the distribution of trust and responsibility among participating neurons.

This is a lighter version of get_delegates().

Parameters:

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

Returns:

A list of DelegateInfoLite objects detailing each delegate’s characteristics.

Return type:

List[DelegateInfoLite]

get_delegates(block=None)[source]#

Retrieves a list of all delegate neurons within the Bittensor network. This function provides an overview of the neurons that are actively involved in the network’s delegation system.

Analyzing the delegate population offers insights into the network’s governance dynamics and the distribution of trust and responsibility among participating neurons.

Parameters:

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

Returns:

A list of DelegateInfo objects detailing each delegate’s characteristics.

Return type:

List[DelegateInfo]

get_delegated(coldkey_ss58, block=None)[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], optional) – The blockchain block number for the query.

Returns:

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

amount.

Return type:

List[Tuple[DelegateInfo, Balance]]

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

get_childkey_take(hotkey, netuid, block=None)[source]#

Get the childkey take of a hotkey on a specific network. Args: - hotkey (str): The hotkey to search for. - netuid (int): The netuid to search for. - block (Optional[int]): Optional parameter specifying the block number. Defaults to None.

Returns: - Optional[int]: The value of the “ChildkeyTake” if found, or None if any error occurs.

Parameters:
  • hotkey (str)

  • netuid (int)

  • block (Optional[int])

Return type:

Optional[int]

get_children(hotkey, netuid)[source]#

Get the children of a hotkey on a specific network. :param hotkey: The hotkey to query. :type hotkey: str :param netuid: The network ID. :type netuid: int

Returns:

List of (proportion, child_address) tuples, or None if an error occurred.

Return type:

list or None

get_parents(child_hotkey, netuid)[source]#

Get the parents of a child hotkey on a specific network. :param child_hotkey: The child hotkey to query. :type child_hotkey: str :param netuid: The network ID. :type netuid: int

Returns:

List of (proportion, parent_address) tuples, or None if an error occurred.

Return type:

list or None

get_stake_info_for_coldkey(coldkey_ss58, block=None)[source]#

Retrieves stake information associated with a specific coldkey. This function provides details about the stakes held by an account, including the staked amounts and associated delegates.

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

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

Returns:

A list of StakeInfo objects detailing the stake allocations for the account.

Return type:

List[StakeInfo]

Stake information is vital for account holders to assess their investment and participation in the network’s delegation and consensus processes.

get_stake_info_for_coldkeys(coldkey_ss58_list, block=None)[source]#

Retrieves stake information for a list of coldkeys. This function aggregates stake data for multiple accounts, providing a collective view of their stakes and delegations.

Parameters:
  • coldkey_ss58_list (List[str]) – A list of SS58 addresses of the accounts’ coldkeys.

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

Returns:

A dictionary mapping each coldkey to a list of its StakeInfo objects.

Return type:

Dict[str, List[StakeInfo]]

This function is useful for analyzing the stake distribution and delegation patterns of multiple accounts simultaneously, offering a broader perspective on network participation and investment strategies.

get_minimum_required_stake()[source]#

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

This method retries the substrate call up to three times with exponential backoff in case of failures.

Returns:

The minimum required stake as a Balance object.

Return type:

Balance

Raises:

Exception – If the substrate call fails after the maximum number of retries.

is_hotkey_registered_any(hotkey_ss58, block=None)[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 at which to perform the check.

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.

is_hotkey_registered_on_subnet(hotkey_ss58, netuid, block=None)[source]#

Checks if a neuron’s hotkey is registered on a specific 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 at which to perform the check.

Returns:

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

Return type:

bool

This function helps in assessing the participation of a neuron in a particular subnet, indicating its specific area of operation or influence within the network.

is_hotkey_registered(hotkey_ss58, netuid=None, block=None)[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.

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.

get_uid_for_hotkey_on_subnet(hotkey_ss58, netuid, block=None)[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.

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.

get_all_uids_for_hotkey(hotkey_ss58, block=None)[source]#

Retrieves all unique identifiers (UIDs) associated with a given hotkey across different subnets within the Bittensor network. This function helps in identifying all the neuron instances that are linked to a specific hotkey.

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

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

Returns:

A list of UIDs associated with the given hotkey across various subnets.

Return type:

List[int]

This function is important for tracking a neuron’s presence and activities across different subnets within the Bittensor ecosystem.

get_netuids_for_hotkey(hotkey_ss58, block=None)[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 at which to perform the query.

Returns:

A list of netuids where the neuron is a member.

Return type:

List[int]

get_neuron_for_pubkey_and_subnet(hotkey_ss58, netuid, block=None)[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 at which to perform the query.

Returns:

Detailed information about the neuron if found, None otherwise.

Return type:

Optional[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.

get_all_neurons_for_pubkey(hotkey_ss58, block=None)[source]#

Retrieves information about all neuron instances associated with a given public key (hotkey SS58 address) across different subnets of the Bittensor network. This function aggregates neuron data from various subnets to provide a comprehensive view of a neuron’s presence and status within the network.

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

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

Returns:

A list of NeuronInfo objects detailing the neuron’s presence across various subnets.

Return type:

List[NeuronInfo]

This function is valuable for analyzing a neuron’s overall participation, influence, and contributions across the Bittensor network.

neuron_has_validator_permit(uid, netuid, block=None)[source]#

Checks if a neuron, identified by its unique identifier (UID), has a validator permit on a specific subnet within the Bittensor network. This function determines whether the neuron is authorized to participate in validation processes on the subnet.

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

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

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

Returns:

True if the neuron has a validator permit, False otherwise.

Return type:

Optional[bool]

This function is essential for understanding a neuron’s role and capabilities within a specific subnet, particularly regarding its involvement in network validation and governance.

neuron_for_wallet(wallet, netuid, block=None)[source]#

Retrieves information about a neuron associated with a given wallet on a specific subnet. This function provides detailed data about the neuron’s status, stake, and activities based on the wallet’s hotkey address.

Parameters:
  • wallet (bittensor.wallet) – The wallet associated with the neuron.

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

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

Returns:

Detailed information about the neuron if found, None otherwise.

Return type:

Optional[NeuronInfo]

This function is important for wallet owners to understand and manage their neuron’s presence and activities within a particular subnet of the Bittensor network.

neuron_for_uid(uid, netuid, block=None)[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 (int) – The unique identifier of the neuron.

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

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

Returns:

Detailed information about the neuron if found, None otherwise.

Return type:

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.

neurons(netuid, block=None)[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], optional) – The blockchain block number for the query.

Returns:

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

Return type:

List[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.

neuron_for_uid_lite(uid, netuid, block=None)[source]#

Retrieves a lightweight version of information about a neuron in a specific subnet, identified by its UID. The ‘lite’ version focuses on essential attributes such as stake and network activity.

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

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

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

Returns:

A simplified version of neuron information if found, None otherwise.

Return type:

Optional[NeuronInfoLite]

This function is useful for quick and efficient analyses of neuron status and activities within a subnet without the need for comprehensive data retrieval.

neurons_lite(netuid, block=None)[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], optional) – The blockchain block number for the query.

Returns:

A list of simplified neuron information for the subnet.

Return type:

List[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.

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, default=True) – If true, returns a metagraph using a lightweight sync (no weights, no bonds).

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

incentive(netuid, block=None)[source]#

Retrieves the list of incentives for neurons within a specific subnet of the Bittensor network. This function provides insights into the reward distribution mechanisms and the incentives allocated to each neuron based on their contributions and activities.

Parameters:
  • netuid (int) – The network UID of the subnet to query.

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

Returns:

The list of incentives for neurons within the subnet, indexed by UID.

Return type:

List[int]

Understanding the incentive structure is crucial for analyzing the network’s economic model and the motivational drivers for neuron participation and collaboration.

weights(netuid, block=None)[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]) – The blockchain block number for the query.

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.

bonds(netuid, block=None)[source]#

Retrieves the bond distribution set by neurons within a specific subnet of the Bittensor network. Bonds represent the investments or commitments made by neurons in one another, indicating a level of trust and perceived value. This bonding mechanism is integral to the network’s market-based approach to measuring and rewarding machine intelligence.

Parameters:
  • netuid (int) – The network UID of the subnet to query.

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

Returns:

A list of tuples mapping each neuron’s UID to its bonds with other

neurons.

Return type:

List[Tuple[int, List[Tuple[int, int]]]]

Understanding bond distributions is crucial for analyzing the trust dynamics and market behavior within the subnet. It reflects how neurons recognize and invest in each other’s intelligence and contributions, supporting diverse and niche systems within the Bittensor ecosystem.

get_subnet_burn_cost(block=None)[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 subnet.

Parameters:

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

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.

_do_delegation(wallet, delegate_ss58, amount, wait_for_inclusion=True, wait_for_finalization=False)[source]#

Delegates a specified amount of stake to a delegate’s hotkey.

This method sends a transaction to add stake to a delegate’s hotkey and retries the call up to three times with exponential backoff in case of failures.

Parameters:
  • wallet (bittensor.wallet) – The wallet from which the stake will be delegated.

  • delegate_ss58 (str) – The SS58 address of the delegate’s hotkey.

  • amount (Balance) – The amount of stake to be delegated.

  • wait_for_inclusion (bool, optional) – Whether to wait for the transaction to be included in a block. Default is True.

  • wait_for_finalization (bool, optional) – Whether to wait for the transaction to be finalized. Default is False.

Returns:

True if the delegation is successful, False otherwise.

Return type:

bool

_do_undelegation(wallet, delegate_ss58, amount, wait_for_inclusion=True, wait_for_finalization=False)[source]#

Removes a specified amount of stake from a delegate’s hotkey.

This method sends a transaction to remove stake from a delegate’s hotkey and retries the call up to three times with exponential backoff in case of failures.

Parameters:
  • wallet (bittensor.wallet) – The wallet from which the stake will be removed.

  • delegate_ss58 (str) – The SS58 address of the delegate’s hotkey.

  • amount (Balance) – The amount of stake to be removed.

  • wait_for_inclusion (bool, optional) – Whether to wait for the transaction to be included in a block. Default is True.

  • wait_for_finalization (bool, optional) – Whether to wait for the transaction to be finalized. Default is False.

Returns:

True if the undelegation is successful, False otherwise.

Return type:

bool

_do_nominate(wallet, wait_for_inclusion=True, wait_for_finalization=False)[source]#

Nominates the wallet’s hotkey to become a delegate.

This method sends a transaction to nominate the wallet’s hotkey to become a delegate and retries the call up to three times with exponential backoff in case of failures.

Parameters:
  • wallet (bittensor.wallet) – The wallet whose hotkey will be nominated.

  • wait_for_inclusion (bool, optional) – Whether to wait for the transaction to be included in a block. Default is True.

  • wait_for_finalization (bool, optional) – Whether to wait for the transaction to be finalized. Default is False.

Returns:

True if the nomination is successful, False otherwise.

Return type:

bool

_do_increase_take(wallet, hotkey_ss58, take, wait_for_inclusion=True, wait_for_finalization=False)[source]#

Increases the take rate for a delegate’s hotkey.

This method sends a transaction to increase the take rate for a delegate’s hotkey and retries the call up to three times with exponential backoff in case of failures.

Parameters:
  • wallet (bittensor.wallet) – The wallet from which the transaction will be signed.

  • hotkey_ss58 (str) – The SS58 address of the delegate’s hotkey.

  • take (int) – The new take rate to be set.

  • wait_for_inclusion (bool, optional) – Whether to wait for the transaction to be included in a block. Default is True.

  • wait_for_finalization (bool, optional) – Whether to wait for the transaction to be finalized. Default is False.

Returns:

True if the take rate increase is successful, False otherwise.

Return type:

bool

_do_decrease_take(wallet, hotkey_ss58, take, wait_for_inclusion=True, wait_for_finalization=False)[source]#

Decreases the take rate for a delegate’s hotkey.

This method sends a transaction to decrease the take rate for a delegate’s hotkey and retries the call up to three times with exponential backoff in case of failures.

Parameters:
  • wallet (bittensor.wallet) – The wallet from which the transaction will be signed.

  • hotkey_ss58 (str) – The SS58 address of the delegate’s hotkey.

  • take (int) – The new take rate to be set.

  • wait_for_inclusion (bool, optional) – Whether to wait for the transaction to be included in a block. Default is True.

  • wait_for_finalization (bool, optional) – Whether to wait for the transaction to be finalized. Default is False.

Returns:

True if the take rate decrease is successful, False otherwise.

Return type:

bool

get_balance(address, block=None)[source]#

Retrieves the token balance of a specific address within the Bittensor network. This function queries the blockchain to determine the amount of Tao held by a given account.

Parameters:
  • address (str) – The Substrate address in ss58 format.

  • block (int, optional) – The blockchain block number at which to perform the query.

Returns:

The account balance at the specified block, represented as a Balance object.

Return type:

Balance

This function is important for monitoring account holdings and managing financial transactions within the Bittensor ecosystem. It helps in assessing the economic status and capacity of network participants.

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.

Returns:

The current chain block number.

Return type:

int

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.

get_balances(block=None)[source]#

Retrieves the token balances of all accounts within the Bittensor network as of a specific blockchain block. This function provides a comprehensive view of the token distribution among different accounts.

Parameters:

block (int, optional) – The blockchain block number at which to perform the query.

Returns:

A dictionary mapping each account’s ss58 address to its balance.

Return type:

Dict[str, Balance]

This function is valuable for analyzing the overall economic landscape of the Bittensor network, including the distribution of financial resources and the financial status of network participants.

static _null_neuron()[source]#
Return type:

bittensor.chain_data.NeuronInfo

get_block_hash(block_id)[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.

Parameters:

block_id (int) – The block number for which the hash is to be retrieved.

Returns:

The cryptographic hash of the specified block.

Return type:

str

The block hash is a fundamental aspect of blockchain technology, providing a secure reference to each block’s data. It is crucial for verifying transactions, ensuring data consistency, and maintaining the trustworthiness of the blockchain.

get_error_info_by_index(error_index)[source]#

Returns the error name and description from the Subtensor error list.

Parameters:

error_index (int) – The index of the error to retrieve.

Returns:

A tuple containing the error name and description from substrate metadata. If the error index is not found, returns (“Unknown Error”, “”) and logs a warning.

Return type:

Tuple[str, str]

class bittensor.subtensor(network=None, config=None, _mock=False, log_verbose=True, connection_timeout=600)#

The Subtensor class in Bittensor serves as a crucial interface for interacting with the Bittensor blockchain, facilitating a range of operations essential for the decentralized machine learning network.

This class enables neurons (network participants) to engage in activities such as registering on the network, managing staked weights, setting inter-neuronal weights, and participating in consensus mechanisms.

The Bittensor network operates on a digital ledger where each neuron holds stakes (S) and learns a set of inter-peer weights (W). These weights, set by the neurons themselves, play a critical role in determining the ranking and incentive mechanisms within the network. Higher-ranked neurons, as determined by their contributions and trust within the network, receive more incentives.

The Subtensor class connects to various Bittensor networks like the main finney network or local test networks, providing a gateway to the blockchain layer of Bittensor. It leverages a staked weighted trust system and consensus to ensure fair and distributed incentive mechanisms, where incentives (I) are primarily allocated to neurons that are trusted by the majority of the network.

Additionally, Bittensor introduces a speculation-based reward mechanism in the form of bonds (B), allowing neurons to accumulate bonds in other neurons, speculating on their future value. This mechanism aligns with market-based speculation, incentivizing neurons to make judicious decisions in their inter-neuronal investments.

Example Usage:

# Connect to the main Bittensor network (Finney).
finney_subtensor = subtensor(network='finney')

# Close websocket connection with the Bittensor network.
finney_subtensor.close()

# (Re)creates the websocket connection with the Bittensor network.
finney_subtensor.connect_websocket()

# Register a new neuron on the network.
wallet = bittensor.wallet(...)  # Assuming a wallet instance is created.
success = finney_subtensor.register(wallet=wallet, netuid=netuid)

# Set inter-neuronal weights for collaborative learning.
success = finney_subtensor.set_weights(wallet=wallet, netuid=netuid, uids=[...], weights=[...])

# Speculate by accumulating bonds in other promising neurons.
success = finney_subtensor.delegate(wallet=wallet, delegate_ss58=other_neuron_ss58, amount=bond_amount)

# Get the metagraph for a specific subnet using given subtensor connection
metagraph = subtensor.metagraph(netuid=netuid)

By facilitating these operations, the Subtensor class is instrumental in maintaining the decentralized intelligence and dynamic learning environment of the Bittensor network, as envisioned in its foundational principles and mechanisms described in the NeurIPS paper. paper.

Initializes a Subtensor interface for interacting with the Bittensor blockchain.

Note

Currently subtensor defaults to the finney network. This will change in a future release.

We strongly encourage users to run their own local subtensor node whenever possible. This increases decentralization and resilience of the network. In a future release, local subtensor will become the default and the fallback to finney removed. Please plan ahead for this change. We will provide detailed instructions on how to run a local subtensor node in the documentation in a subsequent release.

Parameters:
  • network (str, optional) – The network name to connect to (e.g., finney, local). This can also be the chain endpoint (e.g., wss://entrypoint-finney.opentensor.ai:443) and will be correctly parsed into the network and chain endpoint. If not specified, defaults to the main Bittensor network.

  • config (bittensor.config, optional) – Configuration object for the subtensor. If not provided, a default configuration is used.

  • _mock (bool, optional) – If set to True, uses a mocked connection for testing purposes.

  • log_verbose (bool)

  • connection_timeout (int)

This initialization sets up the connection to the specified Bittensor network, allowing for various blockchain operations such as neuron registration, stake management, and setting weights.

config#
log_verbose#
_connection_timeout#
_subtensor_errors: Dict[str, Dict[str, str]]#
__str__()#
Return type:

str

__repr__()#
Return type:

str

_get_substrate()#

Establishes a connection to the Substrate node using configured parameters.

classmethod help()#

Print help to stdout.

classmethod add_args(parser, prefix=None)#

Adds command-line arguments to the provided ArgumentParser for configuring the Subtensor settings.

Parameters:
  • parser (argparse.ArgumentParser) – The ArgumentParser object to which the Subtensor arguments will be added.

  • prefix (Optional[str]) – An optional prefix for the argument names. If provided, the prefix is prepended to each argument name.

Arguments added:
–subtensor.network: The Subtensor network flag. Possible values are ‘finney’, ‘test’, ‘archive’, and

‘local’. Overrides the chain endpoint if set.

–subtensor.chain_endpoint: The Subtensor chain endpoint flag. If set, it overrides the network flag. –subtensor._mock: If true, uses a mocked connection to the chain.

Example

parser = argparse.ArgumentParser() Subtensor.add_args(parser)

static determine_chain_endpoint_and_network(network)#

Determines the chain endpoint and network from the passed network or chain_endpoint.

Parameters:

network (str) – The network flag. The choices are: -- finney (main network), -- archive (archive network +300 blocks), -- local (local running network), -- test (test network).

Returns:

The network flag. chain_endpoint (str): The chain endpoint flag. If set, overrides the network argument.

Return type:

network (str)

static setup_config(network, config)#

Sets up and returns the configuration for the Subtensor network and endpoint.

This method determines the appropriate network and chain endpoint based on the provided network string or configuration object. It evaluates the network and endpoint in the following order of precedence: 1. Provided network string. 2. Configured chain endpoint in the config object. 3. Configured network in the config object. 4. Default chain endpoint. 5. Default network.

Parameters:
  • network (str) – The name of the Subtensor network. If None, the network and endpoint will be determined from the config object.

  • config (bittensor.config) – The configuration object containing the network and chain endpoint settings.

Returns:

A tuple containing the formatted WebSocket endpoint URL and the evaluated network name.

Return type:

tuple

close()#

Cleans up resources for this subtensor instance like active websocket connection and active extensions.

nominate(wallet, wait_for_finalization=False, wait_for_inclusion=True)#

Becomes a delegate for the hotkey associated with the given wallet. This method is used to nominate a neuron (identified by the hotkey in the wallet) as a delegate on the Bittensor network, allowing it to participate in consensus and validation processes.

Parameters:
  • wallet (bittensor.wallet) – The wallet containing the hotkey to be nominated.

  • wait_for_finalization (bool, optional) – If True, waits until the transaction is finalized on the blockchain.

  • wait_for_inclusion (bool, optional) – If True, waits until the transaction is included in a block.

Returns:

True if the nomination process is successful, False otherwise.

Return type:

bool

This function is a key part of the decentralized governance mechanism of Bittensor, allowing for the dynamic selection and participation of validators in the network’s consensus process.

delegate(wallet, delegate_ss58=None, amount=None, wait_for_inclusion=True, wait_for_finalization=False, prompt=False)#

Becomes a delegate for the hotkey associated with the given wallet. This method is used to nominate a neuron (identified by the hotkey in the wallet) as a delegate on the Bittensor network, allowing it to participate in consensus and validation processes.

Parameters:
  • wallet (bittensor.wallet) – The wallet containing the hotkey to be nominated.

  • delegate_ss58 (Optional[str]) – The SS58 address of the delegate neuron.

  • amount (Union[Balance, float]) – The amount of TAO to undelegate.

  • wait_for_finalization (bool, optional) – If True, waits until the transaction is finalized on the blockchain.

  • wait_for_inclusion (bool, optional) – If True, waits until the transaction is included in a block.

  • prompt (bool, optional) – If True, prompts for user confirmation before proceeding.

Returns:

True if the nomination process is successful, False otherwise.

Return type:

bool

This function is a key part of the decentralized governance mechanism of Bittensor, allowing for the dynamic selection and participation of validators in the network’s consensus process.

undelegate(wallet, delegate_ss58=None, amount=None, wait_for_inclusion=True, wait_for_finalization=False, prompt=False)#

Removes a specified amount of stake from a delegate neuron using the provided wallet. This action reduces the staked amount on another neuron, effectively withdrawing support or speculation.

Parameters:
  • wallet (bittensor.wallet) – The wallet used for the undelegation process.

  • delegate_ss58 (Optional[str]) – The SS58 address of the delegate neuron.

  • amount (Union[Balance, float]) – The amount of TAO to undelegate.

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

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

  • prompt (bool, optional) – If True, prompts for user confirmation before proceeding.

Returns:

True if the undelegation is successful, False otherwise.

Return type:

bool

This function reflects the dynamic and speculative nature of the Bittensor network, allowing neurons to adjust their stakes and investments based on changing perceptions and performances within the network.

set_take(wallet, delegate_ss58=None, take=0.0, wait_for_inclusion=True, wait_for_finalization=False)#

Set delegate hotkey take :param wallet: The wallet containing the hotkey to be nominated. :type wallet: bittensor.wallet :param delegate_ss58: Hotkey :type delegate_ss58: str, optional :param take: Delegate take on subnet ID :type take: float :param wait_for_finalization: If True, waits until the transaction is finalized on the

blockchain.

Parameters:
  • wait_for_inclusion (bool, optional) – If True, waits until the transaction is included in a block.

  • wallet (bittensor.wallet)

  • delegate_ss58 (Optional[str])

  • take (float)

  • wait_for_finalization (bool, optional)

Returns:

True if the process is successful, False otherwise.

Return type:

bool

This function is a key part of the decentralized governance mechanism of Bittensor, allowing for the dynamic selection and participation of validators in the network’s consensus process.

send_extrinsic(wallet, module, function, params, period=5, wait_for_inclusion=False, wait_for_finalization=False, max_retries=3, wait_time=3, max_wait=20)#

Sends an extrinsic to the Bittensor blockchain using the provided wallet and parameters. This method constructs and submits the extrinsic, handling retries and blockchain communication.

Parameters:
  • wallet (bittensor.wallet) – The wallet associated with the extrinsic.

  • module (str) – The module name for the extrinsic.

  • function (str) – The function name for the extrinsic.

  • params (dict) – The parameters for the extrinsic.

  • period (int, optional) – The number of blocks for the extrinsic to live in the mempool. Defaults to 5.

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

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

  • max_retries (int, optional) – The maximum number of retries for the extrinsic. Defaults to 3.

  • wait_time (int, optional) – The wait time between retries. Defaults to 3.

  • max_wait (int, optional) – The maximum wait time for the extrinsic. Defaults to 20.

Returns:

The receipt of the extrinsic if successful, None otherwise.

Return type:

Optional[ExtrinsicReceipt]

set_weights(wallet, netuid, uids, weights, version_key=bittensor.__version_as_int__, wait_for_inclusion=False, wait_for_finalization=False, prompt=False, max_retries=5)#

Sets the inter-neuronal weights for the specified neuron. This process involves specifying the influence or trust a neuron places on other neurons in the network, which is a fundamental aspect of Bittensor’s decentralized learning architecture.

Parameters:
  • wallet (bittensor.wallet) – The wallet associated with the neuron setting the weights.

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

  • uids (Union[NDArray[np.int64], torch.LongTensor, list]) – The list of neuron UIDs that the weights are being set for.

  • weights (Union[NDArray[np.float32], torch.FloatTensor, list]) – The corresponding weights to be set for each UID.

  • version_key (int, optional) – Version key for compatibility with the network.

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

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

  • prompt (bool, optional) – If True, prompts for user confirmation before proceeding.

  • max_retries (int, optional) – The number of maximum attempts to set weights. (Default: 5)

Returns:

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 shaping the network’s collective intelligence, where each neuron’s learning and contribution are influenced by the weights it sets towards others【81†source】.

_do_set_weights(wallet, uids, vals, netuid, version_key=bittensor.__version_as_int__, wait_for_inclusion=False, wait_for_finalization=False)#

Internal method to send a transaction to the Bittensor blockchain, setting weights for specified neurons. This method constructs and submits the transaction, handling retries and blockchain communication.

Parameters:
  • wallet (bittensor.wallet) – The wallet associated with the neuron setting the weights.

  • uids (List[int]) – List of neuron UIDs for which weights are being set.

  • vals (List[int]) – List of weight values corresponding to each UID.

  • netuid (int) – Unique identifier for the network.

  • version_key (int, optional) – Version key for compatibility with the network.

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

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

Returns:

A tuple containing a success flag and an optional error message.

Return type:

Tuple[bool, Optional[str]]

This method is vital for the dynamic weighting mechanism in Bittensor, where neurons adjust their trust in other neurons based on observed performance and contributions.

commit_weights(wallet, netuid, salt, uids, weights, version_key=bittensor.__version_as_int__, wait_for_inclusion=False, wait_for_finalization=False, prompt=False, max_retries=5)#

Commits a hash of the neuron’s weights to the Bittensor blockchain using the provided wallet. This action serves as a commitment or snapshot of the neuron’s current weight distribution.

Parameters:
  • wallet (bittensor.wallet) – The wallet associated with the neuron committing the weights.

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

  • salt (List[int]) – list of randomly generated integers as salt to generated weighted hash.

  • uids (np.ndarray) – NumPy array of neuron UIDs for which weights are being committed.

  • weights (np.ndarray) – NumPy array of weight values corresponding to each UID.

  • version_key (int, optional) – Version key for compatibility with the network.

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

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

  • prompt (bool, optional) – If True, prompts for user confirmation before proceeding.

  • max_retries (int, optional) – The number of maximum attempts to commit weights. (Default: 5)

Returns:

True if the weight commitment is successful, False otherwise. And msg, a string value describing the success or potential error.

Return type:

Tuple[bool, str]

This function allows neurons to create a tamper-proof record of their weight distribution at a specific point in time, enhancing transparency and accountability within the Bittensor network.

_do_commit_weights(wallet, netuid, commit_hash, wait_for_inclusion=False, wait_for_finalization=False)#

Internal method to send a transaction to the Bittensor blockchain, committing the hash of a neuron’s weights. This method constructs and submits the transaction, handling retries and blockchain communication.

Parameters:
  • wallet (bittensor.wallet) – The wallet associated with the neuron committing the weights.

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

  • commit_hash (str) – The hash of the neuron’s weights to be committed.

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

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

Returns:

A tuple containing a success flag and an optional error message.

Return type:

Tuple[bool, Optional[str]]

This method ensures that the weight commitment is securely recorded on the Bittensor blockchain, providing a verifiable record of the neuron’s weight distribution at a specific point in time.

reveal_weights(wallet, netuid, uids, weights, salt, version_key=bittensor.__version_as_int__, wait_for_inclusion=False, wait_for_finalization=False, prompt=False, max_retries=5)#

Reveals the weights for a specific subnet on the Bittensor blockchain using the provided wallet. This action serves as a revelation of the neuron’s previously committed weight distribution.

Parameters:
  • wallet (bittensor.wallet) – The wallet associated with the neuron revealing the weights.

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

  • uids (np.ndarray) – NumPy array of neuron UIDs for which weights are being revealed.

  • weights (np.ndarray) – NumPy array of weight values corresponding to each UID.

  • salt (np.ndarray) – NumPy array of salt values corresponding to the hash function.

  • version_key (int, optional) – Version key for compatibility with the network.

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

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

  • prompt (bool, optional) – If True, prompts for user confirmation before proceeding.

  • max_retries (int, optional) – The number of maximum attempts to reveal weights. (Default: 5)

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 neurons to reveal their previously committed weight distribution, ensuring transparency and accountability within the Bittensor network.

_do_reveal_weights(wallet, netuid, uids, values, salt, version_key, wait_for_inclusion=False, wait_for_finalization=False)#

Internal method to send a transaction to the Bittensor blockchain, revealing the weights for a specific subnet. This method constructs and submits the transaction, handling retries and blockchain communication.

Parameters:
  • wallet (bittensor.wallet) – The wallet associated with the neuron revealing the weights.

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

  • uids (List[int]) – List of neuron UIDs for which weights are being revealed.

  • values (List[int]) – List of weight values corresponding to each UID.

  • salt (List[int]) – List of salt values corresponding to the hash function.

  • version_key (int) – Version key for compatibility with the network.

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

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

Returns:

A tuple containing a success flag and an optional error message.

Return type:

Tuple[bool, Optional[str]]

This method ensures that the weight revelation is securely recorded on the Bittensor blockchain, providing transparency and accountability for the neuron’s weight distribution.

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

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) – The wallet associated with the neuron to be registered.

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

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

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

  • prompt (bool, optional) – If True, prompts for user confirmation before proceeding.

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

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.

swap_hotkey(wallet, new_wallet, wait_for_inclusion=False, wait_for_finalization=True, prompt=False)#

Swaps an old hotkey with a new hotkey for the specified wallet.

This method initiates an extrinsic to change the hotkey associated with a wallet to a new hotkey. It provides options to wait for inclusion and finalization of the transaction, and to prompt the user for confirmation.

Parameters:
  • wallet (bittensor.wallet) – The wallet whose hotkey is to be swapped.

  • new_wallet (bittensor.wallet) – The new wallet with the hotkey to be set.

  • wait_for_inclusion (bool) – Whether to wait for the transaction to be included in a block. Default is False.

  • wait_for_finalization (bool) – Whether to wait for the transaction to be finalized. Default is True.

  • prompt (bool) – Whether to prompt the user for confirmation before proceeding. Default is False.

Returns:

True if the hotkey swap was successful, False otherwise.

Return type:

bool

run_faucet(wallet, wait_for_inclusion=False, wait_for_finalization=True, prompt=False, max_allowed_attempts=3, output_in_place=True, cuda=False, dev_id=0, tpb=256, num_processes=None, update_interval=None, log_verbose=False)#

Facilitates a faucet transaction, allowing new neurons to receive an initial amount of TAO for participating in the network. This function is particularly useful for newcomers to the Bittensor network, enabling them to start with a small stake on testnet only.

Parameters:
  • wallet (bittensor.wallet) – The wallet for which the faucet transaction is to be run.

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

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

  • prompt (bool, optional) – If True, prompts for user confirmation before proceeding.

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

Returns:

True if the faucet transaction is successful, False otherwise.

Return type:

bool

This function is part of Bittensor’s onboarding process, ensuring that new neurons have the necessary resources to begin their journey in the decentralized AI network.

Note

This is for testnet ONLY and is disabled currently. You must build your own staging subtensor chain with the --features pow-faucet argument to enable this.

burned_register(wallet, netuid, wait_for_inclusion=False, wait_for_finalization=True, prompt=False)#

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) – The wallet associated with the neuron to be registered.

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

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

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

  • prompt (bool, optional) – If True, prompts for user confirmation before proceeding. Defaults to False.

Returns:

True if the registration is successful, False otherwise.

Return type:

bool

_do_pow_register(netuid, wallet, pow_result, wait_for_inclusion=False, wait_for_finalization=True)#

Sends a (POW) register extrinsic to the chain.

Parameters:
  • netuid (int) – The subnet to register on.

  • wallet (bittensor.wallet) – The wallet to register.

  • pow_result (POWSolution) – The PoW result to register.

  • wait_for_inclusion (bool) – If True, waits for the extrinsic to be included in a block. Default to False.

  • wait_for_finalization (bool) – If True, waits for the extrinsic to be finalized. Default to True.

Returns:

True if the extrinsic was included in a block. error (Optional[str]): None on success or not waiting for inclusion/finalization, otherwise the error

message.

Return type:

success (bool)

_do_burned_register(netuid, wallet, wait_for_inclusion=False, wait_for_finalization=True)#

Performs a burned register extrinsic call to the Subtensor chain.

This method sends a registration transaction to the Subtensor blockchain using the burned register mechanism. It retries the call up to three times with exponential backoff in case of failures.

Parameters:
  • netuid (int) – The network unique identifier to register on.

  • wallet (bittensor.wallet) – The wallet to be registered.

  • wait_for_inclusion (bool) – Whether to wait for the transaction to be included in a block. Default is False.

  • wait_for_finalization (bool) – Whether to wait for the transaction to be finalized. Default is True.

Returns:

A tuple containing a boolean indicating success or failure, and an optional error message.

Return type:

Tuple[bool, Optional[str]]

_do_swap_hotkey(wallet, new_wallet, wait_for_inclusion=False, wait_for_finalization=True)#

Performs a hotkey swap extrinsic call to the Subtensor chain.

Parameters:
  • wallet (bittensor.wallet) – The wallet whose hotkey is to be swapped.

  • new_wallet (bittensor.wallet) – The wallet with the new hotkey to be set.

  • wait_for_inclusion (bool) – Whether to wait for the transaction to be included in a block. Default is

  • False.

  • wait_for_finalization (bool) – Whether to wait for the transaction to be finalized. Default is True.

Returns:

A tuple containing a boolean indicating success or failure, and an optional

error message.

Return type:

Tuple[bool, Optional[str]]

transfer(wallet, dest, amount, wait_for_inclusion=True, wait_for_finalization=False, prompt=False)#

Executes a transfer of funds from the provided wallet to the specified destination address. This function is used to move TAO tokens within the Bittensor network, facilitating transactions between neurons.

Parameters:
  • wallet (bittensor.wallet) – The wallet from which funds are being transferred.

  • dest (str) – The destination public key address.

  • amount (Union[Balance, float]) – The amount of TAO to be transferred.

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

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

  • prompt (bool, optional) – If True, prompts for user confirmation before proceeding.

Returns:

True if the transfer is successful, False otherwise.

Return type:

transfer_extrinsic (bool)

This function is essential for the fluid movement of tokens in the network, supporting various economic activities such as staking, delegation, and reward distribution.

get_transfer_fee(wallet, dest, value)#

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) – The wallet from which the transfer is initiated.

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

  • value (Union[Balance, float, int]) – 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:

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.

_do_transfer(wallet, dest, transfer_balance, wait_for_inclusion=True, wait_for_finalization=False)#

Sends a transfer extrinsic to the chain.

Parameters:
  • wallet (bittensor.wallet()) – Wallet object.

  • dest (str) – Destination public key address.

  • transfer_balance (Balance()) – Amount to transfer.

  • wait_for_inclusion (bool) – If true, waits for inclusion.

  • wait_for_finalization (bool) – If true, waits for finalization.

Returns:

True if transfer was successful. block_hash (str): Block hash of the transfer. On success and if wait_for_ finalization/inclusion is

True.

error (str): Error message if transfer failed.

Return type:

success (bool)

get_existential_deposit(block=None)#

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]) – Block number at which to query the deposit amount. If None, the current block is used.

Returns:

The existential deposit amount, or None if the query fails.

Return type:

Optional[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.

register_subnetwork(wallet, wait_for_inclusion=False, wait_for_finalization=True, prompt=False)#

Registers a new subnetwork on the Bittensor network using the provided wallet. This function is used for the creation and registration of subnetworks, which are specialized segments of the overall Bittensor network.

Parameters:
  • wallet (bittensor.wallet) – The wallet to be used for registration.

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

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

  • prompt (bool, optional) – If True, prompts for user confirmation before proceeding.

Returns:

True if the subnetwork registration is successful, False otherwise.

Return type:

bool

This function allows for the expansion and diversification of the Bittensor network, supporting its decentralized and adaptable architecture.

set_hyperparameter(wallet, netuid, parameter, value, wait_for_inclusion=False, wait_for_finalization=True, prompt=False)#

Sets a specific hyperparameter for a given subnetwork on the Bittensor blockchain. This action involves adjusting network-level parameters, influencing the behavior and characteristics of the subnetwork.

Parameters:
  • wallet (bittensor.wallet) – The wallet used for setting the hyperparameter.

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

  • parameter (str) – The name of the hyperparameter to be set.

  • value – The new value for the hyperparameter.

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

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

  • prompt (bool, optional) – If True, prompts for user confirmation before proceeding.

Returns:

True if the hyperparameter setting is successful, False otherwise.

Return type:

bool

This function plays a critical role in the dynamic governance and adaptability of the Bittensor network, allowing for fine-tuning of network operations and characteristics.

serve(wallet, ip, port, protocol, netuid, placeholder1=0, placeholder2=0, wait_for_inclusion=False, wait_for_finalization=True)#

Registers a neuron’s serving endpoint on the Bittensor network. This function announces the IP address and port where the neuron is available to serve requests, facilitating peer-to-peer communication within the network.

Parameters:
  • wallet (bittensor.wallet) – The wallet associated with the neuron being served.

  • ip (str) – The IP address of the serving neuron.

  • port (int) – The port number on which the neuron is serving.

  • protocol (int) – The protocol type used by the neuron (e.g., GRPC, HTTP).

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

  • placeholder1 (int, optional) – Placeholder parameter for future extensions. Default is 0.

  • placeholder2 (int, optional) – Placeholder parameter for future extensions. Default is 0.

  • wait_for_inclusion (bool, optional) – Waits for the transaction to be included in a block. Default is False.

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

Returns:

True if the serve registration is successful, False otherwise.

Return type:

bool

This function is essential for establishing the neuron’s presence in the network, enabling it to participate in the decentralized machine learning processes of Bittensor.

serve_axon(netuid, axon, wait_for_inclusion=False, wait_for_finalization=True)#

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.Axon) – The Axon instance to be registered for serving.

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

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

Returns:

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.

_do_serve_axon(wallet, call_params, wait_for_inclusion=False, wait_for_finalization=True)#

Internal method to submit a serve axon transaction to the Bittensor blockchain. This method creates and submits a transaction, enabling a neuron’s Axon to serve requests on the network.

Parameters:
  • wallet (bittensor.wallet) – The wallet associated with the neuron.

  • call_params (AxonServeCallParams) – Parameters required for the serve axon call.

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

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

Returns:

A tuple containing a success flag and an optional error message.

Return type:

Tuple[bool, Optional[str]]

This function is crucial for initializing and announcing a neuron’s Axon service on the network, enhancing the decentralized computation capabilities of Bittensor.

serve_prometheus(wallet, port, netuid, wait_for_inclusion=False, wait_for_finalization=True)#
Parameters:
  • wallet (bittensor.wallet)

  • port (int)

  • netuid (int)

  • wait_for_inclusion (bool)

  • wait_for_finalization (bool)

Return type:

bool

_do_serve_prometheus(wallet, call_params, wait_for_inclusion=False, wait_for_finalization=True)#

Sends a serve prometheus extrinsic to the chain. :param wallet: Wallet object. :type wallet: bittensor.wallet() :param call_params: Prometheus serve call parameters. :type call_params: PrometheusServeCallParams() :param wait_for_inclusion: If true, waits for inclusion. :type wait_for_inclusion: bool :param wait_for_finalization: If true, waits for finalization. :type wait_for_finalization: bool

Returns:

True if serve prometheus was successful. error (Optional[str]()): Error message if serve prometheus failed, None otherwise.

Return type:

success (bool)

Parameters:
_do_associate_ips(wallet, ip_info_list, netuid, wait_for_inclusion=False, wait_for_finalization=True)#

Sends an associate IPs extrinsic to the chain.

Parameters:
  • wallet (bittensor.wallet()) – Wallet object.

  • ip_info_list (List[IPInfo]()) – List of IPInfo objects.

  • netuid (int) – Netuid to associate IPs to.

  • wait_for_inclusion (bool) – If true, waits for inclusion.

  • wait_for_finalization (bool) – If true, waits for finalization.

Returns:

True if associate IPs was successful. error (Optional[str]()): Error message if associate IPs failed, None otherwise.

Return type:

success (bool)

add_stake(wallet, hotkey_ss58=None, amount=None, wait_for_inclusion=True, wait_for_finalization=False, prompt=False)#

Adds the specified amount of stake to a neuron identified by the hotkey SS58 address. Staking is a fundamental process in the Bittensor network that enables neurons to participate actively and earn incentives.

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

  • hotkey_ss58 (Optional[str]) – The SS58 address of the hotkey associated with the neuron.

  • amount (Union[Balance, float]) – The amount of TAO to stake.

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

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

  • prompt (bool, optional) – If True, prompts for user confirmation before proceeding.

Returns:

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 rewards in line with Bittensor’s consensus and reward mechanisms.

add_stake_multiple(wallet, hotkey_ss58s, amounts=None, wait_for_inclusion=True, wait_for_finalization=False, prompt=False)#

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) – The wallet used for staking.

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

  • amounts (List[Union[Balance, float]], optional) – Corresponding amounts of TAO to stake for each hotkey.

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

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

  • prompt (bool, optional) – If True, prompts for user confirmation before proceeding.

Returns:

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.

_do_stake(wallet, hotkey_ss58, amount, wait_for_inclusion=True, wait_for_finalization=False)#

Sends a stake extrinsic to the chain.

Parameters:
  • wallet (bittensor.wallet()) – Wallet object that can sign the extrinsic.

  • hotkey_ss58 (str) – Hotkey ss58 address to stake to.

  • amount (Balance()) – Amount to stake.

  • wait_for_inclusion (bool) – If true, waits for inclusion before returning.

  • wait_for_finalization (bool) – If true, waits for finalization before returning.

Returns:

True if the extrinsic was successful.

Return type:

success (bool)

Raises:

StakeError – If the extrinsic failed.

unstake_multiple(wallet, hotkey_ss58s, amounts=None, wait_for_inclusion=True, wait_for_finalization=False, prompt=False)#

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

  • amounts (List[Union[Balance, float]], optional) – The amounts of TAO to unstake from each hotkey. If not provided, unstakes all available stakes.

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

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

  • prompt (bool, optional) – If True, prompts for user confirmation before proceeding.

Returns:

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.

unstake(wallet, hotkey_ss58=None, amount=None, wait_for_inclusion=True, wait_for_finalization=False, prompt=False)#

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

  • amount (Union[Balance, float], optional) – The amount of TAO to unstake. If not specified, unstakes all.

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

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

  • prompt (bool, optional) – If True, prompts for user confirmation before proceeding.

Returns:

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.

_do_unstake(wallet, hotkey_ss58, amount, wait_for_inclusion=True, wait_for_finalization=False)#

Sends an unstake extrinsic to the chain.

Parameters:
  • wallet (bittensor.wallet()) – Wallet object that can sign the extrinsic.

  • hotkey_ss58 (str) – Hotkey ss58 address to unstake from.

  • amount (Balance()) – Amount to unstake.

  • wait_for_inclusion (bool) – If true, waits for inclusion before returning.

  • wait_for_finalization (bool) – If true, waits for finalization before returning.

Returns:

True if the extrinsic was successful.

Return type:

success (bool)

Raises:

StakeError – If the extrinsic failed.

set_childkey_take(wallet, hotkey, take, netuid, wait_for_inclusion=True, wait_for_finalization=False, prompt=False)#

Sets a childkey take extrinsic on the subnet.

Parameters:
  • wallet (bittensor.wallet()) – Wallet object that can sign the extrinsic.

  • hotkey (str) – (str): Hotkey ss58 address of the child for which take is getting set.

  • netuid (int) – Unique identifier of for the subnet.

  • take (float) – Value of childhotkey take on subnet.

  • wait_for_inclusion (bool) – If true, waits for inclusion before returning.

  • wait_for_finalization (bool) – If true, waits for finalization before returning.

  • prompt (bool, optional) – If True, prompts for user confirmation before proceeding.

Returns:

True if the extrinsic was successful.

Return type:

success (bool)

Raises:

ChildHotkeyError – If the extrinsic failed.

_do_set_childkey_take(wallet, hotkey, take, netuid, wait_for_inclusion=True, wait_for_finalization=False)#

Sends a set_children hotkey extrinsic on the chain.

Parameters:
  • wallet (bittensor.wallet()) – Wallet object that can sign the extrinsic.

  • hotkey (str) – (str): Hotkey ss58 address of the wallet for which take is getting set.

  • take (int) – (int): The take that this ss58 hotkey will have if assigned as a child hotkey as u16 value.

  • netuid (int) – Unique identifier for the network.

  • wait_for_inclusion (bool) – If true, waits for inclusion before returning.

  • wait_for_finalization (bool) – If true, waits for finalization before returning.

Returns:

True if the extrinsic was successful.

Return type:

success (bool)

set_children(wallet, hotkey, children_with_proportions, netuid, wait_for_inclusion=True, wait_for_finalization=False, prompt=False)#

Sets a children hotkeys extrinsic on the subnet.

Parameters:
  • wallet (bittensor.wallet()) – Wallet object that can sign the extrinsic.

  • hotkey (str) – (str): Hotkey ss58 address of the parent.

  • netuid (int) – Unique identifier of for the subnet.

  • children_with_proportions (List[Tuple[float, str]]) – List of (proportion, child_ss58) pairs.

  • wait_for_inclusion (bool) – If true, waits for inclusion before returning.

  • wait_for_finalization (bool) – If true, waits for finalization before returning.

  • prompt (bool, optional) – If True, prompts for user confirmation before proceeding.

Returns:

True if the extrinsic was successful.

Return type:

success (bool)

Raises:

ChildHotkeyError – If the extrinsic failed.

_do_set_children(wallet, hotkey, children, netuid, wait_for_inclusion=True, wait_for_finalization=False)#

Sends a set_children hotkey extrinsic on the chain.

Parameters:
  • wallet (bittensor.wallet()) – Wallet object that can sign the extrinsic.

  • hotkey (str) – (str): Hotkey ss58 address of the parent.

  • children (List[Tuple[int, str]]) – (List[Tuple[int, str]]): A list of tuples containing the hotkey ss58 addresses of the children and their proportions as u16 MAX standardized values.

  • netuid (int) – Unique identifier for the network.

  • wait_for_inclusion (bool) – If true, waits for inclusion before returning.

  • wait_for_finalization (bool) – If true, waits for finalization before returning.

Returns:

True if the extrinsic was successful.

Return type:

success (bool)

check_in_arbitration(ss58_address)#

Checks storage function to see if the provided coldkey is in arbitration. If 0, swap has not been called on this key. If 1, swap has been called once, so the key is not in arbitration. If >1, swap has been called with multiple destinations, and the key is thus in arbitration.

Parameters:

ss58_address (str)

Return type:

int

get_remaining_arbitration_period(coldkey_ss58, block=None)#

Retrieves the remaining arbitration period for a given coldkey. :param coldkey_ss58: The SS58 address of the coldkey. :type coldkey_ss58: str :param block: The block number to query. If None, uses the latest block. :type block: Optional[int], optional

Returns:

The remaining arbitration period in blocks, or 0 if not found.

Return type:

Optional[int]

Parameters:
  • coldkey_ss58 (str)

  • block (Optional[int])

register_senate(wallet, wait_for_inclusion=True, wait_for_finalization=False, prompt=False)#

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) – The wallet associated with the neuron from which the stake is being removed.

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

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

  • prompt (bool, optional) – If True, prompts for user confirmation before proceeding.

Returns:

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.

leave_senate(wallet, wait_for_inclusion=True, wait_for_finalization=False, prompt=False)#

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) – The wallet associated with the neuron from which the stake is being removed.

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

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

  • prompt (bool, optional) – If True, prompts for user confirmation before proceeding.

Returns:

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.

vote_senate(wallet, proposal_hash, proposal_idx, vote, wait_for_inclusion=True, wait_for_finalization=False, prompt=False)#

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) – The wallet associated with the neuron from which the stake is being removed.

  • proposal_hash (str) – The hash of the proposal being voted on.

  • proposal_idx (int) – The index of the proposal being voted on.

  • vote (bool) – The vote to be cast (True for yes, False for no).

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

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

  • prompt (bool, optional) – If True, prompts for user confirmation before proceeding.

Returns:

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.

is_senate_member(hotkey_ss58, block=None)#

Checks if a given neuron (identified by its hotkey SS58 address) is a member of the Bittensor senate. The senate is a key governance body within the Bittensor network, responsible for overseeing and approving various network operations and proposals.

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

  • block (Optional[int]) – The blockchain block number at which to check senate membership.

Returns:

True if the neuron is a senate member at the given block, False otherwise.

Return type:

bool

This function is crucial for understanding the governance dynamics of the Bittensor network and for identifying the neurons that hold decision-making power within the network.

get_vote_data(proposal_hash, block=None)#

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 to query the voting data.

Returns:

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

Return type:

Optional[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.

get_proposal_vote_data#
get_senate_members(block=None)#

Retrieves the list of current senate members from the Bittensor blockchain. Senate members are responsible for governance and decision-making within the network.

Parameters:

block (Optional[int]) – The blockchain block number at which to retrieve the senate members.

Returns:

A list of SS58 addresses of current senate members, or None if not available.

Return type:

Optional[List[str]]

Understanding the composition of the senate is key to grasping the governance structure and decision-making authority within the Bittensor network.

get_proposal_call_data(proposal_hash, block=None)#

Retrieves the call data of a specific proposal on the Bittensor blockchain. This data provides detailed information about the proposal, including its purpose and specifications.

Parameters:
  • proposal_hash (str) – The hash of the proposal.

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

Returns:

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

Return type:

Optional[GenericCall]

This function is crucial for analyzing the types of proposals made within the network and the specific changes or actions they intend to implement or address.

get_proposal_hashes(block=None)#

Retrieves the list of proposal hashes currently present on the Bittensor blockchain. Each hash uniquely identifies a proposal made within the network.

Parameters:

block (Optional[int]) – The blockchain block number to query the proposal hashes.

Returns:

A list of proposal hashes, or None if not available.

Return type:

Optional[List[str]]

This function enables tracking and reviewing the proposals made in the network, offering insights into the active governance and decision-making processes.

get_proposals(block=None)#

Retrieves all active proposals on the Bittensor blockchain, along with their call and voting data. This comprehensive view allows for a thorough understanding of the proposals and their reception by the senate.

Parameters:

block (Optional[int]) – The blockchain block number to query the proposals.

Returns:

A dictionary mapping

proposal hashes to their corresponding call and vote data, or None if not available.

Return type:

Optional[Dict[str, Tuple[bittensor.ProposalCallData, bittensor.ProposalVoteData]]]

This function is integral for analyzing the governance activity on the Bittensor network, providing a holistic view of the proposals and their impact or potential changes within the network.

root_register(wallet, wait_for_inclusion=False, wait_for_finalization=True, prompt=False)#

Registers the neuron associated with the wallet on the root network. This process is integral for participating in the highest layer of decision-making and governance within the Bittensor network.

Parameters:
  • wallet (bittensor.wallet) – The wallet associated with the neuron to be registered on the root network.

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

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

  • prompt (bool, optional) – If True, prompts for user confirmation before proceeding.

Returns:

True if the registration on the root network is successful, False otherwise.

Return type:

bool

This function enables neurons to engage in the most critical and influential aspects of the network’s governance, signifying a high level of commitment and responsibility in the Bittensor ecosystem.

_do_root_register(wallet, wait_for_inclusion=False, wait_for_finalization=True)#
Parameters:
  • wallet (bittensor.wallet)

  • wait_for_inclusion (bool)

  • wait_for_finalization (bool)

Return type:

Tuple[bool, Optional[str]]

root_set_weights(wallet, netuids, weights, version_key=0, wait_for_inclusion=False, wait_for_finalization=False, prompt=False)#

Sets the weights for neurons on the root network. This action is crucial for defining the influence and interactions of neurons at the root level of the Bittensor network.

Parameters:
  • wallet (bittensor.wallet) – The wallet associated with the neuron setting the weights.

  • netuids (Union[NDArray[np.int64], torch.LongTensor, list]) – The list of neuron UIDs for which weights are being set.

  • weights (Union[NDArray[np.float32], torch.FloatTensor, list]) – The corresponding weights to be set for each UID.

  • version_key (int, optional) – Version key for compatibility with the network.

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

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

  • prompt (bool, optional) – If True, prompts for user confirmation before proceeding.

Returns:

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

Return type:

bool

This function plays a pivotal role in shaping the root network’s collective intelligence and decision-making processes, reflecting the principles of decentralized governance and collaborative learning in Bittensor.

_do_set_root_weights(wallet, uids, vals, netuid=0, version_key=bittensor.__version_as_int__, wait_for_inclusion=False, wait_for_finalization=False)#

Internal method to send a transaction to the Bittensor blockchain, setting weights for specified neurons on root. This method constructs and submits the transaction, handling retries and blockchain communication.

Parameters:
  • wallet (bittensor.wallet) – The wallet associated with the neuron setting the weights.

  • uids (List[int]) – List of neuron UIDs for which weights are being set.

  • vals (List[int]) – List of weight values corresponding to each UID.

  • netuid (int) – Unique identifier for the network.

  • version_key (int, optional) – Version key for compatibility with the network.

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

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

Returns:

A tuple containing a success flag and an optional error message.

Return type:

Tuple[bool, Optional[str]]

This method is vital for the dynamic weighting mechanism in Bittensor, where neurons adjust their trust in other neurons based on observed performance and contributions on the root network.

query_identity(key, block=None)#

Queries the identity of a neuron on the Bittensor blockchain using the given key. This function retrieves detailed identity information about a specific neuron, which is a crucial aspect of the network’s decentralized identity and governance system.

Note

See the Bittensor CLI documentation for supported identity parameters.

Parameters:
  • key (str) – The key used to query the neuron’s identity, typically the neuron’s SS58 address.

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

Returns:

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

Return type:

result (dict)

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.

update_identity(wallet, identified=None, params=None, wait_for_inclusion=True, wait_for_finalization=False)#

Updates the identity of a neuron on the Bittensor blockchain. This function allows neurons to modify their identity attributes, reflecting changes in their roles, stakes, or other network-specific parameters.

Note

See the Bittensor CLI documentation for supported identity parameters.

Parameters:
  • wallet (bittensor.wallet) – The wallet associated with the neuron whose identity is being updated.

  • identified (str, optional) – The identified SS58 address of the neuron. Defaults to the wallet’s coldkey address.

  • params (dict, optional) – A dictionary of parameters to update in the neuron’s identity.

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

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

Returns:

True if the identity update is successful, False otherwise.

Return type:

bool

This function plays a vital role in maintaining the accuracy and currency of neuron identities in the Bittensor network, ensuring that the network’s governance and consensus mechanisms operate effectively.

commit(wallet, netuid, data)#

Commits arbitrary data to the Bittensor network by publishing metadata.

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

get_commitment(netuid, uid, block=None)#

Retrieves the on-chain commitment for a specific neuron in the Bittensor network.

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.

Returns:

The commitment data as a string.

Return type:

str

query_subtensor(name, block=None, params=None)#

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.

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

Returns:

An object containing the requested data.

Return type:

query_response (ScaleType)

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.

query_map_subtensor(name, block=None, params=None)#

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.

  • params (Optional[List[object]], optional) – 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:

QueryMapResult

This function is particularly useful for analyzing and understanding complex network structures and relationships within the Bittensor ecosystem, such as inter-neuronal connections and stake distributions.

query_constant(module_name, constant_name, block=None)#

Retrieves a constant from the specified module on the Bittensor blockchain. This function is used to access fixed parameters or values defined within the blockchain’s modules, which are essential for understanding the network’s configuration and rules.

Parameters:
  • module_name (str) – The name of the module containing the constant.

  • constant_name (str) – The name of the constant to retrieve.

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

Returns:

The value of the constant if found, None otherwise.

Return type:

Optional[ScaleType]

Constants queried through this function can include critical network parameters such as inflation rates, consensus rules, or validation thresholds, providing a deeper understanding of the Bittensor network’s operational parameters.

query_module(module, name, block=None, params=None)#

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.

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

Returns:

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

Return type:

Optional[ScaleType]

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.

query_map(module, name, block=None, params=None)#

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.

  • name (str) – The specific storage function within the module to query.

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

  • params (Optional[List[object]], optional) – Parameters to be passed to the query.

Returns:

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

Return type:

result (QueryMapResult)

This function is particularly useful for retrieving detailed and structured data from various blockchain modules, offering insights into the network’s state and the relationships between its different components.

state_call(method, data, block=None)#

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.

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.

query_runtime_api(runtime_api, method, params, block=None)#

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[List[ParamWithTypes]], optional) – The parameters to pass to the method call.

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

Returns:

The Scale Bytes encoded result from the runtime API call, or None if the call fails.

Return type:

Optional[bytes]

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

_encode_params(call_definition, params)#

Returns a hex encoded string of the params using their types.

Parameters:
Return type:

str

_get_hyperparameter(param_name, netuid, block=None)#

Retrieves a specified hyperparameter for a specific subnet.

Parameters:
  • param_name (str) – The name of the hyperparameter to retrieve.

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

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

Returns:

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

otherwise.

Return type:

Optional[Union[int, float]]

rho(netuid, block=None)#

Retrieves the ‘Rho’ hyperparameter for a specified subnet within the Bittensor network. ‘Rho’ represents the global inflation rate, which directly influences the network’s token emission rate and economic model.

Note

This is currently fixed such that the Bittensor blockchain emmits 7200 Tao per day.

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

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

Returns:

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

Return type:

Optional[int]

Mathematical Context:

Rho (p) is calculated based on the network’s target inflation and actual neuron staking. It adjusts the emission rate of the TAO token to balance the network’s economy and dynamics. The formula for Rho is defined as: p = (Staking_Target / Staking_Actual) * Inflation_Target. Here, Staking_Target and Staking_Actual represent the desired and actual total stakes in the network, while Inflation_Target is the predefined inflation rate goal.

‘Rho’ is essential for understanding the network’s economic dynamics, affecting the reward distribution and incentive structures across the network’s neurons.

kappa(netuid, block=None)#

Retrieves the ‘Kappa’ hyperparameter for a specified subnet. ‘Kappa’ is a critical parameter in the Bittensor network that controls the distribution of stake weights among neurons, impacting their rankings and incentive allocations.

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

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

Returns:

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

Return type:

Optional[float]

Mathematical Context:

Kappa (κ) is used in the calculation of neuron ranks, which determine their share of network incentives. It is derived from the softmax function applied to the inter-neuronal weights set by each neuron. The formula for Kappa is: κ_i = exp(w_i) / Σ(exp(w_j)), where w_i represents the weight set by neuron i, and the denominator is the sum of exponential weights set by all neurons. This mechanism ensures a normalized and probabilistic distribution of ranks based on relative weights.

Understanding ‘Kappa’ is crucial for analyzing stake dynamics and the consensus mechanism within the network, as it plays a significant role in neuron ranking and incentive allocation processes.

difficulty(netuid, block=None)#

Retrieves the ‘Difficulty’ hyperparameter for a specified subnet in the Bittensor network. This parameter is instrumental in determining the computational challenge required for neurons to participate in consensus and validation processes.

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

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

Returns:

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

Return type:

Optional[int]

The ‘Difficulty’ parameter directly impacts the network’s security and integrity by setting the computational effort required for validating transactions and participating in the network’s consensus mechanism.

recycle(netuid, block=None)#

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.

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.

immunity_period(netuid, block=None)#

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.

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.

validator_batch_size(netuid, block=None)#

Returns network ValidatorBatchSize hyper parameter.

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

  • block (Optional[int]) – The block number to retrieve the parameter from. If None, the latest block is used. Default is None.

Returns:

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

or the parameter is not found.

Return type:

Optional[int]

validator_prune_len(netuid, block=None)#

Returns network ValidatorPruneLen hyper parameter.

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

  • block (Optional[int]) – The block number to retrieve the parameter from. If None, the latest block

  • None. (is used. Default is)

Returns:

The value of the ValidatorPruneLen hyperparameter, or None if the subnetwork does not exist or the parameter is not found.

Return type:

Optional[int]

validator_logits_divergence(netuid, block=None)#

Returns network ValidatorLogitsDivergence hyper parameter.

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

  • block (Optional[int]) – The block number to retrieve the parameter from. If None, the latest block

  • None. (is used. Default is)

Returns:

The value of the ValidatorLogitsDivergence hyperparameter, or None if the subnetwork does not exist or the parameter is not found.

Return type:

Optional[float]

validator_sequence_length(netuid, block=None)#

Returns network ValidatorSequenceLength hyperparameter.

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

  • block (Optional[int], optional) – The block number to retrieve the parameter from. If None, the latest block is used. Default is None.

Returns:

The value of the ValidatorSequenceLength hyperparameter, or None if the subnetwork does

not exist or the parameter is not found.

Return type:

Optional[int]

validator_epochs_per_reset(netuid, block=None)#

Returns network ValidatorEpochsPerReset hyperparameter.

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

  • block (Optional[int], optional) – The block number to retrieve the parameter from. If None, the latest block is used. Default is None.

Returns:

The value of the ValidatorEpochsPerReset hyperparameter, or None if the subnetwork does

not exist or the parameter is not found.

Return type:

Optional[int]

validator_epoch_length(netuid, block=None)#

Returns network ValidatorEpochLen hyperparameter.

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

  • block (Optional[int], optional) – The block number to retrieve the parameter from. If None, the latest block is used. Default is None.

Returns:

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

exist or the parameter is not found.

Return type:

Optional[int]

validator_exclude_quantile(netuid, block=None)#

Returns network ValidatorExcludeQuantile hyperparameter.

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

  • block (Optional[int], optional) – The block number to retrieve the parameter from. If None, the latest block is used. Default is None.

Returns:

The value of the ValidatorExcludeQuantile hyperparameter, or None if the subnetwork does not exist or the parameter is not found.

Return type:

Optional[float]

max_allowed_validators(netuid, block=None)#

Returns network ValidatorExcludeQuantile hyperparameter.

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

  • block (Optional[int], optional) – The block number to retrieve the parameter from. If None, the latest block is used. Default is None.

Returns:

The value of the ValidatorExcludeQuantile hyperparameter, or None if the subnetwork

does not exist or the parameter is not found.

Return type:

Optional[float]

min_allowed_weights(netuid, block=None)#

Returns network MinAllowedWeights hyperparameter.

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

  • block (Optional[int], optional) – The block number to retrieve the parameter from. If None, the latest block is used. Default is None.

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]

max_weight_limit(netuid, block=None)#

Returns network MaxWeightsLimit hyperparameter.

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

  • block (Optional[int], optional) – The block number to retrieve the parameter from. If None, the latest block is used. Default is None.

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]

adjustment_alpha(netuid, block=None)#

Returns network AdjustmentAlpha hyperparameter.

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

  • block (Optional[int], optional) – The block number to retrieve the parameter from. If None, the latest block is used. Default is None.

Returns:

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

exist or the parameter is not found.

Return type:

Optional[float]

bonds_moving_avg(netuid, block=None)#

Returns network BondsMovingAverage hyperparameter.

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

  • block (Optional[int], optional) – The block number to retrieve the parameter from. If None, the latest block is used. Default is None.

Returns:

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

exist or the parameter is not found.

Return type:

Optional[float]

scaling_law_power(netuid, block=None)#

Returns network ScalingLawPower hyper parameter

Parameters:
  • netuid (int)

  • block (Optional[int])

Return type:

Optional[float]

synergy_scaling_law_power(netuid, block=None)#

Returns network ScalingLawPower hyperparameter.

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

  • block (Optional[int], optional) – The block number to retrieve the parameter from. If None, the latest block is used. Default is None.

Returns:

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

exist or the parameter is not found.

Return type:

Optional[float]

subnetwork_n(netuid, block=None)#

Returns network SubnetworkN hyperparameter.

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

  • block (Optional[int], optional) – The block number to retrieve the parameter from. If None, the latest block is used. Default is None.

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]

max_n(netuid, block=None)#

Returns network MaxAllowedUids hyperparameter.

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

  • block (Optional[int], optional) – The block number to retrieve the parameter from. If None, the latest block is used. Default is None.

Returns:

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

exist or the parameter is not found.

Return type:

Optional[int]

blocks_since_epoch(netuid, block=None)#

Returns network BlocksSinceEpoch hyperparameter.

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

  • block (Optional[int], optional) – The block number to retrieve the parameter from. If None, the latest block is used. Default is None.

Returns:

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

exist or the parameter is not found.

Return type:

Optional[int]

blocks_since_last_update(netuid, uid)#

Returns the number of blocks since the last update for a specific UID in the subnetwork.

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]

weights_rate_limit(netuid)#

Returns network WeightsSetRateLimit hyperparameter.

Parameters:

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

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]

tempo(netuid, block=None)#

Returns network Tempo hyperparameter.

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

  • block (Optional[int], optional) – The block number to retrieve the parameter from. If None, the latest block is used. Default is None.

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]

get_total_stake_for_hotkey(ss58_address, block=None)#

Returns the total stake held on a hotkey including delegative.

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

  • block (Optional[int], optional) – The block number to retrieve the stake from. If None, the latest block is used. Default is None.

Returns:

The total stake held on the hotkey, or None if the hotkey does not

exist or the stake is not found.

Return type:

Optional[Balance]

get_total_stake_for_coldkey(ss58_address, block=None)#

Returns the total stake held on a coldkey.

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

  • block (Optional[int], optional) – The block number to retrieve the stake from. If None, the latest block is used. Default is None.

Returns:

The total stake held on the coldkey, or None if the coldkey does not

exist or the stake is not found.

Return type:

Optional[Balance]

get_stake_for_coldkey_and_hotkey(hotkey_ss58, coldkey_ss58, block=None)#

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.

  • block (Optional[int], optional) – The block number to retrieve the stake from. If None, the latest block is used. Default is None.

Returns:

The stake under the coldkey - hotkey pairing, or None if the pairing does not

exist or the stake is not found.

Return type:

Optional[Balance]

get_stake(hotkey_ss58, block=None)#

Returns a list of stake tuples (coldkey, balance) for each delegating coldkey including the owner.

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

  • block (Optional[int], optional) – The block number to retrieve the stakes from. If None, the latest block is used. Default is None.

Returns:

A list of tuples, each containing a coldkey SS58 address and the corresponding

balance staked by that coldkey.

Return type:

List[Tuple[str, Balance]]

does_hotkey_exist(hotkey_ss58, block=None)#

Returns true if the hotkey is known by the chain and there are accounts.

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

  • block (Optional[int], optional) – The block number to check the hotkey against. If None, the latest block is used. Default is None.

Returns:

True if the hotkey is known by the chain and there are accounts, False otherwise.

Return type:

bool

get_hotkey_owner(hotkey_ss58, block=None)#

Returns the coldkey owner of the passed hotkey.

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

  • block (Optional[int], optional) – The block number to check the hotkey owner against. If None, the latest block is used. Default is None.

Returns:

The SS58 address of the coldkey owner, or None if the hotkey does not exist or the owner

is not found.

Return type:

Optional[str]

get_axon_info(netuid, hotkey_ss58, block=None)#

Returns the axon information for this hotkey account.

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

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

  • block (Optional[int], optional) – The block number to retrieve the axon information from. If None, the latest block is used. Default is None.

Returns:

An AxonInfo object containing the axon information, or None if the axon information

is not found.

Return type:

Optional[AxonInfo]

get_prometheus_info(netuid, hotkey_ss58, block=None)#

Returns the prometheus information for this hotkey account.

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

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

  • block (Optional[int], optional) – The block number to retrieve the prometheus information from. If None, the latest block is used. Default is None.

Returns:

A PrometheusInfo object containing the prometheus information, or None if the

prometheus information is not found.

Return type:

Optional[PrometheusInfo]

property block: int#

Returns current chain block. :returns: Current chain block. :rtype: block (int)

Return type:

int

total_issuance(block=None)#

Retrieves the total issuance of the Bittensor network’s native token (Tao) as of a specific blockchain block. This represents the total amount of currency that has been issued or mined on the network.

Parameters:

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

Returns:

The total issuance of TAO, represented as a Balance object.

Return type:

Balance

The total issuance is a key economic indicator in the Bittensor network, reflecting the overall supply of the currency and providing insights into the network’s economic health and inflationary trends.

total_stake(block=None)#

Retrieves the total amount of TAO staked on the Bittensor network as of a specific blockchain block. This represents the cumulative stake across all neurons in the network, indicating the overall level of participation and investment by the network’s participants.

Parameters:

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

Returns:

The total amount of TAO staked on the network, represented as a Balance object.

Return type:

Balance

The total stake is an important metric for understanding the network’s security, governance dynamics, and the level of commitment by its participants. It is also a critical factor in the network’s consensus and incentive mechanisms.

serving_rate_limit(netuid, block=None)#

Retrieves the serving rate limit for a specific subnet within the Bittensor network. This rate limit determines how often you can change your node’s IP address on the blockchain. Expressed in number of blocks. Applies to both subnet validator and subnet miner nodes. Used when you move your node to a new machine.

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

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

Returns:

The serving rate limit of the subnet if it exists, None otherwise.

Return type:

Optional[int]

The serving rate limit is a crucial parameter for maintaining network efficiency and preventing overuse of resources by individual neurons. It helps ensure a balanced distribution of service requests across the network.

tx_rate_limit(block=None)#

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], optional) – The blockchain block number at which to perform the query.

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.

subnet_exists(netuid, block=None)#

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], optional) – The blockchain block number at which to check the subnet’s existence.

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.

get_all_subnet_netuids(block=None)#

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

Parameters:

block (Optional[int], optional) – The blockchain block number at which to retrieve the subnet netuids.

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.

get_total_subnets(block=None)#

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

Parameters:

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

Returns:

The total number of subnets in the network.

Return type:

int

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

get_subnet_modality(netuid, block=None)#

Returns the NetworkModality hyperparameter for a specific subnetwork.

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

  • block (Optional[int], optional) – The block number to retrieve the parameter from. If None, the latest block is used. Default is None.

Returns:

The value of the NetworkModality hyperparameter, or None if the subnetwork does not exist or the parameter is not found.

Return type:

Optional[int]

get_subnet_connection_requirement(netuid_0, netuid_1, block=None)#
Parameters:
  • netuid_0 (int)

  • netuid_1 (int)

  • block (Optional[int])

Return type:

Optional[int]

get_emission_value_by_subnet(netuid, block=None)#

Retrieves the emission value of a specific subnet within the Bittensor network. The emission value represents the rate at which the subnet emits or distributes the network’s native token (Tao).

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

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

Returns:

The emission value of the subnet, None if not available.

Return type:

Optional[float]

The emission value is a critical economic parameter, influencing the incentive distribution and reward mechanisms within the subnet.

get_subnet_connection_requirements(netuid, block=None)#

Retrieves the connection requirements for a specific subnet within the Bittensor network. This function provides details on the criteria that must be met for neurons to connect to the subnet.

Parameters:
  • netuid (int) – The network UID of the subnet to query.

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

Returns:

A dictionary detailing the connection requirements for the subnet.

Return type:

Dict[str, int]

Understanding these requirements is crucial for neurons looking to participate in or interact with specific subnets, ensuring compliance with their connection standards.

get_subnets(block=None)#

Retrieves a list of all subnets currently active within the Bittensor network. This function provides an overview of the various subnets and their identifiers.

Parameters:

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

Returns:

A list of network UIDs representing each active subnet.

Return type:

List[int]

This function is valuable for understanding the network’s structure and the diversity of subnets available for neuron participation and collaboration.

get_all_subnets_info(block=None)#

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], optional) – The blockchain block number for the query.

Returns:

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

Return type:

List[SubnetInfo]

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

get_subnet_info(netuid, block=None)#

Retrieves detailed information about a specific subnet within the Bittensor network. This function provides key data on the subnet, including its operational parameters and network status.

Parameters:
  • netuid (int) – The network UID of the subnet to query.

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

Returns:

Detailed information about the subnet, or None if not found.

Return type:

Optional[SubnetInfo]

This function is essential for neurons and stakeholders interested in the specifics of a particular subnet, including its governance, performance, and role within the broader network.

get_subnet_hyperparameters(netuid, block=None)#

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], optional) – The blockchain block number for the query.

Returns:

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

Return type:

Optional[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.

get_subnet_owner(netuid, block=None)#

Retrieves the owner’s address of a specific subnet within the Bittensor network. The owner is typically the entity responsible for the creation and maintenance of the subnet.

Parameters:
  • netuid (int) – The network UID of the subnet to query.

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

Returns:

The SS58 address of the subnet’s owner, or None if not available.

Return type:

Optional[str]

Knowing the subnet owner provides insights into the governance and operational control of the subnet, which can be important for decision-making and collaboration within the network.

is_hotkey_delegate(hotkey_ss58, block=None)#

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], optional) – The blockchain block number for the query.

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.

get_delegate_take(hotkey_ss58, block=None)#

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], optional) – The blockchain block number for the query.

Returns:

The delegate take percentage, None if not available.

Return type:

Optional[float]

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

get_nominators_for_hotkey(hotkey_ss58, block=None)#

Retrieves a list of nominators and their stakes for a neuron identified by its hotkey. Nominators are neurons that stake their tokens on a delegate to support its operations.

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

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

Returns:

A list of tuples containing each nominator’s address and staked amount or 0.

Return type:

Union[List[Tuple[str, Balance]], int]

This function provides insights into the neuron’s support network within the Bittensor ecosystem, indicating its trust and collaboration relationships.

get_delegate_by_hotkey(hotkey_ss58, block=None)#

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], optional) – The blockchain block number for the query.

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.

get_delegates_lite(block=None)#

Retrieves a lighter list of all delegate neurons within the Bittensor network. This function provides an overview of the neurons that are actively involved in the network’s delegation system.

Analyzing the delegate population offers insights into the network’s governance dynamics and the distribution of trust and responsibility among participating neurons.

This is a lighter version of get_delegates().

Parameters:

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

Returns:

A list of DelegateInfoLite objects detailing each delegate’s characteristics.

Return type:

List[DelegateInfoLite]

get_delegates(block=None)#

Retrieves a list of all delegate neurons within the Bittensor network. This function provides an overview of the neurons that are actively involved in the network’s delegation system.

Analyzing the delegate population offers insights into the network’s governance dynamics and the distribution of trust and responsibility among participating neurons.

Parameters:

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

Returns:

A list of DelegateInfo objects detailing each delegate’s characteristics.

Return type:

List[DelegateInfo]

get_delegated(coldkey_ss58, block=None)#

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], optional) – The blockchain block number for the query.

Returns:

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

amount.

Return type:

List[Tuple[DelegateInfo, Balance]]

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

get_childkey_take(hotkey, netuid, block=None)#

Get the childkey take of a hotkey on a specific network. Args: - hotkey (str): The hotkey to search for. - netuid (int): The netuid to search for. - block (Optional[int]): Optional parameter specifying the block number. Defaults to None.

Returns: - Optional[int]: The value of the “ChildkeyTake” if found, or None if any error occurs.

Parameters:
  • hotkey (str)

  • netuid (int)

  • block (Optional[int])

Return type:

Optional[int]

get_children(hotkey, netuid)#

Get the children of a hotkey on a specific network. :param hotkey: The hotkey to query. :type hotkey: str :param netuid: The network ID. :type netuid: int

Returns:

List of (proportion, child_address) tuples, or None if an error occurred.

Return type:

list or None

get_parents(child_hotkey, netuid)#

Get the parents of a child hotkey on a specific network. :param child_hotkey: The child hotkey to query. :type child_hotkey: str :param netuid: The network ID. :type netuid: int

Returns:

List of (proportion, parent_address) tuples, or None if an error occurred.

Return type:

list or None

get_stake_info_for_coldkey(coldkey_ss58, block=None)#

Retrieves stake information associated with a specific coldkey. This function provides details about the stakes held by an account, including the staked amounts and associated delegates.

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

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

Returns:

A list of StakeInfo objects detailing the stake allocations for the account.

Return type:

List[StakeInfo]

Stake information is vital for account holders to assess their investment and participation in the network’s delegation and consensus processes.

get_stake_info_for_coldkeys(coldkey_ss58_list, block=None)#

Retrieves stake information for a list of coldkeys. This function aggregates stake data for multiple accounts, providing a collective view of their stakes and delegations.

Parameters:
  • coldkey_ss58_list (List[str]) – A list of SS58 addresses of the accounts’ coldkeys.

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

Returns:

A dictionary mapping each coldkey to a list of its StakeInfo objects.

Return type:

Dict[str, List[StakeInfo]]

This function is useful for analyzing the stake distribution and delegation patterns of multiple accounts simultaneously, offering a broader perspective on network participation and investment strategies.

get_minimum_required_stake()#

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

This method retries the substrate call up to three times with exponential backoff in case of failures.

Returns:

The minimum required stake as a Balance object.

Return type:

Balance

Raises:

Exception – If the substrate call fails after the maximum number of retries.

is_hotkey_registered_any(hotkey_ss58, block=None)#

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

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.

is_hotkey_registered_on_subnet(hotkey_ss58, netuid, block=None)#

Checks if a neuron’s hotkey is registered on a specific 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 at which to perform the check.

Returns:

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

Return type:

bool

This function helps in assessing the participation of a neuron in a particular subnet, indicating its specific area of operation or influence within the network.

is_hotkey_registered(hotkey_ss58, netuid=None, block=None)#

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.

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.

get_uid_for_hotkey_on_subnet(hotkey_ss58, netuid, block=None)#

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.

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.

get_all_uids_for_hotkey(hotkey_ss58, block=None)#

Retrieves all unique identifiers (UIDs) associated with a given hotkey across different subnets within the Bittensor network. This function helps in identifying all the neuron instances that are linked to a specific hotkey.

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

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

Returns:

A list of UIDs associated with the given hotkey across various subnets.

Return type:

List[int]

This function is important for tracking a neuron’s presence and activities across different subnets within the Bittensor ecosystem.

get_netuids_for_hotkey(hotkey_ss58, block=None)#

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

Returns:

A list of netuids where the neuron is a member.

Return type:

List[int]

get_neuron_for_pubkey_and_subnet(hotkey_ss58, netuid, block=None)#

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

Returns:

Detailed information about the neuron if found, None otherwise.

Return type:

Optional[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.

get_all_neurons_for_pubkey(hotkey_ss58, block=None)#

Retrieves information about all neuron instances associated with a given public key (hotkey SS58 address) across different subnets of the Bittensor network. This function aggregates neuron data from various subnets to provide a comprehensive view of a neuron’s presence and status within the network.

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

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

Returns:

A list of NeuronInfo objects detailing the neuron’s presence across various subnets.

Return type:

List[NeuronInfo]

This function is valuable for analyzing a neuron’s overall participation, influence, and contributions across the Bittensor network.

neuron_has_validator_permit(uid, netuid, block=None)#

Checks if a neuron, identified by its unique identifier (UID), has a validator permit on a specific subnet within the Bittensor network. This function determines whether the neuron is authorized to participate in validation processes on the subnet.

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

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

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

Returns:

True if the neuron has a validator permit, False otherwise.

Return type:

Optional[bool]

This function is essential for understanding a neuron’s role and capabilities within a specific subnet, particularly regarding its involvement in network validation and governance.

neuron_for_wallet(wallet, netuid, block=None)#

Retrieves information about a neuron associated with a given wallet on a specific subnet. This function provides detailed data about the neuron’s status, stake, and activities based on the wallet’s hotkey address.

Parameters:
  • wallet (bittensor.wallet) – The wallet associated with the neuron.

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

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

Returns:

Detailed information about the neuron if found, None otherwise.

Return type:

Optional[NeuronInfo]

This function is important for wallet owners to understand and manage their neuron’s presence and activities within a particular subnet of the Bittensor network.

neuron_for_uid(uid, netuid, block=None)#

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 (int) – The unique identifier of the neuron.

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

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

Returns:

Detailed information about the neuron if found, None otherwise.

Return type:

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.

neurons(netuid, block=None)#

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], optional) – The blockchain block number for the query.

Returns:

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

Return type:

List[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.

neuron_for_uid_lite(uid, netuid, block=None)#

Retrieves a lightweight version of information about a neuron in a specific subnet, identified by its UID. The ‘lite’ version focuses on essential attributes such as stake and network activity.

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

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

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

Returns:

A simplified version of neuron information if found, None otherwise.

Return type:

Optional[NeuronInfoLite]

This function is useful for quick and efficient analyses of neuron status and activities within a subnet without the need for comprehensive data retrieval.

neurons_lite(netuid, block=None)#

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], optional) – The blockchain block number for the query.

Returns:

A list of simplified neuron information for the subnet.

Return type:

List[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.

metagraph(netuid, lite=True, block=None)#

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, default=True) – If true, returns a metagraph using a lightweight sync (no weights, no bonds).

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

incentive(netuid, block=None)#

Retrieves the list of incentives for neurons within a specific subnet of the Bittensor network. This function provides insights into the reward distribution mechanisms and the incentives allocated to each neuron based on their contributions and activities.

Parameters:
  • netuid (int) – The network UID of the subnet to query.

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

Returns:

The list of incentives for neurons within the subnet, indexed by UID.

Return type:

List[int]

Understanding the incentive structure is crucial for analyzing the network’s economic model and the motivational drivers for neuron participation and collaboration.

weights(netuid, block=None)#

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]) – The blockchain block number for the query.

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.

bonds(netuid, block=None)#

Retrieves the bond distribution set by neurons within a specific subnet of the Bittensor network. Bonds represent the investments or commitments made by neurons in one another, indicating a level of trust and perceived value. This bonding mechanism is integral to the network’s market-based approach to measuring and rewarding machine intelligence.

Parameters:
  • netuid (int) – The network UID of the subnet to query.

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

Returns:

A list of tuples mapping each neuron’s UID to its bonds with other

neurons.

Return type:

List[Tuple[int, List[Tuple[int, int]]]]

Understanding bond distributions is crucial for analyzing the trust dynamics and market behavior within the subnet. It reflects how neurons recognize and invest in each other’s intelligence and contributions, supporting diverse and niche systems within the Bittensor ecosystem.

get_subnet_burn_cost(block=None)#

Retrieves the burn cost for registering a new subnet within the Bittensor network. This cost represents the amount of Tao that needs to be locked or burned to establish a new subnet.

Parameters:

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

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.

_do_delegation(wallet, delegate_ss58, amount, wait_for_inclusion=True, wait_for_finalization=False)#

Delegates a specified amount of stake to a delegate’s hotkey.

This method sends a transaction to add stake to a delegate’s hotkey and retries the call up to three times with exponential backoff in case of failures.

Parameters:
  • wallet (bittensor.wallet) – The wallet from which the stake will be delegated.

  • delegate_ss58 (str) – The SS58 address of the delegate’s hotkey.

  • amount (Balance) – The amount of stake to be delegated.

  • wait_for_inclusion (bool, optional) – Whether to wait for the transaction to be included in a block. Default is True.

  • wait_for_finalization (bool, optional) – Whether to wait for the transaction to be finalized. Default is False.

Returns:

True if the delegation is successful, False otherwise.

Return type:

bool

_do_undelegation(wallet, delegate_ss58, amount, wait_for_inclusion=True, wait_for_finalization=False)#

Removes a specified amount of stake from a delegate’s hotkey.

This method sends a transaction to remove stake from a delegate’s hotkey and retries the call up to three times with exponential backoff in case of failures.

Parameters:
  • wallet (bittensor.wallet) – The wallet from which the stake will be removed.

  • delegate_ss58 (str) – The SS58 address of the delegate’s hotkey.

  • amount (Balance) – The amount of stake to be removed.

  • wait_for_inclusion (bool, optional) – Whether to wait for the transaction to be included in a block. Default is True.

  • wait_for_finalization (bool, optional) – Whether to wait for the transaction to be finalized. Default is False.

Returns:

True if the undelegation is successful, False otherwise.

Return type:

bool

_do_nominate(wallet, wait_for_inclusion=True, wait_for_finalization=False)#

Nominates the wallet’s hotkey to become a delegate.

This method sends a transaction to nominate the wallet’s hotkey to become a delegate and retries the call up to three times with exponential backoff in case of failures.

Parameters:
  • wallet (bittensor.wallet) – The wallet whose hotkey will be nominated.

  • wait_for_inclusion (bool, optional) – Whether to wait for the transaction to be included in a block. Default is True.

  • wait_for_finalization (bool, optional) – Whether to wait for the transaction to be finalized. Default is False.

Returns:

True if the nomination is successful, False otherwise.

Return type:

bool

_do_increase_take(wallet, hotkey_ss58, take, wait_for_inclusion=True, wait_for_finalization=False)#

Increases the take rate for a delegate’s hotkey.

This method sends a transaction to increase the take rate for a delegate’s hotkey and retries the call up to three times with exponential backoff in case of failures.

Parameters:
  • wallet (bittensor.wallet) – The wallet from which the transaction will be signed.

  • hotkey_ss58 (str) – The SS58 address of the delegate’s hotkey.

  • take (int) – The new take rate to be set.

  • wait_for_inclusion (bool, optional) – Whether to wait for the transaction to be included in a block. Default is True.

  • wait_for_finalization (bool, optional) – Whether to wait for the transaction to be finalized. Default is False.

Returns:

True if the take rate increase is successful, False otherwise.

Return type:

bool

_do_decrease_take(wallet, hotkey_ss58, take, wait_for_inclusion=True, wait_for_finalization=False)#

Decreases the take rate for a delegate’s hotkey.

This method sends a transaction to decrease the take rate for a delegate’s hotkey and retries the call up to three times with exponential backoff in case of failures.

Parameters:
  • wallet (bittensor.wallet) – The wallet from which the transaction will be signed.

  • hotkey_ss58 (str) – The SS58 address of the delegate’s hotkey.

  • take (int) – The new take rate to be set.

  • wait_for_inclusion (bool, optional) – Whether to wait for the transaction to be included in a block. Default is True.

  • wait_for_finalization (bool, optional) – Whether to wait for the transaction to be finalized. Default is False.

Returns:

True if the take rate decrease is successful, False otherwise.

Return type:

bool

get_balance(address, block=None)#

Retrieves the token balance of a specific address within the Bittensor network. This function queries the blockchain to determine the amount of Tao held by a given account.

Parameters:
  • address (str) – The Substrate address in ss58 format.

  • block (int, optional) – The blockchain block number at which to perform the query.

Returns:

The account balance at the specified block, represented as a Balance object.

Return type:

Balance

This function is important for monitoring account holdings and managing financial transactions within the Bittensor ecosystem. It helps in assessing the economic status and capacity of network participants.

get_current_block()#

Returns the current block number on the Bittensor blockchain. This function provides the latest block number, indicating the most recent state of the blockchain.

Returns:

The current chain block number.

Return type:

int

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.

get_balances(block=None)#

Retrieves the token balances of all accounts within the Bittensor network as of a specific blockchain block. This function provides a comprehensive view of the token distribution among different accounts.

Parameters:

block (int, optional) – The blockchain block number at which to perform the query.

Returns:

A dictionary mapping each account’s ss58 address to its balance.

Return type:

Dict[str, Balance]

This function is valuable for analyzing the overall economic landscape of the Bittensor network, including the distribution of financial resources and the financial status of network participants.

static _null_neuron()#
Return type:

bittensor.chain_data.NeuronInfo

get_block_hash(block_id)#

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.

Parameters:

block_id (int) – The block number for which the hash is to be retrieved.

Returns:

The cryptographic hash of the specified block.

Return type:

str

The block hash is a fundamental aspect of blockchain technology, providing a secure reference to each block’s data. It is crucial for verifying transactions, ensuring data consistency, and maintaining the trustworthiness of the blockchain.

get_error_info_by_index(error_index)#

Returns the error name and description from the Subtensor error list.

Parameters:

error_index (int) – The index of the error to retrieve.

Returns:

A tuple containing the error name and description from substrate metadata. If the error index is not found, returns (“Unknown Error”, “”) and logs a warning.

Return type:

Tuple[str, str]

class bittensor.cli(config=None, args=None)[source]#

Implementation of the Command Line Interface (CLI) class for the Bittensor protocol. This class handles operations like key management (hotkey and coldkey) and token transfer.

Initializes a bittensor.CLI object.

Parameters:
  • config (bittensor.config, optional) – The configuration settings for the CLI.

  • args (List[str], optional) – List of command line arguments.

config#
static __create_parser__()[source]#

Creates the argument parser for the Bittensor CLI.

Returns:

An argument parser object for Bittensor CLI.

Return type:

argparse.ArgumentParser

static create_config(args)[source]#

From the argument parser, add config to bittensor.executor and local config

Parameters:

args (List[str]) – List of command line arguments.

Returns:

The configuration object for Bittensor CLI.

Return type:

bittensor.config

static check_config(config)[source]#

Checks if the essential configuration exists under different command

Parameters:

config (bittensor.config) – The configuration settings for the CLI.

run()[source]#

Executes the command from the configuration.

bittensor.ALL_COMMANDS#
bittensor.logging#
bittensor.metagraph#
class bittensor.PriorityThreadPoolExecutor(maxsize=-1, max_workers=None, thread_name_prefix='', initializer=None, initargs=())[source]#

Bases: concurrent.futures._base.Executor

Base threadpool executor with a priority queue

Initializes a new ThreadPoolExecutor instance.

Parameters:
  • max_workers – The maximum number of threads that can be used to execute the given calls.

  • thread_name_prefix – An optional name prefix to give our threads.

  • initializer – An callable used to initialize worker threads.

  • initargs – A tuple of arguments to pass to the initializer.

_counter#
_max_workers#
_work_queue#
_idle_semaphore#
_threads#
_broken = False#
_shutdown = False#
_shutdown_lock#
_thread_name_prefix#
_initializer#
_initargs#
classmethod add_args(parser, prefix=None)[source]#

Accept specific arguments from parser

Parameters:
classmethod config()[source]#

Get config from the argument parser.

Return: bittensor.config() object.

Return type:

bittensor.config

property is_empty#
submit(fn, *args, **kwargs)[source]#

Submits a callable to be executed with the given arguments.

Schedules the callable to be executed as fn(*args, **kwargs) and returns a Future instance representing the execution of the callable.

Returns:

A Future representing the given call.

Parameters:

fn (Callable)

Return type:

concurrent.futures._base.Future

_adjust_thread_count()[source]#
_initializer_failed()[source]#
shutdown(wait=True)[source]#

Clean-up the resources associated with the Executor.

It is safe to call this method several times. Otherwise, no other methods can be called after this one.

Parameters:
  • wait – If True then shutdown will not return until all running futures have finished executing and the resources used by the executor have been reclaimed.

  • cancel_futures – If True then shutdown will cancel all pending futures. Futures that are completed or running will not be cancelled.

class bittensor.TerminalInfo(/, **data)[source]#

Bases: pydantic.BaseModel

TerminalInfo encapsulates detailed information about a network synapse (node) involved in a communication process.

This class serves as a metadata carrier, providing essential details about the state and configuration of a terminal during network interactions. This is a crucial class in the Bittensor framework.

The TerminalInfo class contains information such as HTTP status codes and messages, processing times, IP addresses, ports, Bittensor version numbers, and unique identifiers. These details are vital for maintaining network reliability, security, and efficient data flow within the Bittensor network.

This class includes Pydantic validators and root validators to enforce data integrity and format. It is designed to be used natively within Synapses, so that you will not need to call this directly, but rather is used as a helper class for Synapses.

Parameters:
  • status_code (int) – HTTP status code indicating the result of a network request. Essential for identifying the outcome of network interactions.

  • status_message (str) – Descriptive message associated with the status code, providing additional context about the request’s result.

  • process_time (float) – Time taken by the terminal to process the call, important for performance monitoring and optimization.

  • ip (str) – IP address of the terminal, crucial for network routing and data transmission.

  • port (int) – Network port used by the terminal, key for establishing network connections.

  • version (int) – Bittensor version running on the terminal, ensuring compatibility between different nodes in the network.

  • nonce (int) – Unique, monotonically increasing number for each terminal, aiding in identifying and ordering network interactions.

  • uuid (str) – Unique identifier for the terminal, fundamental for network security and identification.

  • hotkey (str) – Encoded hotkey string of the terminal wallet, important for transaction and identity verification in the network.

  • signature (str) – Digital signature verifying the tuple of nonce, axon_hotkey, dendrite_hotkey, and uuid, critical for ensuring data authenticity and security.

  • data (Any)

Usage:

# Creating a TerminalInfo instance
terminal_info = TerminalInfo(
    status_code=200,
    status_message="Success",
    process_time=0.1,
    ip="198.123.23.1",
    port=9282,
    version=111,
    nonce=111111,
    uuid="5ecbd69c-1cec-11ee-b0dc-e29ce36fec1a",
    hotkey="5EnjDGNqqWnuL2HCAdxeEtN2oqtXZw6BMBe936Kfy2PFz1J1",
    signature="0x0813029319030129u4120u10841824y0182u091u230912u"
)

# Accessing TerminalInfo attributes
ip_address = terminal_info.ip
processing_duration = terminal_info.process_time

# TerminalInfo can be used to monitor and verify network interactions, ensuring proper communication and security within the Bittensor network.

TerminalInfo plays a pivotal role in providing transparency and control over network operations, making it an indispensable tool for developers and users interacting with the Bittensor ecosystem.

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

model_config#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

status_code: int | None#
status_message: str | None#
process_time: float | None#
ip: str | None#
port: int | None#
version: int | None#
nonce: int | None#
uuid: str | None#
hotkey: str | None#
signature: str | None#
_extract_process_time#
_extract_port#
_extract_version#
_extract_nonce#
_extract_status_code#
class bittensor.Synapse(/, **data)[source]#

Bases: pydantic.BaseModel

Represents a Synapse in the Bittensor network, serving as a communication schema between neurons (nodes).

Synapses ensure the format and correctness of transmission tensors according to the Bittensor protocol. Each Synapse type is tailored for a specific machine learning (ML) task, following unique compression and communication processes. This helps maintain sanitized, correct, and useful information flow across the network.

The Synapse class encompasses essential network properties such as HTTP route names, timeouts, request sizes, and terminal information. It also includes methods for serialization, deserialization, attribute setting, and hash computation, ensuring secure and efficient data exchange in the network.

The class includes Pydantic validators and root validators to enforce data integrity and format. Additionally, properties like is_success, is_failure, is_timeout, etc., provide convenient status checks based on dendrite responses.

Think of Bittensor Synapses as glorified pydantic wrappers that have been designed to be used in a distributed network. They provide a standardized way to communicate between neurons, and are the primary mechanism for communication between neurons in Bittensor.

Key Features:

  1. HTTP Route Name (name attribute):

    Enables the identification and proper routing of requests within the network. Essential for users defining custom routes for specific machine learning tasks.

  2. Query Timeout (timeout attribute):

    Determines the maximum duration allowed for a query, ensuring timely responses and network efficiency. Crucial for users to manage network latency and response times, particularly in time-sensitive applications.

  3. Request Sizes (total_size, header_size attributes):

    Keeps track of the size of request bodies and headers, ensuring efficient data transmission without overloading the network. Important for users to monitor and optimize the data payload, especially in bandwidth-constrained environments.

  4. Terminal Information (dendrite, axon attributes):

    Stores information about the dendrite (receiving end) and axon (sending end), facilitating communication between nodes. Users can access detailed information about the communication endpoints, aiding in debugging and network analysis.

  5. Body Hash Computation (computed_body_hash, required_hash_fields):

    Ensures data integrity and security by computing hashes of transmitted data. Provides users with a mechanism to verify data integrity and detect any tampering during transmission. It is recommended that names of fields in required_hash_fields are listed in the order they are defined in the class.

  6. Serialization and Deserialization Methods:

    Facilitates the conversion of Synapse objects to and from a format suitable for network transmission. Essential for users who need to customize data formats for specific machine learning models or tasks.

  7. Status Check Properties (is_success, is_failure, is_timeout, etc.):

    Provides quick and easy methods to check the status of a request, improving error handling and response management. Users can efficiently handle different outcomes of network requests, enhancing the robustness of their applications.

Example usage:

# Creating a Synapse instance with default values
synapse = Synapse()

# Setting properties and input
synapse.timeout = 15.0
synapse.name = "MySynapse"
# Not setting fields that are not defined in your synapse class will result in an error, e.g.:
synapse.dummy_input = 1 # This will raise an error because dummy_input is not defined in the Synapse class

# Get a dictionary of headers and body from the synapse instance
synapse_dict = synapse.model_dump_json()

# Get a dictionary of headers from the synapse instance
headers = synapse.to_headers()

# Reconstruct the synapse from headers using the classmethod 'from_headers'
synapse = Synapse.from_headers(headers)

# Deserialize synapse after receiving it over the network, controlled by `deserialize` method
deserialized_synapse = synapse.deserialize()

# Checking the status of the request
if synapse.is_success:
    print("Request succeeded")

# Checking and setting the status of the request
print(synapse.axon.status_code)
synapse.axon.status_code = 408 # Timeout
Parameters:
  • name (str) – HTTP route name, set on axon.attach().

  • timeout (float) – Total query length, set by the dendrite terminal.

  • total_size (int) – Total size of request body in bytes.

  • header_size (int) – Size of request header in bytes.

  • dendrite (TerminalInfo) – Information about the dendrite terminal.

  • axon (TerminalInfo) – Information about the axon terminal.

  • computed_body_hash (str) – Computed hash of the request body.

  • required_hash_fields (List[str]) – Fields required to compute the body hash.

  • data (Any)

deserialize()[source]#

Custom deserialization logic for subclasses.

Return type:

Synapse

__setattr__()[source]#

Override method to make required_hash_fields read-only.

Parameters:
  • name (str)

  • value (Any)

get_total_size()[source]#

Calculates and returns the total size of the object.

Return type:

int

to_headers()[source]#

Constructs a dictionary of headers from instance properties.

Return type:

dict

body_hash()#

Computes a SHA3-256 hash of the serialized body.

Return type:

str

parse_headers_to_inputs()[source]#

Parses headers to construct an inputs dictionary.

Parameters:

headers (dict)

Return type:

dict

from_headers()[source]#

Creates an instance from a headers dictionary.

Parameters:

headers (dict)

Return type:

Synapse

This class is a cornerstone in the Bittensor framework, providing the necessary tools for secure, efficient, and standardized communication in a decentralized environment.

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

model_config#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

_model_json_schema: ClassVar[Dict[str, Any]]#
deserialize()[source]#

Deserializes the Synapse object.

This method is intended to be overridden by subclasses for custom deserialization logic. In the context of the Synapse superclass, this method simply returns the instance itself. When inheriting from this class, subclasses should provide their own implementation for deserialization if specific deserialization behavior is desired.

By default, if a subclass does not provide its own implementation of this method, the Synapse’s deserialize method will be used, returning the object instance as-is.

In its default form, this method simply returns the instance of the Synapse itself without any modifications. Subclasses of Synapse can override this method to add specific deserialization behaviors, such as converting serialized data back into complex object types or performing additional data integrity checks.

Example:

class CustomSynapse(Synapse):
    additional_data: str

    def deserialize(self) -> "CustomSynapse":
        # Custom deserialization logic
        # For example, decoding a base64 encoded string in 'additional_data'
        if self.additional_data:
            self.additional_data = base64.b64decode(self.additional_data).decode('utf-8')
        return self

serialized_data = '{"additional_data": "SGVsbG8gV29ybGQ="}'  # Base64 for 'Hello World'
custom_synapse = CustomSynapse.model_validate_json(serialized_data)
deserialized_synapse = custom_synapse.deserialize()

# deserialized_synapse.additional_data would now be 'Hello World'
Returns:

The deserialized Synapse object. In this default implementation, it returns the object itself.

Return type:

Synapse

set_name_type(values)[source]#
Return type:

dict

name: str | None#
timeout: float | None#
total_size: int | None#
header_size: int | None#
dendrite: TerminalInfo | None#
axon: TerminalInfo | None#
computed_body_hash: str | None#
required_hash_fields: ClassVar[Tuple[str, Ellipsis]] = ()#
_extract_total_size#
_extract_header_size#
_extract_timeout#
__setattr__(name, value)[source]#

Override the __setattr__() method to make the required_hash_fields property read-only.

This is a security mechanism such that the required_hash_fields property cannot be overridden by the user or malicious code.

Parameters:
  • name (str)

  • value (Any)

get_total_size()[source]#

Get the total size of the current object.

This method first calculates the size of the current object, then assigns it to the instance variable self.total_size() and finally returns this value.

Returns:

The total size of the current object.

Return type:

int

property is_success: bool#

Checks if the dendrite’s status code indicates success.

This method returns True if the status code of the dendrite is 200, which typically represents a successful HTTP request.

Returns:

True if dendrite’s status code is 200, False otherwise.

Return type:

bool

property is_failure: bool#

Checks if the dendrite’s status code indicates failure.

This method returns True if the status code of the dendrite is not 200, which would mean the HTTP request was not successful.

Returns:

True if dendrite’s status code is not 200, False otherwise.

Return type:

bool

property is_timeout: bool#

Checks if the dendrite’s status code indicates a timeout.

This method returns True if the status code of the dendrite is 408, which is the HTTP status code for a request timeout.

Returns:

True if dendrite’s status code is 408, False otherwise.

Return type:

bool

property is_blacklist: bool#

Checks if the dendrite’s status code indicates a blacklisted request.

This method returns True if the status code of the dendrite is 403, which is the HTTP status code for a forbidden request.

Returns:

True if dendrite’s status code is 403, False otherwise.

Return type:

bool

property failed_verification: bool#

Checks if the dendrite’s status code indicates failed verification.

This method returns True if the status code of the dendrite is 401, which is the HTTP status code for unauthorized access.

Returns:

True if dendrite’s status code is 401, False otherwise.

Return type:

bool

classmethod _get_cached_model_json_schema()[source]#

Returns the JSON schema for the Synapse model.

This method returns a cached version of the JSON schema for the Synapse model. The schema is stored in the class variable _model_json_schema and is only generated once to improve performance.

Returns:

The JSON schema for the Synapse model.

Return type:

dict

get_required_fields()[source]#

Get the required fields from the model’s JSON schema.

to_headers()[source]#

Converts the state of a Synapse instance into a dictionary of HTTP headers.

This method is essential for packaging Synapse data for network transmission in the Bittensor framework, ensuring that each key aspect of the Synapse is represented in a format suitable for HTTP communication.

Process:

  1. Basic Information: It starts by including the name and timeout of the Synapse, which are fundamental for identifying the query and managing its lifespan on the network.

  2. Complex Objects: The method serializes the axon and dendrite objects, if present, into strings. This serialization is crucial for preserving the state and structure of these objects over the network.

  3. Encoding: Non-optional complex objects are serialized and encoded in base64, making them safe for HTTP transport.

  4. Size Metrics: The method calculates and adds the size of headers and the total object size, providing valuable information for network bandwidth management.

Example Usage:

synapse = Synapse(name="ExampleSynapse", timeout=30)
headers = synapse.to_headers()
# headers now contains a dictionary representing the Synapse instance
Returns:

A dictionary containing key-value pairs representing the Synapse’s properties, suitable for HTTP communication.

Return type:

dict

property body_hash: str#

Computes a SHA3-256 hash of the serialized body of the Synapse instance.

This hash is used to ensure the data integrity and security of the Synapse instance when it’s transmitted across the network. It is a crucial feature for verifying that the data received is the same as the data sent.

Process:

  1. Iterates over each required field as specified in required_hash_fields.

  2. Concatenates the string representation of these fields.

  3. Applies SHA3-256 hashing to the concatenated string to produce a unique fingerprint of the data.

Example:

synapse = Synapse(name="ExampleRoute", timeout=10)
hash_value = synapse.body_hash
# hash_value is the SHA3-256 hash of the serialized body of the Synapse instance
Returns:

The SHA3-256 hash as a hexadecimal string, providing a fingerprint of the Synapse instance’s data for integrity checks.

Return type:

str

classmethod parse_headers_to_inputs(headers)[source]#

Interprets and transforms a given dictionary of headers into a structured dictionary, facilitating the reconstruction of Synapse objects.

This method is essential for parsing network-transmitted data back into a Synapse instance, ensuring data consistency and integrity.

Process:

  1. Separates headers into categories based on prefixes (axon, dendrite, etc.).

  2. Decodes and deserializes input_obj headers into their original objects.

  3. Assigns simple fields directly from the headers to the input dictionary.

Example:

received_headers = {
    'bt_header_axon_address': '127.0.0.1',
    'bt_header_dendrite_port': '8080',
    # Other headers...
}
inputs = Synapse.parse_headers_to_inputs(received_headers)
# inputs now contains a structured representation of Synapse properties based on the headers

Note

This is handled automatically when calling Synapse.from_headers(headers)() and does not need to be called directly.

Parameters:

headers (dict) – The headers dictionary to parse.

Returns:

A structured dictionary representing the inputs for constructing a Synapse instance.

Return type:

dict

classmethod from_headers(headers)[source]#

Constructs a new Synapse instance from a given headers dictionary, enabling the re-creation of the Synapse’s state as it was prior to network transmission.

This method is a key part of the deserialization process in the Bittensor network, allowing nodes to accurately reconstruct Synapse objects from received data.

Example:

received_headers = {
    'bt_header_axon_address': '127.0.0.1',
    'bt_header_dendrite_port': '8080',
    # Other headers...
}
synapse = Synapse.from_headers(received_headers)
# synapse is a new Synapse instance reconstructed from the received headers
Parameters:

headers (dict) – The dictionary of headers containing serialized Synapse information.

Returns:

A new instance of Synapse, reconstructed from the parsed header information, replicating the original instance’s state.

Return type:

Synapse

class bittensor.StreamingSynapse(/, **data)[source]#

Bases: bittensor.Synapse, abc.ABC

The StreamingSynapse() class is designed to be subclassed for handling streaming responses in the Bittensor network. It provides abstract methods that must be implemented by the subclass to deserialize, process streaming responses, and extract JSON data. It also includes a method to create a streaming response object.

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

Parameters:

data (Any)

model_config#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class BTStreamingResponse(model, *, synapse=None, **kwargs)[source]#

Bases: starlette.responses.StreamingResponse

BTStreamingResponse() is a specialized subclass of the Starlette StreamingResponse designed to handle the streaming of tokens within the Bittensor network. It is used internally by the StreamingSynapse class to manage the response streaming process, including sending headers and calling the token streamer provided by the subclass.

This class is not intended to be directly instantiated or modified by developers subclassing StreamingSynapse. Instead, it is used by the create_streaming_response() method to create a response object based on the token streamer provided by the subclass.

Initializes the BTStreamingResponse with the given token streamer model.

Parameters:
  • model (BTStreamingResponseModel) – A BTStreamingResponseModel instance containing the token streamer callable, which is responsible for generating the content of the response.

  • synapse (Optional[StreamingSynapse]) – The response Synapse to be used to update the response headers etc.

  • **kwargs – Additional keyword arguments passed to the parent StreamingResponse class.

token_streamer#
synapse#
async stream_response(send)[source]#

Asynchronously streams the response by sending headers and calling the token streamer.

This method is responsible for initiating the response by sending the appropriate headers, including the content type for event-streaming. It then calls the token streamer to generate the content and sends the response body to the client.

Parameters:

send (starlette.types.Send) – A callable to send the response, provided by the ASGI server.

async __call__(scope, receive, send)[source]#

Asynchronously calls the stream_response method, allowing the BTStreamingResponse object to be used as an ASGI application.

This method is part of the ASGI interface and is called by the ASGI server to handle the request and send the response. It delegates to the stream_response() method to perform the actual streaming process.

Parameters:
  • scope (starlette.types.Scope) – The scope of the request, containing information about the client, server, and request itself.

  • receive (starlette.types.Receive) – A callable to receive the request, provided by the ASGI server.

  • send (starlette.types.Send) – A callable to send the response, provided by the ASGI server.

abstract process_streaming_response(response)[source]#
Async:

Parameters:

response (aiohttp.ClientResponse)

Abstract method that must be implemented by the subclass. This method should provide logic to handle the streaming response, such as parsing and accumulating data. It is called as the response is being streamed from the network, and should be implemented to handle the specific streaming data format and requirements of the subclass.

Parameters:

response (aiohttp.ClientResponse) – The response object to be processed, typically containing chunks of data.

abstract extract_response_json(response)[source]#

Abstract method that must be implemented by the subclass. This method should provide logic to extract JSON data from the response, including headers and content. It is called after the response has been processed and is responsible for retrieving structured data that can be used by the application.

Parameters:

response (aiohttp.ClientResponse) – The response object from which to extract JSON data.

Return type:

dict

create_streaming_response(token_streamer)[source]#

Creates a streaming response using the provided token streamer. This method can be used by the subclass to create a response object that can be sent back to the client. The token streamer should be implemented to generate the content of the response according to the specific requirements of the subclass.

Parameters:

token_streamer (Callable[[starlette.types.Send], Awaitable[None]]) – A callable that takes a send function and returns an awaitable. It’s responsible for generating the content of the response.

Returns:

The streaming response object, ready to be sent to the client.

Return type:

BTStreamingResponse

class bittensor.tensor[source]#
class bittensor.Tensor(/, **data)[source]#

Bases: pydantic.BaseModel

Represents a Tensor object.

Parameters:
  • buffer (Optional[str]) – Tensor buffer data.

  • dtype (str) – Tensor data type.

  • shape (List[int]) – Tensor shape.

  • data (Any)

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

model_config#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

tensor()[source]#
Return type:

Union[numpy.ndarray, bittensor.utils.registration.torch.Tensor]

tolist()[source]#
Return type:

List[object]

numpy()[source]#
Return type:

numpy.ndarray

deserialize()[source]#

Deserializes the Tensor object.

Returns:

The deserialized tensor object.

Return type:

np.array or torch.Tensor

Raises:

Exception – If the deserialization process encounters an error.

static serialize(tensor_)[source]#

Serializes the given tensor.

Parameters:
  • tensor (np.array or torch.Tensor) – The tensor to serialize.

  • tensor_ (Union[numpy.ndarray, bittensor.utils.registration.torch.Tensor])

Returns:

The serialized tensor.

Return type:

Tensor

Raises:

Exception – If the serialization process encounters an error.

buffer: str | None#
dtype: str#
shape: List[int]#
_extract_shape#
_extract_dtype#
class bittensor.axon(wallet=None, config=None, port=None, ip=None, external_ip=None, external_port=None, max_workers=None)[source]#

The axon class in Bittensor is a fundamental component that serves as the server-side interface for a neuron within the Bittensor network.

This class is responsible for managing incoming requests from other neurons and implements various mechanisms to ensure efficient and secure network interactions.

An axon relies on a FastAPI router to create endpoints for different message types. These endpoints are crucial for handling various request types that a neuron might receive. The class is designed to be flexible and customizable, allowing users to specify custom rules for forwarding, blacklisting, prioritizing, and verifying incoming requests. The class also includes internal mechanisms to manage a thread pool, supporting concurrent handling of requests with defined priority levels.

Methods in this class are equipped to deal with incoming requests from various scenarios in the network and serve as the server face for a neuron. It accepts multiple arguments, like wallet, configuration parameters, ip address, server binding port, external ip, external port and max workers. Key methods involve managing and operating the FastAPI application router, including the attachment and operation of endpoints.

Key Features:

  • FastAPI router integration for endpoint creation and management.

  • Customizable request handling including forwarding, blacklisting, and prioritization.

  • Verification of incoming requests against custom-defined functions.

  • Thread pool management for concurrent request handling.

  • Command-line argument support for user-friendly program interaction.

Example Usage:

import bittensor
# Define your custom synapse class
class MySyanpse( bittensor.Synapse ):
    input: int = 1
    output: int = None

# Define a custom request forwarding function using your synapse class
def forward( synapse: MySyanpse ) -> MySyanpse:
    # Apply custom logic to synapse and return it
    synapse.output = 2
    return synapse

# Define a custom request verification function
def verify_my_synapse( synapse: MySyanpse ):
    # Apply custom verification logic to synapse
    # Optionally raise Exception
    assert synapse.input == 1
    ...

# Define a custom request blacklist fucntion
def blacklist_my_synapse( synapse: MySyanpse ) -> bool:
    # Apply custom blacklist
    return False ( if non blacklisted ) or True ( if blacklisted )

# Define a custom request priority fucntion
def prioritize_my_synape( synapse: MySyanpse ) -> float:
    # Apply custom priority
    return 1.0

# Initialize Axon object with a custom configuration
my_axon = bittensor.axon(
    config=my_config,
    wallet=my_wallet,
    port=9090,
    ip="192.0.2.0",
    external_ip="203.0.113.0",
    external_port=7070
)

# Attach the endpoint with the specified verification and forward functions.
my_axon.attach(
    forward_fn = forward_my_synapse,
    verify_fn = verify_my_synapse,
    blacklist_fn = blacklist_my_synapse,
    priority_fn = prioritize_my_synape
)

# Serve and start your axon.
my_axon.serve(
    netuid = ...
    subtensor = ...
).start()

# If you have multiple forwarding functions, you can chain attach them.
my_axon.attach(
    forward_fn = forward_my_synapse,
    verify_fn = verify_my_synapse,
    blacklist_fn = blacklist_my_synapse,
    priority_fn = prioritize_my_synape
).attach(
    forward_fn = forward_my_synapse_2,
    verify_fn = verify_my_synapse_2,
    blacklist_fn = blacklist_my_synapse_2,
    priority_fn = prioritize_my_synape_2
).serve(
    netuid = ...
    subtensor = ...
).start()
Parameters:
  • wallet (bittensor.wallet, optional) – Wallet with hotkey and coldkeypub.

  • config (bittensor.config, optional) – Configuration parameters for the axon.

  • port (int, optional) – Port for server binding.

  • ip (str, optional) – Binding IP address.

  • external_ip (str, optional) – External IP address to broadcast.

  • external_port (int, optional) – External port to broadcast.

  • max_workers (int, optional) – Number of active threads for request handling.

Returns:

An instance of the axon class configured as per the provided arguments.

Return type:

bittensor.axon

Note

This class is a core part of Bittensor’s decentralized network for machine intelligence, allowing neurons to communicate effectively and securely.

Importance and Functionality
Endpoint Registration

This method dynamically registers API endpoints based on the Synapse used, allowing the Axon to respond to specific types of requests and synapses.

Customization of Request Handling

By attaching different functions, the Axon can customize how it handles, verifies, prioritizes, and potentially blocks incoming requests, making it adaptable to various network scenarios.

Security and Efficiency

The method contributes to both the security (via verification and blacklisting) and efficiency (via prioritization) of request handling, which are crucial in a decentralized network environment.

Flexibility

The ability to define custom functions for different aspects of request handling provides great flexibility, allowing the Axon to be tailored to specific needs and use cases within the Bittensor network.

Error Handling and Validation

The method ensures that the attached functions meet the required signatures, providing error handling to prevent runtime issues.

Creates a new bittensor.Axon object from passed arguments. :param config: bittensor.axon.config() :type config: Optional[bittensor.config], optional :param wallet: bittensor wallet with hotkey and coldkeypub. :type wallet: Optional[bittensor.wallet], optional :param port: Binding port. :type port: Optional[int], optional :param ip: Binding ip. :type ip: Optional[str], optional :param external_ip: The external ip of the server to broadcast to the network. :type external_ip: Optional[str], optional :param external_port: The external port of the server to broadcast to the network. :type external_port: Optional[int], optional :param max_workers: Used to create the threadpool if not passed, specifies the number of active threads servicing requests. :type max_workers: Optional[int], optional

config[source]#
ip#
port#
external_ip#
external_port#
max_workers#
wallet#
uuid#
full_address#
started = False#
thread_pool#
nonces: Dict[str, int]#
forward_class_types: Dict[str, List[inspect.Signature]]#
blacklist_fns: Dict[str, Callable | None]#
priority_fns: Dict[str, Callable | None]#
forward_fns: Dict[str, Callable | None]#
verify_fns: Dict[str, Callable | None]#
app#
log_level#
fast_config#
fast_server#
router#
middleware_cls#
info()[source]#

Returns the axon info object associated with this axon.

Return type:

bittensor.AxonInfo

attach(forward_fn, blacklist_fn=None, priority_fn=None, verify_fn=None)[source]#

Attaches custom functions to the Axon server for handling incoming requests. This method enables the Axon to define specific behaviors for request forwarding, verification, blacklisting, and prioritization, thereby customizing its interaction within the Bittensor network.

Registers an API endpoint to the FastAPI application router. It uses the name of the first argument of the forward_fn() function as the endpoint name.

The attach method in the Bittensor framework’s axon class is a crucial function for registering API endpoints to the Axon’s FastAPI application router. This method allows the Axon server to define how it handles incoming requests by attaching functions for forwarding, verifying, blacklisting, and prioritizing requests. It’s a key part of customizing the server’s behavior and ensuring efficient and secure handling of requests within the Bittensor network.

Parameters:
  • forward_fn (Callable) – Function to be called when the API endpoint is accessed. It should have at least one argument.

  • blacklist_fn (Callable, optional) – Function to filter out undesired requests. It should take the same arguments as forward_fn() and return a boolean value. Defaults to None, meaning no blacklist filter will be used.

  • priority_fn (Callable, optional) – Function to rank requests based on their priority. It should take the same arguments as forward_fn() and return a numerical value representing the request’s priority. Defaults to None, meaning no priority sorting will be applied.

  • verify_fn (Callable, optional) – Function to verify requests. It should take the same arguments as forward_fn() and return a boolean value. If None, self.default_verify() function will be used.

Return type:

bittensor.axon

Note

The methods forward_fn(), blacklist_fn(), priority_fn(), and verify_fn() should be designed to receive the same parameters.

Raises:
  • AssertionError – If forward_fn() does not have the signature: forward( synapse: YourSynapse ) -> synapse.

  • AssertionError – If blacklist_fn() does not have the signature: blacklist( synapse: YourSynapse ) -> bool.

  • AssertionError – If priority_fn() does not have the signature: priority( synapse: YourSynapse ) -> float.

  • AssertionError – If verify_fn() does not have the signature: verify( synapse: YourSynapse ) -> None.

Returns:

Returns the instance of the AxonServer class for potential method chaining.

Return type:

self

Parameters:
  • forward_fn (Callable)

  • blacklist_fn (Optional[Callable])

  • priority_fn (Optional[Callable])

  • verify_fn (Optional[Callable])

Example Usage:

def forward_custom(synapse: MyCustomSynapse) -> MyCustomSynapse:
    # Custom logic for processing the request
    return synapse

def blacklist_custom(synapse: MyCustomSynapse) -> Tuple[bool, str]:
    return True, "Allowed!"

def priority_custom(synapse: MyCustomSynapse) -> float:
    return 1.0

def verify_custom(synapse: MyCustomSynapse):
    # Custom logic for verifying the request
    pass

my_axon = bittensor.axon(...)
my_axon.attach(forward_fn=forward_custom, verify_fn=verify_custom)

Note

The attach() method is fundamental in setting up the Axon server’s request handling capabilities, enabling it to participate effectively and securely in the Bittensor network. The flexibility offered by this method allows developers to tailor the Axon’s behavior to specific requirements and use cases.

classmethod help()[source]#

Prints the help text (list of command-line arguments and their descriptions) to stdout.

classmethod add_args(parser, prefix=None)[source]#

Adds AxonServer-specific command-line arguments to the argument parser.

Parameters:
  • parser (argparse.ArgumentParser) – Argument parser to which the arguments will be added.

  • prefix (str, optional) – Prefix to add to the argument names. Defaults to None.

Note

Environment variables are used to define default values for the arguments.

async verify_body_integrity(request)[source]#

The verify_body_integrity method in the Bittensor framework is a key security function within the Axon server’s middleware. It is responsible for ensuring the integrity of the body of incoming HTTP requests.

It asynchronously verifies the integrity of the body of a request by comparing the hash of required fields with the corresponding hashes provided in the request headers. This method is critical for ensuring that the incoming request payload has not been altered or tampered with during transmission, establishing a level of trust and security between the sender and receiver in the network.

Parameters:

request (Request) – The incoming FastAPI request object containing both headers and the request body.

Returns:

Returns the parsed body of the request as a dictionary if all the hash comparisons match,

indicating that the body is intact and has not been tampered with.

Return type:

dict

Raises:

JSONResponse – Raises a JSONResponse with a 400 status code if any of the hash comparisons fail, indicating a potential integrity issue with the incoming request payload. The response includes the detailed error message specifying which field has a hash mismatch.

This method performs several key functions:

  1. Decoding and loading the request body for inspection.

  2. Gathering required field names for hash comparison from the Axon configuration.

  3. Loading and parsing the request body into a dictionary.

  4. Reconstructing the Synapse object and recomputing the hash for verification and logging.

  5. Comparing the recomputed hash with the hash provided in the request headers for verification.

Note

The integrity verification is an essential step in ensuring the security of the data exchange within the Bittensor network. It helps prevent tampering and manipulation of data during transit, thereby maintaining the reliability and trust in the network communication.

classmethod check_config(config)[source]#

This method checks the configuration for the axon’s port and wallet.

Parameters:

config (bittensor.config) – The config object holding axon settings.

Raises:

AssertionError – If the axon or external ports are not in range [1024, 65535]

to_string()[source]#

Provides a human-readable representation of the AxonInfo for this Axon.

__str__()[source]#

Provides a human-readable representation of the Axon instance.

Return type:

str

__repr__()[source]#

Provides a machine-readable (unambiguous) representation of the Axon instance. It is made identical to __str__ in this case.

Return type:

str

__del__()[source]#

This magic method is called when the Axon object is about to be destroyed. It ensures that the Axon server shuts down properly.

start()[source]#

Starts the Axon server and its underlying FastAPI server thread, transitioning the state of the Axon instance to started. This method initiates the server’s ability to accept and process incoming network requests, making it an active participant in the Bittensor network.

The start method triggers the FastAPI server associated with the Axon to begin listening for incoming requests. It is a crucial step in making the neuron represented by this Axon operational within the Bittensor network.

Returns:

The Axon instance in the ‘started’ state.

Return type:

bittensor.axon

Example:

my_axon = bittensor.axon(...)
... # setup axon, attach functions, etc.
my_axon.start()  # Starts the axon server

Note

After invoking this method, the Axon is ready to handle requests as per its configured endpoints and custom logic.

stop()[source]#

Stops the Axon server and its underlying GRPC server thread, transitioning the state of the Axon instance to stopped. This method ceases the server’s ability to accept new network requests, effectively removing the neuron’s server-side presence in the Bittensor network.

By stopping the FastAPI server, the Axon ceases to listen for incoming requests, and any existing connections are gracefully terminated. This function is typically used when the neuron is being shut down or needs to temporarily go offline.

Returns:

The Axon instance in the ‘stopped’ state.

Return type:

bittensor.axon

Example:

my_axon = bittensor.axon(...)
my_axon.start()
...
my_axon.stop()  # Stops the axon server

Note

It is advisable to ensure that all ongoing processes or requests are completed or properly handled before invoking this method.

serve(netuid, subtensor=None)[source]#

Serves the Axon on the specified subtensor connection using the configured wallet. This method registers the Axon with a specific subnet within the Bittensor network, identified by the netuid. It links the Axon to the broader network, allowing it to participate in the decentralized exchange of information.

Parameters:
  • netuid (int) – The unique identifier of the subnet to register on. This ID is essential for the Axon to correctly position itself within the Bittensor network topology.

  • subtensor (bittensor.subtensor, optional) – The subtensor connection to use for serving. If not provided, a new connection is established based on default configurations.

Returns:

The Axon instance that is now actively serving on the specified subtensor.

Return type:

bittensor.axon

Example:

my_axon = bittensor.axon(...)
subtensor = bt.subtensor(network="local") # Local by default
my_axon.serve(netuid=1, subtensor=subtensor)  # Serves the axon on subnet with netuid 1

Note

The serve method is crucial for integrating the Axon into the Bittensor network, allowing it to start receiving and processing requests from other neurons.

async default_verify(synapse)[source]#

This method is used to verify the authenticity of a received message using a digital signature.

It ensures that the message was not tampered with and was sent by the expected sender.

The default_verify() method in the Bittensor framework is a critical security function within the Axon server. It is designed to authenticate incoming messages by verifying their digital signatures. This verification ensures the integrity of the message and confirms that it was indeed sent by the claimed sender. The method plays a pivotal role in maintaining the trustworthiness and reliability of the communication within the Bittensor network.

Key Features
Security Assurance

The default_verify method is crucial for ensuring the security of the Bittensor network. By verifying digital signatures, it guards against unauthorized access and data manipulation.

Preventing Replay Attacks

The method checks for increasing nonce values, which is a vital step in preventing replay attacks. A replay attack involves an adversary reusing or delaying the transmission of a valid data transmission to deceive the receiver. The first time a nonce is seen, it is checked for freshness by ensuring it is within an acceptable delta time range.

Authenticity and Integrity Checks

By verifying that the message’s digital signature matches its content, the method ensures the message’s authenticity (it comes from the claimed sender) and integrity (it hasn’t been altered during transmission).

Trust in Communication

This method fosters trust in the network communication. Neurons (nodes in the Bittensor network) can confidently interact, knowing that the messages they receive are genuine and have not been tampered with.

Cryptographic Techniques

The method’s reliance on asymmetric encryption techniques is a cornerstone of modern cryptographic security, ensuring that only entities with the correct cryptographic keys can participate in secure communication.

Parameters:

synapse (bittensor.Synapse) – bittensor.Synapse bittensor request synapse.

Raises:
  • Exception – If the receiver_hotkey doesn’t match with self.receiver_hotkey.

  • Exception – If the nonce is not larger than the previous nonce for the same endpoint key.

  • Exception – If the signature verification fails.

After successful verification, the nonce for the given endpoint key is updated.

Note

The verification process assumes the use of an asymmetric encryption algorithm, where the sender signs the message with their private key and the receiver verifies the signature using the sender’s public key.

class bittensor.dendrite(wallet=None)[source]#

Bases: DendriteMixin, BaseModel

The Dendrite class represents the abstracted implementation of a network client module.

In the brain analogy, dendrites receive signals from other neurons (in this case, network servers or axons), and the Dendrite class here is designed to send requests to those endpoint to recieve inputs.

This class includes a wallet or keypair used for signing messages, and methods for making HTTP requests to the network servers. It also provides functionalities such as logging network requests and processing server responses.

Parameters:
  • keypair – The wallet or keypair used for signing messages.

  • external_ip (str) – The external IP address of the local system.

  • synapse_history (list) – A list of Synapse objects representing the historical responses.

  • wallet (Optional[Union[bittensor.wallet, bittensor.Keypair]])

__str__()#

Returns a string representation of the Dendrite object.

Return type:

str

__repr__()#

Returns a string representation of the Dendrite object, acting as a fallback for __str__().

Return type:

str

query(self, *args, **kwargs) bittensor.Synapse | List[bittensor.Synapse]#

Makes synchronous requests to one or multiple target Axons and returns responses.

Return type:

List[Union[AsyncGenerator[Any, Any], bittensor.Synapse, bittensor.StreamingSynapse]]

forward(self, axons, synapse=bittensor.Synapse(), timeout=12, deserialize=True, run_async=True, streaming=False) bittensor.Synapse#

Asynchronously sends requests to one or multiple Axons and collates their responses.

Parameters:
Return type:

List[Union[AsyncGenerator[Any, Any], bittensor.Synapse, bittensor.StreamingSynapse]]

call(self, target_axon, synapse=bittensor.Synapse(), timeout=12.0, deserialize=True) bittensor.Synapse#

Asynchronously sends a request to a specified Axon and processes the response.

call_stream(self, target_axon, synapse=bittensor.Synapse(), timeout=12.0, deserialize=True) AsyncGenerator[bittensor.Synapse, None]#

Sends a request to a specified Axon and yields an AsyncGenerator that contains streaming response chunks before finally yielding the filled Synapse as the final element.

Parameters:
Return type:

AsyncGenerator[Any, Any]

preprocess_synapse_for_request(self, target_axon_info, synapse, timeout=12.0) bittensor.Synapse#

Preprocesses the synapse for making a request, including building headers and signing.

Parameters:
Return type:

bittensor.Synapse

process_server_response(self, server_response, json_response, local_synapse)#

Processes the server response, updates the local synapse state, and merges headers.

Parameters:
close_session(self)#

Synchronously closes the internal aiohttp client session.

aclose_session(self)#

Asynchronously closes the internal aiohttp client session.

Note

When working with async aiohttp client sessions, it is recommended to use a context manager.

Example with a context manager:

>>> aysnc with dendrite(wallet = bittensor.wallet()) as d:
>>>     print(d)
>>>     d( <axon> ) # ping axon
>>>     d( [<axons>] ) # ping multiple
>>>     d( bittensor.axon(), bittensor.Synapse )

However, you are able to safely call dendrite.query() without a context manager in a synchronous setting.

Example without a context manager:

>>> d = dendrite(wallet = bittensor.wallet() )
>>> print(d)
>>> d( <axon> ) # ping axon
>>> d( [<axons>] ) # ping multiple
>>> d( bittensor.axon(), bittensor.Synapse )

Initializes the Dendrite object, setting up essential properties.

Parameters:

wallet (Optional[Union['bittensor.wallet', 'bittensor.keypair']], optional) – The user’s wallet or keypair used for signing messages. Defaults to None, in which case a new bittensor.wallet().hotkey() is generated and used.

class bittensor.MockKeyfile(path)[source]#

Bases: bittensor.keyfile

Defines an interface to a mocked keyfile object (nothing is created on device) keypair is treated as non encrypted and the data is just the string version.

Parameters:

path (str)

_mock_keypair#
_mock_data#
__str__()[source]#
__repr__()[source]#
property keypair: bittensor.Keypair#

Returns the keypair from path, decrypts data if the file is encrypted.

Returns:

The keypair stored under the path.

Return type:

keypair (bittensor.Keypair)

Raises:

KeyFileError – Raised if the file does not exist, is not readable, writable, corrupted, or if the password is incorrect.

property data: bytes#

Returns the keyfile data under path.

Returns:

The keyfile data stored under the path.

Return type:

keyfile_data (bytes)

Raises:

KeyFileError – Raised if the file does not exist, is not readable, or writable.

property keyfile_data: bytes#

Returns the keyfile data under path.

Returns:

The keyfile data stored under the path.

Return type:

keyfile_data (bytes)

Raises:

KeyFileError – Raised if the file does not exist, is not readable, or writable.

set_keypair(keypair, encrypt=True, overwrite=False, password=None)[source]#

Writes the keypair to the file and optionally encrypts data.

Parameters:
  • keypair (bittensor.Keypair) – The keypair to store under the path.

  • encrypt (bool, optional) – If True, encrypts the file under the path. Default is True.

  • overwrite (bool, optional) – If True, forces overwrite of the current file. Default is False.

  • password (str, optional) – The password used to encrypt the file. If None, asks for user input.

Raises:

KeyFileError – Raised if the file does not exist, is not readable, writable, or if the password is incorrect.

get_keypair(password=None)[source]#

Returns the keypair from the path, decrypts data if the file is encrypted.

Parameters:

password (str, optional) – The password used to decrypt the file. If None, asks for user input.

Returns:

The keypair stored under the path.

Return type:

keypair (bittensor.Keypair)

Raises:

KeyFileError – Raised if the file does not exist, is not readable, writable, corrupted, or if the password is incorrect.

make_dirs()[source]#

Creates directories for the path if they do not exist.

exists_on_device()[source]#

Returns True if the file exists on the device.

Returns:

True if the file is on the device.

Return type:

on_device (bool)

is_readable()[source]#

Returns True if the file under path is readable.

Returns:

True if the file is readable.

Return type:

readable (bool)

is_writable()[source]#

Returns True if the file under path is writable.

Returns:

True if the file is writable.

Return type:

writable (bool)

is_encrypted()[source]#

Returns True if the file under path is encrypted.

Returns:

True if the file is encrypted.

Return type:

encrypted (bool)

encrypt(password=None)[source]#

Encrypts the file under the path.

Parameters:

password (str, optional) – The password for encryption. If None, asks for user input.

Raises:

KeyFileError – Raised if the file does not exist, is not readable, or writable.

decrypt(password=None)[source]#

Decrypts the file under the path.

Parameters:

password (str, optional) – The password for decryption. If None, asks for user input.

Raises:

KeyFileError – Raised if the file does not exist, is not readable, writable, corrupted, or if the password is incorrect.

class bittensor.MockSubtensor(*args, **kwargs)[source]#

Bases: bittensor.subtensor.Subtensor

A Mock Subtensor class for running tests. This should mock only methods that make queries to the chain. e.g. We mock Subtensor.query_subtensor instead of all query methods.

This class will also store a local (mock) state of the chain.

Initializes a Subtensor interface for interacting with the Bittensor blockchain.

Note

Currently subtensor defaults to the finney network. This will change in a future release.

We strongly encourage users to run their own local subtensor node whenever possible. This increases decentralization and resilience of the network. In a future release, local subtensor will become the default and the fallback to finney removed. Please plan ahead for this change. We will provide detailed instructions on how to run a local subtensor node in the documentation in a subsequent release.

Parameters:
  • network (str, optional) – The network name to connect to (e.g., finney, local). This can also be the chain endpoint (e.g., wss://entrypoint-finney.opentensor.ai:443) and will be correctly parsed into the network and chain endpoint. If not specified, defaults to the main Bittensor network.

  • config (bittensor.config, optional) – Configuration object for the subtensor. If not provided, a default configuration is used.

  • _mock (bool, optional) – If set to True, uses a mocked connection for testing purposes.

This initialization sets up the connection to the specified Bittensor network, allowing for various blockchain operations such as neuron registration, stake management, and setting weights.

chain_state: MockChainState#
block_number: int#
classmethod reset()[source]#
Return type:

None

setup()[source]#
Return type:

None

__dict__#
get_block_hash(block_id)[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.

Parameters:

block_id (int) – The block number for which the hash is to be retrieved.

Returns:

The cryptographic hash of the specified block.

Return type:

str

The block hash is a fundamental aspect of blockchain technology, providing a secure reference to each block’s data. It is crucial for verifying transactions, ensuring data consistency, and maintaining the trustworthiness of the blockchain.

create_subnet(netuid)[source]#
Parameters:

netuid (int)

Return type:

None

set_difficulty(netuid, difficulty)[source]#
Parameters:
  • netuid (int)

  • difficulty (int)

Return type:

None

_register_neuron(netuid, hotkey, coldkey)[source]#
Parameters:
Return type:

int

static _convert_to_balance(balance)[source]#
Parameters:

balance (Union[bittensor.utils.balance.Balance, float, int])

Return type:

bittensor.utils.balance.Balance

force_register_neuron(netuid, hotkey, coldkey, stake=Balance(0), balance=Balance(0))[source]#

Force register a neuron on the mock chain, returning the UID.

Parameters:
Return type:

int

force_set_balance(ss58_address, balance=Balance(0))[source]#
Returns:

(success, err_msg)

Return type:

Tuple[bool, Optional[str]]

Parameters:
sudo_force_set_balance#
do_block_step()[source]#
Return type:

None

_handle_type_default(name, params)[source]#
Parameters:
Return type:

object

commit(wallet, netuid, data)[source]#

Commits arbitrary data to the Bittensor network by publishing metadata.

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

Return type:

None

get_commitment(netuid, uid, block=None)[source]#

Retrieves the on-chain commitment for a specific neuron in the Bittensor network.

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.

Returns:

The commitment data as a string.

Return type:

str

query_subtensor(name, block=None, params=[])[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.

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

Returns:

An object containing the requested data.

Return type:

query_response (ScaleType)

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.

query_map_subtensor(name, block=None, params=[])[source]#

Note: Double map requires one param

Parameters:
  • name (str)

  • block (Optional[int])

  • params (Optional[List[object]])

Return type:

Optional[MockMapResult]

query_constant(module_name, constant_name, block=None)[source]#

Retrieves a constant from the specified module on the Bittensor blockchain. This function is used to access fixed parameters or values defined within the blockchain’s modules, which are essential for understanding the network’s configuration and rules.

Parameters:
  • module_name (str) – The name of the module containing the constant.

  • constant_name (str) – The name of the constant to retrieve.

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

Returns:

The value of the constant if found, None otherwise.

Return type:

Optional[ScaleType]

Constants queried through this function can include critical network parameters such as inflation rates, consensus rules, or validation thresholds, providing a deeper understanding of the Bittensor network’s operational parameters.

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.

Returns:

The current chain block number.

Return type:

int

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.

get_balance(address, block=None)[source]#

Retrieves the token balance of a specific address within the Bittensor network. This function queries the blockchain to determine the amount of Tao held by a given account.

Parameters:
  • address (str) – The Substrate address in ss58 format.

  • block (int, optional) – The blockchain block number at which to perform the query.

Returns:

The account balance at the specified block, represented as a Balance object.

Return type:

Balance

This function is important for monitoring account holdings and managing financial transactions within the Bittensor ecosystem. It helps in assessing the economic status and capacity of network participants.

get_balances(block=None)[source]#

Retrieves the token balances of all accounts within the Bittensor network as of a specific blockchain block. This function provides a comprehensive view of the token distribution among different accounts.

Parameters:

block (int, optional) – The blockchain block number at which to perform the query.

Returns:

A dictionary mapping each account’s ss58 address to its balance.

Return type:

Dict[str, Balance]

This function is valuable for analyzing the overall economic landscape of the Bittensor network, including the distribution of financial resources and the financial status of network participants.

neuron_for_uid(uid, netuid, block=None)[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 (int) – The unique identifier of the neuron.

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

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

Returns:

Detailed information about the neuron if found, None otherwise.

Return type:

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.

neurons(netuid, block=None)[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], optional) – The blockchain block number for the query.

Returns:

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

Return type:

List[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.

static _get_most_recent_storage(storage, block_number=None)[source]#
Parameters:
  • storage (Dict[BlockNumber, Any])

  • block_number (Optional[int])

Return type:

Any

_get_axon_info(netuid, hotkey, block=None)[source]#
Parameters:
  • netuid (int)

  • hotkey (str)

  • block (Optional[int])

Return type:

AxonInfoDict

_get_prometheus_info(netuid, hotkey, block=None)[source]#
Parameters:
  • netuid (int)

  • hotkey (str)

  • block (Optional[int])

Return type:

PrometheusInfoDict

_neuron_subnet_exists(uid, netuid, block=None)[source]#
Parameters:
  • uid (int)

  • netuid (int)

  • block (Optional[int])

Return type:

Optional[bittensor.chain_data.NeuronInfo]

neuron_for_uid_lite(uid, netuid, block=None)[source]#

Retrieves a lightweight version of information about a neuron in a specific subnet, identified by its UID. The ‘lite’ version focuses on essential attributes such as stake and network activity.

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

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

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

Returns:

A simplified version of neuron information if found, None otherwise.

Return type:

Optional[NeuronInfoLite]

This function is useful for quick and efficient analyses of neuron status and activities within a subnet without the need for comprehensive data retrieval.

neurons_lite(netuid, block=None)[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], optional) – The blockchain block number for the query.

Returns:

A list of simplified neuron information for the subnet.

Return type:

List[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.

_do_delegation(wallet, delegate_ss58, amount, wait_for_inclusion=True, wait_for_finalization=False)[source]#

Delegates a specified amount of stake to a delegate’s hotkey.

This method sends a transaction to add stake to a delegate’s hotkey and retries the call up to three times with exponential backoff in case of failures.

Parameters:
  • wallet (bittensor.wallet) – The wallet from which the stake will be delegated.

  • delegate_ss58 (str) – The SS58 address of the delegate’s hotkey.

  • amount (Balance) – The amount of stake to be delegated.

  • wait_for_inclusion (bool, optional) – Whether to wait for the transaction to be included in a block. Default is True.

  • wait_for_finalization (bool, optional) – Whether to wait for the transaction to be finalized. Default is False.

Returns:

True if the delegation is successful, False otherwise.

Return type:

bool

_do_undelegation(wallet, delegate_ss58, amount, wait_for_inclusion=True, wait_for_finalization=False)[source]#

Removes a specified amount of stake from a delegate’s hotkey.

This method sends a transaction to remove stake from a delegate’s hotkey and retries the call up to three times with exponential backoff in case of failures.

Parameters:
  • wallet (bittensor.wallet) – The wallet from which the stake will be removed.

  • delegate_ss58 (str) – The SS58 address of the delegate’s hotkey.

  • amount (Balance) – The amount of stake to be removed.

  • wait_for_inclusion (bool, optional) – Whether to wait for the transaction to be included in a block. Default is True.

  • wait_for_finalization (bool, optional) – Whether to wait for the transaction to be finalized. Default is False.

Returns:

True if the undelegation is successful, False otherwise.

Return type:

bool

_do_nominate(wallet, wait_for_inclusion=True, wait_for_finalization=False)[source]#

Nominates the wallet’s hotkey to become a delegate.

This method sends a transaction to nominate the wallet’s hotkey to become a delegate and retries the call up to three times with exponential backoff in case of failures.

Parameters:
  • wallet (bittensor.wallet) – The wallet whose hotkey will be nominated.

  • wait_for_inclusion (bool, optional) – Whether to wait for the transaction to be included in a block. Default is True.

  • wait_for_finalization (bool, optional) – Whether to wait for the transaction to be finalized. Default is False.

Returns:

True if the nomination is successful, False otherwise.

Return type:

bool

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) – The wallet from which the transfer is initiated.

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

  • value (Union[Balance, float, int]) – 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:

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.

_do_transfer(wallet, dest, transfer_balance, wait_for_inclusion=True, wait_for_finalization=False)[source]#

Sends a transfer extrinsic to the chain.

Parameters:
  • wallet (bittensor.wallet()) – Wallet object.

  • dest (str) – Destination public key address.

  • transfer_balance (Balance()) – Amount to transfer.

  • wait_for_inclusion (bool) – If true, waits for inclusion.

  • wait_for_finalization (bool) – If true, waits for finalization.

Returns:

True if transfer was successful. block_hash (str): Block hash of the transfer. On success and if wait_for_ finalization/inclusion is

True.

error (str): Error message if transfer failed.

Return type:

success (bool)

_do_pow_register(netuid, wallet, pow_result, wait_for_inclusion=False, wait_for_finalization=True)[source]#

Sends a (POW) register extrinsic to the chain.

Parameters:
  • netuid (int) – The subnet to register on.

  • wallet (bittensor.wallet) – The wallet to register.

  • pow_result (POWSolution) – The PoW result to register.

  • wait_for_inclusion (bool) – If True, waits for the extrinsic to be included in a block. Default to False.

  • wait_for_finalization (bool) – If True, waits for the extrinsic to be finalized. Default to True.

Returns:

True if the extrinsic was included in a block. error (Optional[str]): None on success or not waiting for inclusion/finalization, otherwise the error

message.

Return type:

success (bool)

_do_burned_register(netuid, wallet, wait_for_inclusion=False, wait_for_finalization=True)[source]#

Performs a burned register extrinsic call to the Subtensor chain.

This method sends a registration transaction to the Subtensor blockchain using the burned register mechanism. It retries the call up to three times with exponential backoff in case of failures.

Parameters:
  • netuid (int) – The network unique identifier to register on.

  • wallet (bittensor.wallet) – The wallet to be registered.

  • wait_for_inclusion (bool) – Whether to wait for the transaction to be included in a block. Default is False.

  • wait_for_finalization (bool) – Whether to wait for the transaction to be finalized. Default is True.

Returns:

A tuple containing a boolean indicating success or failure, and an optional error message.

Return type:

Tuple[bool, Optional[str]]

_do_stake(wallet, hotkey_ss58, amount, wait_for_inclusion=True, wait_for_finalization=False)[source]#

Sends a stake extrinsic to the chain.

Parameters:
  • wallet (bittensor.wallet()) – Wallet object that can sign the extrinsic.

  • hotkey_ss58 (str) – Hotkey ss58 address to stake to.

  • amount (Balance()) – Amount to stake.

  • wait_for_inclusion (bool) – If true, waits for inclusion before returning.

  • wait_for_finalization (bool) – If true, waits for finalization before returning.

Returns:

True if the extrinsic was successful.

Return type:

success (bool)

Raises:

StakeError – If the extrinsic failed.

_do_unstake(wallet, hotkey_ss58, amount, wait_for_inclusion=True, wait_for_finalization=False)[source]#

Sends an unstake extrinsic to the chain.

Parameters:
  • wallet (bittensor.wallet()) – Wallet object that can sign the extrinsic.

  • hotkey_ss58 (str) – Hotkey ss58 address to unstake from.

  • amount (Balance()) – Amount to unstake.

  • wait_for_inclusion (bool) – If true, waits for inclusion before returning.

  • wait_for_finalization (bool) – If true, waits for finalization before returning.

Returns:

True if the extrinsic was successful.

Return type:

success (bool)

Raises:

StakeError – If the extrinsic failed.

static min_required_stake()[source]#

As the minimum required stake may change, this method allows us to dynamically update the amount in the mock without updating the tests

get_minimum_required_stake()[source]#

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

This method retries the substrate call up to three times with exponential backoff in case of failures.

Returns:

The minimum required stake as a Balance object.

Return type:

Balance

Raises:

Exception – If the substrate call fails after the maximum number of retries.

get_delegate_by_hotkey(hotkey_ss58, block=None)[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], optional) – The blockchain block number for the query.

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.

get_delegates(block=None)[source]#

Retrieves a list of all delegate neurons within the Bittensor network. This function provides an overview of the neurons that are actively involved in the network’s delegation system.

Analyzing the delegate population offers insights into the network’s governance dynamics and the distribution of trust and responsibility among participating neurons.

Parameters:

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

Returns:

A list of DelegateInfo objects detailing each delegate’s characteristics.

Return type:

List[DelegateInfo]

get_delegated(coldkey_ss58, block=None)[source]#

Returns the list of delegates that a given coldkey is staked to.

Parameters:
  • coldkey_ss58 (str)

  • block (Optional[int])

Return type:

List[Tuple[bittensor.chain_data.DelegateInfo, bittensor.utils.balance.Balance]]

get_all_subnets_info(block=None)[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], optional) – The blockchain block number for the query.

Returns:

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

Return type:

List[SubnetInfo]

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

get_subnet_info(netuid, block=None)[source]#

Retrieves detailed information about a specific subnet within the Bittensor network. This function provides key data on the subnet, including its operational parameters and network status.

Parameters:
  • netuid (int) – The network UID of the subnet to query.

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

Returns:

Detailed information about the subnet, or None if not found.

Return type:

Optional[SubnetInfo]

This function is essential for neurons and stakeholders interested in the specifics of a particular subnet, including its governance, performance, and role within the broader network.

_do_serve_prometheus(wallet, call_params, wait_for_inclusion=False, wait_for_finalization=True)[source]#

Sends a serve prometheus extrinsic to the chain. :param wallet: Wallet object. :type wallet: bittensor.wallet() :param call_params: Prometheus serve call parameters. :type call_params: PrometheusServeCallParams() :param wait_for_inclusion: If true, waits for inclusion. :type wait_for_inclusion: bool :param wait_for_finalization: If true, waits for finalization. :type wait_for_finalization: bool

Returns:

True if serve prometheus was successful. error (Optional[str]()): Error message if serve prometheus failed, None otherwise.

Return type:

success (bool)

Parameters:
_do_set_weights(wallet, netuid, uids, vals, version_key, wait_for_inclusion=False, wait_for_finalization=True)[source]#

Internal method to send a transaction to the Bittensor blockchain, setting weights for specified neurons. This method constructs and submits the transaction, handling retries and blockchain communication.

Parameters:
  • wallet (bittensor.wallet) – The wallet associated with the neuron setting the weights.

  • uids (List[int]) – List of neuron UIDs for which weights are being set.

  • vals (List[int]) – List of weight values corresponding to each UID.

  • netuid (int) – Unique identifier for the network.

  • version_key (int, optional) – Version key for compatibility with the network.

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

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

Returns:

A tuple containing a success flag and an optional error message.

Return type:

Tuple[bool, Optional[str]]

This method is vital for the dynamic weighting mechanism in Bittensor, where neurons adjust their trust in other neurons based on observed performance and contributions.

_do_serve_axon(wallet, call_params, wait_for_inclusion=False, wait_for_finalization=True)[source]#

Internal method to submit a serve axon transaction to the Bittensor blockchain. This method creates and submits a transaction, enabling a neuron’s Axon to serve requests on the network.

Parameters:
  • wallet (bittensor.wallet) – The wallet associated with the neuron.

  • call_params (AxonServeCallParams) – Parameters required for the serve axon call.

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

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

Returns:

A tuple containing a success flag and an optional error message.

Return type:

Tuple[bool, Optional[str]]

This function is crucial for initializing and announcing a neuron’s Axon service on the network, enhancing the decentralized computation capabilities of Bittensor.

class bittensor.MockWallet(**kwargs)[source]#

Bases: bittensor.wallet

Mocked Version of the bittensor wallet class, meant to be used for testing

Init bittensor wallet object containing a hot and coldkey. :param _mock: If true creates a mock wallet with random keys. :type _mock: required=True, default=False

_is_mock = True#
_mocked_coldkey_keyfile = None#
_mocked_hotkey_keyfile = None#
property hotkey_file: bittensor.keyfile#

Property that returns the hotkey file.

Returns:

The hotkey file.

Return type:

bittensor.keyfile

property coldkey_file: bittensor.keyfile#

Property that returns the coldkey file.

Returns:

The coldkey file.

Return type:

bittensor.keyfile

property coldkeypub_file: bittensor.keyfile#

Property that returns the coldkeypub file.

Returns:

The coldkeypub file.

Return type:

bittensor.keyfile

class bittensor.SubnetsAPI(wallet)[source]#

Bases: abc.ABC

Helper class that provides a standard way to create an ABC using inheritance.

Parameters:

wallet (bittensor.wallet)

wallet#
dendrite#
async __call__(*args, **kwargs)[source]#
abstract prepare_synapse(*args, **kwargs)[source]#

Prepare the synapse-specific payload.

Return type:

Any

abstract process_responses(responses)[source]#

Process the responses from the network.

Parameters:

responses (List[Union[bittensor.Synapse, Any]])

Return type:

Any

async query_api(axons, deserialize=False, timeout=12, **kwargs)[source]#

Queries the API nodes of a subnet using the given synapse and bespoke query function.

Parameters:
  • axons (Union[bt.axon, List[bt.axon]]) – The list of axon(s) to query.

  • deserialize (bool, optional) – Whether to deserialize the responses. Defaults to False.

  • timeout (int, optional) – The timeout in seconds for the query. Defaults to 12.

  • **kwargs – Keyword arguments for the prepare_synapse_fn.

Returns:

The result of the process_responses_fn.

Return type:

Any

bittensor.configs#
bittensor.defaults#