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)