diff --git a/.circleci/config.yml b/.circleci/config.yml index 7ea959790e..d9fd2d9363 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -37,7 +37,13 @@ jobs: key: v2-pypi-py-ruff-<< parameters.python-version >> - run: - name: Ruff format check + name: Ruff linter check + command: | + . .venv/bin/activate + ruff check --diff --unsafe-fixes . + + - run: + name: Ruff format command: | . .venv/bin/activate ruff format --diff . diff --git a/README.md b/README.md index b9284f2a5b..2a16a97577 100644 --- a/README.md +++ b/README.md @@ -244,7 +244,7 @@ Subtensor: Interfaces with bittensor's blockchain and can perform operations lik ```python import bittensor # Bittensor's chain interface. -subtensor = bittensor.subtensor() +subtensor = bittensor.Subtensor() # Get the chain block subtensor.get_current_block() # Transfer Tao to a destination address. diff --git a/bittensor/__init__.py b/bittensor/__init__.py index 8ec8019728..05eeeebea2 100644 --- a/bittensor/__init__.py +++ b/bittensor/__init__.py @@ -17,12 +17,9 @@ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. -from rich.console import Console -from rich.traceback import install - # Install and apply nest asyncio to allow the async functions # to run in a .ipynb -import nest_asyncio +import nest_asyncio # noqa: F401 nest_asyncio.apply() @@ -37,6 +34,9 @@ ) __new_signature_version__ = 360 +from rich.console import Console # noqa: F401, E402 +from rich.traceback import install # noqa: F401, E402 + # Rich console. __console__ = Console() __use_console__ = True @@ -261,7 +261,6 @@ def debug(on: bool = True): strtobool, strtobool_with_default, get_explorer_root_url_by_network_from_map, - get_explorer_root_url_by_network_from_map, get_explorer_url_for_network, ss58_address_to_bytes, U16_NORMALIZED_FLOAT, diff --git a/bittensor/axon.py b/bittensor/axon.py index 7f4aff1c73..a424c155b6 100644 --- a/bittensor/axon.py +++ b/bittensor/axon.py @@ -31,11 +31,12 @@ import traceback import typing import uuid -from inspect import signature, Signature, Parameter -from typing import List, Optional, Tuple, Callable, Any, Dict, Awaitable +from collections.abc import Awaitable +from inspect import Parameter, Signature, signature +from typing import Any, Callable, Optional import uvicorn -from fastapi import FastAPI, APIRouter, Depends +from fastapi import APIRouter, Depends, FastAPI from fastapi.responses import JSONResponse from fastapi.routing import serialize_response from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint @@ -45,15 +46,15 @@ import bittensor from bittensor.errors import ( + BlacklistedException, InvalidRequestNameError, - SynapseDendriteNoneException, - SynapseParsingError, - UnknownSynapseError, NotVerifiedException, - BlacklistedException, - PriorityException, PostProcessException, + PriorityException, + SynapseDendriteNoneException, SynapseException, + SynapseParsingError, + UnknownSynapseError, ) from bittensor.threadpool import PriorityThreadPoolExecutor from bittensor.utils import networking @@ -342,12 +343,12 @@ def __init__( self.port = self.config.axon.port self.external_ip = ( self.config.axon.external_ip - if self.config.axon.external_ip != None + if self.config.axon.external_ip is not None else bittensor.utils.networking.get_external_ip() ) self.external_port = ( self.config.axon.external_port - if self.config.axon.external_port != None + if self.config.axon.external_port is not None else self.config.axon.port ) self.full_address = str(self.config.axon.ip) + ":" + str(self.config.axon.port) @@ -357,14 +358,14 @@ def __init__( self.thread_pool = bittensor.PriorityThreadPoolExecutor( max_workers=self.config.axon.max_workers ) - self.nonces: Dict[str, int] = {} + self.nonces: dict[str, int] = {} # Request default functions. - self.forward_class_types: Dict[str, List[Signature]] = {} - self.blacklist_fns: Dict[str, Optional[Callable]] = {} - self.priority_fns: Dict[str, Optional[Callable]] = {} - self.forward_fns: Dict[str, Optional[Callable]] = {} - self.verify_fns: Dict[str, Optional[Callable]] = {} + self.forward_class_types: dict[str, list[Signature]] = {} + self.blacklist_fns: dict[str, Optional[Callable]] = {} + self.priority_fns: dict[str, Optional[Callable]] = {} + self.forward_fns: dict[str, Optional[Callable]] = {} + self.verify_fns: dict[str, Optional[Callable]] = {} # Instantiate FastAPI self.app = FastAPI() @@ -517,27 +518,21 @@ async def endpoint(*args, **kwargs): ] if blacklist_fn: blacklist_sig = Signature( - expected_params, return_annotation=Tuple[bool, str] + expected_params, return_annotation=tuple[bool, str] ) assert ( signature(blacklist_fn) == blacklist_sig - ), "The blacklist_fn function must have the signature: blacklist( synapse: {} ) -> Tuple[bool, str]".format( - request_name - ) + ), f"The blacklist_fn function must have the signature: blacklist( synapse: {request_name} ) -> Tuple[bool, str]" if priority_fn: priority_sig = Signature(expected_params, return_annotation=float) assert ( signature(priority_fn) == priority_sig - ), "The priority_fn function must have the signature: priority( synapse: {} ) -> float".format( - request_name - ) + ), f"The priority_fn function must have the signature: priority( synapse: {request_name} ) -> float" if verify_fn: verify_sig = Signature(expected_params, return_annotation=None) assert ( signature(verify_fn) == verify_sig - ), "The verify_fn function must have the signature: verify( synapse: {} ) -> None".format( - request_name - ) + ), f"The verify_fn function must have the signature: verify( synapse: {request_name} ) -> None" # Store functions in appropriate attribute dictionaries self.forward_class_types[request_name] = param_class @@ -1149,7 +1144,7 @@ async def preprocess(self, request: Request) -> bittensor.Synapse: # Extracts the request name from the URL path. try: request_name = request.url.path.split("/")[1] - except: + except: # noqa: E722 # FIXME: This is a broad exception catch, should be narrowed down. raise InvalidRequestNameError( f"Improperly formatted request. Could not parser request {request.url.path}." ) @@ -1164,7 +1159,7 @@ async def preprocess(self, request: Request) -> bittensor.Synapse: try: synapse = request_synapse.from_headers(request.headers) # type: ignore - except Exception as e: + except Exception: raise SynapseParsingError( f"Improperly formatted request. Could not parse headers {request.headers} into synapse of type {request_name}." ) @@ -1325,7 +1320,7 @@ async def priority(self, synapse: bittensor.Synapse): async def submit_task( executor: PriorityThreadPoolExecutor, priority: float - ) -> Tuple[float, Any]: + ) -> tuple[float, Any]: """ Submits the given priority function to the specified executor for asynchronous execution. The function will run in the provided executor and return the priority value along with the result. diff --git a/bittensor/btlogging/__init__.py b/bittensor/btlogging/__init__.py index 6bf6d2bf35..ab76ebb9df 100644 --- a/bittensor/btlogging/__init__.py +++ b/bittensor/btlogging/__init__.py @@ -24,5 +24,4 @@ from bittensor.btlogging.loggingmachine import LoggingMachine - logging = LoggingMachine(LoggingMachine.config()) diff --git a/bittensor/btlogging/defines.py b/bittensor/btlogging/defines.py index c87177ffd0..88e0429779 100644 --- a/bittensor/btlogging/defines.py +++ b/bittensor/btlogging/defines.py @@ -19,7 +19,7 @@ BASE_LOG_FORMAT = "%(asctime)s | %(levelname)s | %(message)s" TRACE_LOG_FORMAT = ( - f"%(asctime)s | %(levelname)s | %(name)s:%(filename)s:%(lineno)s | %(message)s" + "%(asctime)s | %(levelname)s | %(name)s:%(filename)s:%(lineno)s | %(message)s" ) DATE_FORMAT = "%Y-%m-%d %H:%M:%S" BITTENSOR_LOGGER_NAME = "bittensor" diff --git a/bittensor/btlogging/format.py b/bittensor/btlogging/format.py index 5f2c8cb866..f0741c17ec 100644 --- a/bittensor/btlogging/format.py +++ b/bittensor/btlogging/format.py @@ -23,10 +23,8 @@ import logging import time -from typing import Dict - -from colorama import init, Fore, Back, Style +from colorama import Back, Fore, Style, init init(autoreset=True) @@ -52,14 +50,14 @@ def _success(self, message: str, *args, **kws): logging.addLevelName(TRACE_LEVEL_NUM, "TRACE") logging.Logger.trace = _trace -emoji_map: Dict[str, str] = { +emoji_map: dict[str, str] = { ":white_heavy_check_mark:": "✅", ":cross_mark:": "❌", ":satellite:": "🛰️", } -color_map: Dict[str, str] = { +color_map: dict[str, str] = { "": Fore.RED, "": Style.RESET_ALL, "": Fore.BLUE, @@ -69,7 +67,7 @@ def _success(self, message: str, *args, **kws): } -log_level_color_prefix: Dict[int, str] = { +log_level_color_prefix: dict[int, str] = { logging.NOTSET: Fore.RESET, logging.TRACE: Fore.MAGENTA, logging.DEBUG: Fore.BLUE, @@ -81,12 +79,12 @@ def _success(self, message: str, *args, **kws): } -LOG_FORMATS: Dict[int, str] = { +LOG_FORMATS: dict[int, str] = { level: f"{Fore.BLUE}%(asctime)s{Fore.RESET} | {Style.BRIGHT}{color}%(levelname)s\033[0m | %(message)s" for level, color in log_level_color_prefix.items() } -LOG_TRACE_FORMATS: Dict[int, str] = { +LOG_TRACE_FORMATS: dict[int, str] = { level: f"{Fore.BLUE}%(asctime)s{Fore.RESET}" f" | {Style.BRIGHT}{color}%(levelname)s{Fore.RESET}{Back.RESET}{Style.RESET_ALL}" f" | %(name)s:%(filename)s:%(lineno)s" @@ -134,7 +132,7 @@ def formatTime(self, record, datefmt=None) -> str: s = time.strftime(datefmt, created) else: s = time.strftime("%Y-%m-%d %H:%M:%S", created) - s += ".{:03d}".format(int(record.msecs)) + s += f".{int(record.msecs):03d}" return s def format(self, record) -> str: @@ -205,7 +203,7 @@ def formatTime(self, record, datefmt=None) -> str: s = time.strftime(datefmt, created) else: s = time.strftime("%Y-%m-%d %H:%M:%S", created) - s += ".{:03d}".format(int(record.msecs)) + s += f".{int(record.msecs):03d}" return s def format(self, record) -> str: diff --git a/bittensor/btlogging/helpers.py b/bittensor/btlogging/helpers.py index 532c1f7166..f31b3e261e 100644 --- a/bittensor/btlogging/helpers.py +++ b/bittensor/btlogging/helpers.py @@ -20,7 +20,7 @@ """ import logging -from typing import Generator +from collections.abc import Generator def all_loggers() -> Generator[logging.Logger, None, None]: diff --git a/bittensor/btlogging/loggingmachine.py b/bittensor/btlogging/loggingmachine.py index 1c6aad3bb6..1bb7214a37 100644 --- a/bittensor/btlogging/loggingmachine.py +++ b/bittensor/btlogging/loggingmachine.py @@ -31,18 +31,18 @@ from logging.handlers import QueueHandler, QueueListener, RotatingFileHandler from typing import NamedTuple -from statemachine import StateMachine, State +from statemachine import State, StateMachine import bittensor.config from bittensor.btlogging.defines import ( - TRACE_LOG_FORMAT, - DATE_FORMAT, BITTENSOR_LOGGER_NAME, + DATE_FORMAT, + DEFAULT_LOG_BACKUP_COUNT, DEFAULT_LOG_FILE_NAME, DEFAULT_MAX_ROTATING_LOG_FILE_SIZE, - DEFAULT_LOG_BACKUP_COUNT, + TRACE_LOG_FORMAT, ) -from bittensor.btlogging.format import BtStreamFormatter, BtFileFormatter +from bittensor.btlogging.format import BtFileFormatter, BtStreamFormatter from bittensor.btlogging.helpers import all_loggers @@ -91,7 +91,7 @@ class LoggingMachine(StateMachine): def __init__(self, config: bittensor.config, name: str = BITTENSOR_LOGGER_NAME): # basics - super(LoggingMachine, self).__init__() + super().__init__() self._queue = mp.Queue(-1) self._primary_loggers = {name} self._config = config @@ -260,7 +260,7 @@ def after_transition(self, event, state): # Default Logging def before_enable_default(self): """Logs status before enable Default.""" - self._logger.info(f"Enabling default logging.") + self._logger.info("Enabling default logging.") self._logger.setLevel(stdlogging.INFO) for logger in all_loggers(): if logger.name in self._primary_loggers: @@ -284,7 +284,7 @@ def after_enable_trace(self): def before_disable_trace(self): """Logs status before disable Trace.""" - self._logger.info(f"Disabling trace.") + self._logger.info("Disabling trace.") self._stream_formatter.set_trace(False) self.enable_default() diff --git a/bittensor/chain_data.py b/bittensor/chain_data.py index 6edc7116cc..f5260c2133 100644 --- a/bittensor/chain_data.py +++ b/bittensor/chain_data.py @@ -21,9 +21,9 @@ """ import json -from dataclasses import dataclass, asdict +from dataclasses import asdict, dataclass from enum import Enum -from typing import List, Tuple, Dict, Optional, Any, TypedDict, Union +from typing import Any, Optional, TypedDict, Union from scalecodec.base import RuntimeConfiguration, ScaleBytes from scalecodec.type_registry import load_type_registry_preset @@ -31,7 +31,9 @@ from scalecodec.utils.ss58 import ss58_encode import bittensor -from .utils import networking as net, RAOPERTAO, U16_NORMALIZED_FLOAT + +from .utils import RAOPERTAO, U16_NORMALIZED_FLOAT +from .utils import networking as net from .utils.balance import Balance from .utils.registration import torch, use_torch @@ -230,9 +232,7 @@ def __eq__(self, other: "AxonInfo"): return False def __str__(self): - return "AxonInfo( {}, {}, {}, {} )".format( - str(self.ip_str()), str(self.hotkey), str(self.coldkey), self.version - ) + return f"AxonInfo( {str(self.ip_str())}, {str(self.hotkey)}, {str(self.coldkey)}, {self.version} )" def __repr__(self): return self.__str__() @@ -327,11 +327,11 @@ class ChainDataType(Enum): def from_scale_encoding( - input_: Union[List[int], bytes, ScaleBytes], + input_: Union[list[int], bytes, ScaleBytes], type_name: ChainDataType, is_vec: bool = False, is_option: bool = False, -) -> Optional[Dict]: +) -> Optional[dict]: """ Decodes input_ data from SCALE encoding based on the specified type name and modifiers. @@ -357,8 +357,8 @@ def from_scale_encoding( def from_scale_encoding_using_type_string( - input_: Union[List[int], bytes, ScaleBytes], type_string: str -) -> Optional[Dict]: + input_: Union[list[int], bytes, ScaleBytes], type_string: str +) -> Optional[dict]: if isinstance(input_, ScaleBytes): as_scale_bytes = input_ else: @@ -393,7 +393,7 @@ class NeuronInfo: active: int stake: Balance # mapping of coldkey to amount staked to this Neuron - stake_dict: Dict[str, Balance] + stake_dict: dict[str, Balance] total_stake: Balance rank: float emission: float @@ -404,8 +404,8 @@ class NeuronInfo: dividends: float last_update: int validator_permit: bool - weights: List[List[int]] - bonds: List[List[int]] + weights: list[list[int]] + bonds: list[list[int]] pruning_score: int prometheus_info: Optional["PrometheusInfo"] = None axon_info: Optional[AxonInfo] = None @@ -462,7 +462,7 @@ def fix_decoded_values(cls, neuron_info_decoded: Any) -> "NeuronInfo": return cls(**neuron_info_decoded) @classmethod - def from_vec_u8(cls, vec_u8: List[int]) -> "NeuronInfo": + def from_vec_u8(cls, vec_u8: list[int]) -> "NeuronInfo": """Returns a NeuronInfo object from a ``vec_u8``.""" if len(vec_u8) == 0: return NeuronInfo.get_null_neuron() @@ -474,7 +474,7 @@ def from_vec_u8(cls, vec_u8: List[int]) -> "NeuronInfo": return NeuronInfo.fix_decoded_values(decoded) @classmethod - def list_from_vec_u8(cls, vec_u8: List[int]) -> List["NeuronInfo"]: + def list_from_vec_u8(cls, vec_u8: list[int]) -> list["NeuronInfo"]: """Returns a list of NeuronInfo objects from a ``vec_u8``""" decoded_list = from_scale_encoding( @@ -521,8 +521,8 @@ def get_null_neuron() -> "NeuronInfo": def from_weights_bonds_and_neuron_lite( cls, neuron_lite: "NeuronInfoLite", - weights_as_dict: Dict[int, List[Tuple[int, int]]], - bonds_as_dict: Dict[int, List[Tuple[int, int]]], + weights_as_dict: dict[int, list[tuple[int, int]]], + bonds_as_dict: dict[int, list[tuple[int, int]]], ) -> "NeuronInfo": n_dict = neuron_lite.__dict__ n_dict["weights"] = weights_as_dict.get(neuron_lite.uid, []) @@ -542,7 +542,7 @@ class NeuronInfoLite: active: int stake: Balance # mapping of coldkey to amount staked to this Neuron - stake_dict: Dict[str, Balance] + stake_dict: dict[str, Balance] total_stake: Balance rank: float emission: float @@ -554,7 +554,7 @@ class NeuronInfoLite: last_update: int validator_permit: bool prometheus_info: Optional["PrometheusInfo"] - axon_info: "axon_info" + axon_info: "AxonInfo" pruning_score: int is_null: bool = False @@ -602,7 +602,7 @@ def fix_decoded_values(cls, neuron_info_decoded: Any) -> "NeuronInfoLite": return cls(**neuron_info_decoded) @classmethod - def from_vec_u8(cls, vec_u8: List[int]) -> "NeuronInfoLite": + def from_vec_u8(cls, vec_u8: list[int]) -> "NeuronInfoLite": """Returns a NeuronInfoLite object from a ``vec_u8``.""" if len(vec_u8) == 0: return NeuronInfoLite.get_null_neuron() @@ -614,7 +614,7 @@ def from_vec_u8(cls, vec_u8: List[int]) -> "NeuronInfoLite": return NeuronInfoLite.fix_decoded_values(decoded) @classmethod - def list_from_vec_u8(cls, vec_u8: List[int]) -> List["NeuronInfoLite"]: + def list_from_vec_u8(cls, vec_u8: list[int]) -> list["NeuronInfoLite"]: """Returns a list of NeuronInfoLite objects from a ``vec_u8``.""" decoded_list = from_scale_encoding( @@ -667,7 +667,7 @@ class PrometheusInfo: ip_type: int @classmethod - def fix_decoded_values(cls, prometheus_info_decoded: Dict) -> "PrometheusInfo": + def fix_decoded_values(cls, prometheus_info_decoded: dict) -> "PrometheusInfo": """Returns a PrometheusInfo object from a prometheus_info_decoded dictionary.""" prometheus_info_decoded["ip"] = net.int_to_ip( int(prometheus_info_decoded["ip"]) @@ -724,15 +724,15 @@ class DelegateInfo: hotkey_ss58: str # Hotkey of delegate total_stake: Balance # Total stake of the delegate - nominators: List[ - Tuple[str, Balance] + nominators: list[ + tuple[str, Balance] ] # List of nominators of the delegate and their stake owner_ss58: str # Coldkey of owner take: float # Take of the delegate as a percentage - validator_permits: List[ + validator_permits: list[ int ] # List of subnets that the delegate is allowed to validate on - registrations: List[int] # List of subnets that the delegate is registered on + registrations: list[int] # List of subnets that the delegate is registered on return_per_1000: Balance # Return per 1000 tao of the delegate over a day total_daily_return: Balance # Total daily return of the delegate @@ -763,7 +763,7 @@ def fix_decoded_values(cls, decoded: Any) -> "DelegateInfo": ) @classmethod - def from_vec_u8(cls, vec_u8: List[int]) -> Optional["DelegateInfo"]: + def from_vec_u8(cls, vec_u8: list[int]) -> Optional["DelegateInfo"]: """Returns a DelegateInfo object from a ``vec_u8``.""" if len(vec_u8) == 0: return None @@ -775,7 +775,7 @@ def from_vec_u8(cls, vec_u8: List[int]) -> Optional["DelegateInfo"]: return DelegateInfo.fix_decoded_values(decoded) @classmethod - def list_from_vec_u8(cls, vec_u8: List[int]) -> List["DelegateInfo"]: + def list_from_vec_u8(cls, vec_u8: list[int]) -> list["DelegateInfo"]: """Returns a list of DelegateInfo objects from a ``vec_u8``.""" decoded = from_scale_encoding(vec_u8, ChainDataType.DelegateInfo, is_vec=True) @@ -786,8 +786,8 @@ def list_from_vec_u8(cls, vec_u8: List[int]) -> List["DelegateInfo"]: @classmethod def delegated_list_from_vec_u8( - cls, vec_u8: List[int] - ) -> List[Tuple["DelegateInfo", Balance]]: + cls, vec_u8: list[int] + ) -> list[tuple["DelegateInfo", Balance]]: """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. @@ -820,7 +820,7 @@ def fix_decoded_values(cls, decoded: Any) -> "StakeInfo": ) @classmethod - def from_vec_u8(cls, vec_u8: List[int]) -> Optional["StakeInfo"]: + def from_vec_u8(cls, vec_u8: list[int]) -> Optional["StakeInfo"]: """Returns a StakeInfo object from a ``vec_u8``.""" if len(vec_u8) == 0: return None @@ -833,8 +833,8 @@ def from_vec_u8(cls, vec_u8: List[int]) -> Optional["StakeInfo"]: @classmethod def list_of_tuple_from_vec_u8( - cls, vec_u8: List[int] - ) -> Dict[str, List["StakeInfo"]]: + cls, vec_u8: list[int] + ) -> dict[str, list["StakeInfo"]]: """Returns a list of StakeInfo objects from a ``vec_u8``.""" decoded: Optional[list[tuple[str, list[object]]]] = ( from_scale_encoding_using_type_string( @@ -853,7 +853,7 @@ def list_of_tuple_from_vec_u8( } @classmethod - def list_from_vec_u8(cls, vec_u8: List[int]) -> List["StakeInfo"]: + def list_from_vec_u8(cls, vec_u8: list[int]) -> list["StakeInfo"]: """Returns a list of StakeInfo objects from a ``vec_u8``.""" decoded = from_scale_encoding(vec_u8, ChainDataType.StakeInfo, is_vec=True) if decoded is None: @@ -881,13 +881,13 @@ class SubnetInfo: tempo: int modality: int # netuid -> topk percentile prunning score requirement (u16:MAX normalized.) - connection_requirements: Dict[str, float] + connection_requirements: dict[str, float] emission_value: float burn: Balance owner_ss58: str @classmethod - def from_vec_u8(cls, vec_u8: List[int]) -> Optional["SubnetInfo"]: + def from_vec_u8(cls, vec_u8: list[int]) -> Optional["SubnetInfo"]: """Returns a SubnetInfo object from a ``vec_u8``.""" if len(vec_u8) == 0: return None @@ -899,7 +899,7 @@ def from_vec_u8(cls, vec_u8: List[int]) -> Optional["SubnetInfo"]: return SubnetInfo.fix_decoded_values(decoded) @classmethod - def list_from_vec_u8(cls, vec_u8: List[int]) -> List["SubnetInfo"]: + def list_from_vec_u8(cls, vec_u8: list[int]) -> list["SubnetInfo"]: r"""Returns a list of SubnetInfo objects from a ``vec_u8``.""" decoded = from_scale_encoding( vec_u8, ChainDataType.SubnetInfo, is_vec=True, is_option=True @@ -911,7 +911,7 @@ def list_from_vec_u8(cls, vec_u8: List[int]) -> List["SubnetInfo"]: return [SubnetInfo.fix_decoded_values(d) for d in decoded] @classmethod - def fix_decoded_values(cls, decoded: Dict) -> "SubnetInfo": + def fix_decoded_values(cls, decoded: dict) -> "SubnetInfo": """Returns a SubnetInfo object from a decoded SubnetInfo dictionary.""" return SubnetInfo( netuid=decoded["netuid"], @@ -986,7 +986,7 @@ class SubnetHyperparameters: commit_reveal_weights_enabled: bool @classmethod - def from_vec_u8(cls, vec_u8: List[int]) -> Optional["SubnetHyperparameters"]: + def from_vec_u8(cls, vec_u8: list[int]) -> Optional["SubnetHyperparameters"]: """Returns a SubnetHyperparameters object from a ``vec_u8``.""" if len(vec_u8) == 0: return None @@ -998,7 +998,7 @@ def from_vec_u8(cls, vec_u8: List[int]) -> Optional["SubnetHyperparameters"]: return SubnetHyperparameters.fix_decoded_values(decoded) @classmethod - def list_from_vec_u8(cls, vec_u8: List[int]) -> List["SubnetHyperparameters"]: + def list_from_vec_u8(cls, vec_u8: list[int]) -> list["SubnetHyperparameters"]: """Returns a list of SubnetHyperparameters objects from a ``vec_u8``.""" decoded = from_scale_encoding( vec_u8, ChainDataType.SubnetHyperparameters, is_vec=True, is_option=True @@ -1009,7 +1009,7 @@ def list_from_vec_u8(cls, vec_u8: List[int]) -> List["SubnetHyperparameters"]: return [SubnetHyperparameters.fix_decoded_values(d) for d in decoded] @classmethod - def fix_decoded_values(cls, decoded: Dict) -> "SubnetHyperparameters": + def fix_decoded_values(cls, decoded: dict) -> "SubnetHyperparameters": """Returns a SubnetInfo object from a decoded SubnetInfo dictionary.""" return SubnetHyperparameters( rho=decoded["rho"], @@ -1065,7 +1065,7 @@ class IPInfo: ip_type: int protocol: int - def encode(self) -> Dict[str, Any]: + def encode(self) -> dict[str, Any]: """Returns a dictionary of the IPInfo object that can be encoded.""" return { "ip": net.ip_to_int( @@ -1075,7 +1075,7 @@ def encode(self) -> Dict[str, Any]: } @classmethod - def from_vec_u8(cls, vec_u8: List[int]) -> Optional["IPInfo"]: + def from_vec_u8(cls, vec_u8: list[int]) -> Optional["IPInfo"]: """Returns a IPInfo object from a ``vec_u8``.""" if len(vec_u8) == 0: return None @@ -1087,7 +1087,7 @@ def from_vec_u8(cls, vec_u8: List[int]) -> Optional["IPInfo"]: return IPInfo.fix_decoded_values(decoded) @classmethod - def list_from_vec_u8(cls, vec_u8: List[int]) -> List["IPInfo"]: + def list_from_vec_u8(cls, vec_u8: list[int]) -> list["IPInfo"]: r"""Returns a list of IPInfo objects from a ``vec_u8``.""" decoded = from_scale_encoding(vec_u8, ChainDataType.IPInfo, is_vec=True) @@ -1097,7 +1097,7 @@ def list_from_vec_u8(cls, vec_u8: List[int]) -> List["IPInfo"]: return [IPInfo.fix_decoded_values(d) for d in decoded] @classmethod - def fix_decoded_values(cls, decoded: Dict) -> "IPInfo": + def fix_decoded_values(cls, decoded: dict) -> "IPInfo": """Returns a SubnetInfo object from a decoded IPInfo dictionary.""" return IPInfo( ip=net.int_to_ip(decoded["ip"]), @@ -1128,8 +1128,8 @@ def from_parameter_dict( class ProposalVoteData(TypedDict): index: int threshold: int - ayes: List[str] - nays: List[str] + ayes: list[str] + nays: list[str] end: int diff --git a/bittensor/cli.py b/bittensor/cli.py index 931c5d8d14..21cb4520b2 100644 --- a/bittensor/cli.py +++ b/bittensor/cli.py @@ -15,13 +15,17 @@ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. +import argparse import sys +from typing import Optional + import shtab -import argparse + import bittensor -from typing import List, Optional + from .commands import ( AutocompleteCommand, + CommitWeightCommand, DelegateStakeCommand, DelegateUnstakeCommand, GetIdentityCommand, @@ -43,6 +47,7 @@ RegenHotkeyCommand, RegisterCommand, RegisterSubnetworkCommand, + RevealWeightCommand, RootGetWeightsCommand, RootList, RootRegisterCommand, @@ -68,8 +73,6 @@ VoteCommand, WalletBalanceCommand, WalletCreateCommand, - CommitWeightCommand, - RevealWeightCommand, ) # Create a console instance for CLI display. @@ -233,7 +236,7 @@ class cli: def __init__( self, config: Optional["bittensor.config"] = None, - args: Optional[List[str]] = None, + args: Optional[list[str]] = None, ): """ Initializes a bittensor.CLI object. @@ -313,7 +316,7 @@ def __create_parser__() -> "argparse.ArgumentParser": return parser @staticmethod - def create_config(args: List[str]) -> "bittensor.config": + def create_config(args: list[str]) -> "bittensor.config": """ From the argument parser, add config to bittensor.executor and local config diff --git a/bittensor/commands/__init__.py b/bittensor/commands/__init__.py index 2ccea346a4..fd5dbcdf75 100644 --- a/bittensor/commands/__init__.py +++ b/bittensor/commands/__init__.py @@ -62,63 +62,63 @@ } ) -from .stake import StakeCommand, StakeShow -from .unstake import UnStakeCommand -from .overview import OverviewCommand -from .register import ( - PowRegisterCommand, - RegisterCommand, - RunFaucetCommand, - SwapHotkeyCommand, -) from .delegates import ( - NominateCommand, - ListDelegatesCommand, - ListDelegatesLiteCommand, DelegateStakeCommand, DelegateUnstakeCommand, + ListDelegatesCommand, + ListDelegatesLiteCommand, MyDelegatesCommand, + NominateCommand, SetTakeCommand, ) -from .wallets import ( - NewColdkeyCommand, - NewHotkeyCommand, - RegenColdkeyCommand, - RegenColdkeypubCommand, - RegenHotkeyCommand, - UpdateWalletCommand, - WalletCreateCommand, - WalletBalanceCommand, - GetWalletHistoryCommand, -) -from .weights import CommitWeightCommand, RevealWeightCommand -from .transfer import TransferCommand +from .identity import GetIdentityCommand, SetIdentityCommand from .inspect import InspectCommand -from .metagraph import MetagraphCommand from .list import ListCommand -from .misc import UpdateCommand, AutocompleteCommand -from .senate import ( - SenateCommand, - ProposalsCommand, - ShowVotesCommand, - SenateRegisterCommand, - SenateLeaveCommand, - VoteCommand, -) +from .metagraph import MetagraphCommand +from .misc import AutocompleteCommand, UpdateCommand from .network import ( RegisterSubnetworkCommand, - SubnetLockCostCommand, + SubnetGetHyperparamsCommand, + SubnetHyperparamsCommand, SubnetListCommand, + SubnetLockCostCommand, SubnetSudoCommand, - SubnetHyperparamsCommand, - SubnetGetHyperparamsCommand, +) +from .overview import OverviewCommand +from .register import ( + PowRegisterCommand, + RegisterCommand, + RunFaucetCommand, + SwapHotkeyCommand, ) from .root import ( - RootRegisterCommand, - RootList, - RootSetWeightsCommand, RootGetWeightsCommand, + RootList, + RootRegisterCommand, RootSetBoostCommand, RootSetSlashCommand, + RootSetWeightsCommand, ) -from .identity import GetIdentityCommand, SetIdentityCommand +from .senate import ( + ProposalsCommand, + SenateCommand, + SenateLeaveCommand, + SenateRegisterCommand, + ShowVotesCommand, + VoteCommand, +) +from .stake import StakeCommand, StakeShow +from .transfer import TransferCommand +from .unstake import UnStakeCommand +from .wallets import ( + GetWalletHistoryCommand, + NewColdkeyCommand, + NewHotkeyCommand, + RegenColdkeyCommand, + RegenColdkeypubCommand, + RegenHotkeyCommand, + UpdateWalletCommand, + WalletBalanceCommand, + WalletCreateCommand, +) +from .weights import CommitWeightCommand, RevealWeightCommand diff --git a/bittensor/commands/delegates.py b/bittensor/commands/delegates.py index 344b2bfcea..3e9f6c7a64 100644 --- a/bittensor/commands/delegates.py +++ b/bittensor/commands/delegates.py @@ -18,21 +18,22 @@ import argparse import os import sys -from typing import List, Dict, Optional +from typing import Optional from rich.console import Text -from rich.prompt import Prompt, FloatPrompt, Confirm +from rich.prompt import Confirm, FloatPrompt, Prompt from rich.table import Table from substrateinterface.exceptions import SubstrateRequestException from tqdm import tqdm import bittensor + from . import defaults from .identity import SetIdentityCommand -from .utils import get_delegates_details, DelegatesDetails +from .utils import DelegatesDetails, get_delegates_details -def _get_coldkey_wallets_for_path(path: str) -> List["bittensor.wallet"]: +def _get_coldkey_wallets_for_path(path: str) -> list["bittensor.wallet"]: try: wallet_names = next(os.walk(os.path.expanduser(path)))[1] return [bittensor.wallet(path=path, name=name) for name in wallet_names] @@ -46,7 +47,7 @@ def _get_coldkey_wallets_for_path(path: str) -> List["bittensor.wallet"]: def show_delegates_lite( - delegates_lite: List["bittensor.DelegateInfoLite"], width: Optional[int] = None + delegates_lite: list["bittensor.DelegateInfoLite"], width: Optional[int] = None ): """ This method is a lite version of the :func:`show_delegates`. This method displays a formatted table of Bittensor network delegates with detailed statistics to the console. @@ -83,7 +84,7 @@ def show_delegates_lite( the table in the console. """ - registered_delegate_info: Optional[Dict[str, DelegatesDetails]] = ( + registered_delegate_info: Optional[dict[str, DelegatesDetails]] = ( get_delegates_details(url=bittensor.__delegates_details_url__) ) if registered_delegate_info is None: @@ -153,8 +154,8 @@ def show_delegates_lite( # Uses rich console to pretty print a table of delegates. def show_delegates( - delegates: List["bittensor.DelegateInfo"], - prev_delegates: Optional[List["bittensor.DelegateInfo"]], + delegates: list["bittensor.DelegateInfo"], + prev_delegates: Optional[list["bittensor.DelegateInfo"]], width: Optional[int] = None, ): """ @@ -206,7 +207,7 @@ def show_delegates( for prev_delegate in prev_delegates: prev_delegates_dict[prev_delegate.hotkey_ss58] = prev_delegate - registered_delegate_info: Optional[Dict[str, DelegatesDetails]] = ( + registered_delegate_info: Optional[dict[str, DelegatesDetails]] = ( get_delegates_details(url=bittensor.__delegates_details_url__) ) if registered_delegate_info is None: @@ -287,13 +288,11 @@ def show_delegates( / float(prev_stake) ) if rate_change_in_stake > 0: - rate_change_in_stake_str = "[green]{:.2f}%[/green]".format( - rate_change_in_stake + rate_change_in_stake_str = ( + f"[green]{rate_change_in_stake:.2f}%[/green]" ) elif rate_change_in_stake < 0: - rate_change_in_stake_str = "[red]{:.2f}%[/red]".format( - rate_change_in_stake - ) + rate_change_in_stake_str = f"[red]{rate_change_in_stake:.2f}%[/red]" else: rate_change_in_stake_str = "[grey0]0%[/grey0]" else: @@ -366,7 +365,7 @@ def run(cli: "bittensor.cli"): try: config = cli.config.copy() wallet = bittensor.wallet(config=config) - subtensor: "bittensor.subtensor" = bittensor.subtensor( + subtensor: bittensor.Subtensor = bittensor.Subtensor( config=config, log_verbose=False ) subtensor.delegate( @@ -408,8 +407,8 @@ def check_config(config: "bittensor.config"): if not config.get("delegate_ss58key"): # Check for delegates. with bittensor.__console__.status(":satellite: Loading delegates..."): - subtensor = bittensor.subtensor(config=config, log_verbose=False) - delegates: List[bittensor.DelegateInfo] = subtensor.get_delegates() + subtensor = bittensor.Subtensor(config=config, log_verbose=False) + delegates: list[bittensor.DelegateInfo] = subtensor.get_delegates() try: prev_delegates = subtensor.get_delegates( max(0, subtensor.block - 1200) @@ -424,9 +423,7 @@ def check_config(config: "bittensor.config"): if len(delegates) == 0: console.print( - ":cross_mark: [red]There are no delegates on {}[/red]".format( - subtensor.network - ) + f":cross_mark: [red]There are no delegates on {subtensor.network}[/red]" ) sys.exit(1) @@ -434,9 +431,7 @@ def check_config(config: "bittensor.config"): show_delegates(delegates, prev_delegates=prev_delegates) delegate_index = Prompt.ask("Enter delegate index") config.delegate_ss58key = str(delegates[int(delegate_index)].hotkey_ss58) - console.print( - "Selected: [yellow]{}[/yellow]".format(config.delegate_ss58key) - ) + console.print(f"Selected: [yellow]{config.delegate_ss58key}[/yellow]") if not config.is_set("wallet.name") and not config.no_prompt: wallet_name = Prompt.ask("Enter wallet name", default=defaults.wallet.name) @@ -454,9 +449,7 @@ def check_config(config: "bittensor.config"): config.amount = float(amount) except ValueError: console.print( - ":cross_mark: [red]Invalid Tao amount[/red] [bold white]{}[/bold white]".format( - amount - ) + f":cross_mark: [red]Invalid Tao amount[/red] [bold white]{amount}[/bold white]" ) sys.exit() else: @@ -501,7 +494,7 @@ def run(cli: "bittensor.cli"): """Undelegates stake from a chain delegate.""" try: config = cli.config.copy() - subtensor: "bittensor.subtensor" = bittensor.subtensor( + subtensor: bittensor.Subtensor = bittensor.Subtensor( config=config, log_verbose=False ) DelegateUnstakeCommand._run(cli, subtensor) @@ -510,7 +503,7 @@ def run(cli: "bittensor.cli"): subtensor.close() bittensor.logging.debug("closing subtensor connection") - def _run(self: "bittensor.cli", subtensor: "bittensor.subtensor"): + def _run(self: "bittensor.cli", subtensor: "bittensor.Subtensor"): """Undelegates stake from a chain delegate.""" config = self.config.copy() wallet = bittensor.wallet(config=config) @@ -553,8 +546,8 @@ def check_config(config: "bittensor.config"): if not config.get("delegate_ss58key"): # Check for delegates. with bittensor.__console__.status(":satellite: Loading delegates..."): - subtensor = bittensor.subtensor(config=config, log_verbose=False) - delegates: List[bittensor.DelegateInfo] = subtensor.get_delegates() + subtensor = bittensor.Subtensor(config=config, log_verbose=False) + delegates: list[bittensor.DelegateInfo] = subtensor.get_delegates() try: prev_delegates = subtensor.get_delegates( max(0, subtensor.block - 1200) @@ -569,9 +562,7 @@ def check_config(config: "bittensor.config"): if len(delegates) == 0: console.print( - ":cross_mark: [red]There are no delegates on {}[/red]".format( - subtensor.network - ) + f":cross_mark: [red]There are no delegates on {subtensor.network}[/red]" ) sys.exit(1) @@ -579,9 +570,7 @@ def check_config(config: "bittensor.config"): show_delegates(delegates, prev_delegates=prev_delegates) delegate_index = Prompt.ask("Enter delegate index") config.delegate_ss58key = str(delegates[int(delegate_index)].hotkey_ss58) - console.print( - "Selected: [yellow]{}[/yellow]".format(config.delegate_ss58key) - ) + console.print(f"Selected: [yellow]{config.delegate_ss58key}[/yellow]") # Get amount. if not config.get("amount") and not config.get("unstake_all"): @@ -595,9 +584,7 @@ def check_config(config: "bittensor.config"): config.amount = float(amount) except ValueError: console.print( - ":cross_mark: [red]Invalid Tao amount[/red] [bold white]{}[/bold white]".format( - amount - ) + f":cross_mark: [red]Invalid Tao amount[/red] [bold white]{amount}[/bold white]" ) sys.exit() else: @@ -647,7 +634,7 @@ def run(cli: "bittensor.cli"): cli.config.subtensor.chain_endpoint = ( "wss://archive.chain.opentensor.ai:443" ) - subtensor: "bittensor.subtensor" = bittensor.subtensor( + subtensor: bittensor.Subtensor = bittensor.Subtensor( config=cli.config, log_verbose=False ) ListDelegatesLiteCommand._run(cli, subtensor) @@ -657,7 +644,7 @@ def run(cli: "bittensor.cli"): bittensor.logging.debug("closing subtensor connection") @staticmethod - def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): + def _run(cli: "bittensor.cli", subtensor: "bittensor.Subtensor"): r""" List all delegates on the network. """ @@ -729,7 +716,7 @@ def run(cli: "bittensor.cli"): cli.config.subtensor.chain_endpoint = ( "wss://archive.chain.opentensor.ai:443" ) - subtensor: "bittensor.subtensor" = bittensor.subtensor( + subtensor: bittensor.Subtensor = bittensor.Subtensor( config=cli.config, log_verbose=False ) ListDelegatesCommand._run(cli, subtensor) @@ -739,7 +726,7 @@ def run(cli: "bittensor.cli"): bittensor.logging.debug("closing subtensor connection") @staticmethod - def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): + def _run(cli: "bittensor.cli", subtensor: "bittensor.Subtensor"): r""" List all delegates on the network. """ @@ -811,7 +798,7 @@ class NominateCommand: def run(cli: "bittensor.cli"): r"""Nominate wallet.""" try: - subtensor: "bittensor.subtensor" = bittensor.subtensor( + subtensor: bittensor.Subtensor = bittensor.Subtensor( config=cli.config, log_verbose=False ) NominateCommand._run(cli, subtensor) @@ -821,7 +808,7 @@ def run(cli: "bittensor.cli"): bittensor.logging.debug("closing subtensor connection") @staticmethod - def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): + def _run(cli: "bittensor.cli", subtensor: "bittensor.Subtensor"): r"""Nominate wallet.""" wallet = bittensor.wallet(config=cli.config) @@ -832,39 +819,31 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): # Check if the hotkey is already a delegate. if subtensor.is_hotkey_delegate(wallet.hotkey.ss58_address): bittensor.__console__.print( - "Aborting: Hotkey {} is already a delegate.".format( - wallet.hotkey.ss58_address - ) + f"Aborting: Hotkey {wallet.hotkey.ss58_address} is already a delegate." ) return result: bool = subtensor.nominate(wallet) if not result: bittensor.__console__.print( - "Could not became a delegate on [white]{}[/white]".format( - subtensor.network - ) + f"Could not became a delegate on [white]{subtensor.network}[/white]" ) else: # Check if we are a delegate. is_delegate: bool = subtensor.is_hotkey_delegate(wallet.hotkey.ss58_address) if not is_delegate: bittensor.__console__.print( - "Could not became a delegate on [white]{}[/white]".format( - subtensor.network - ) + f"Could not became a delegate on [white]{subtensor.network}[/white]" ) return bittensor.__console__.print( - "Successfully became a delegate on [white]{}[/white]".format( - subtensor.network - ) + f"Successfully became a delegate on [white]{subtensor.network}[/white]" ) # Prompt use to set identity on chain. if not cli.config.no_prompt: do_set_identity = Prompt.ask( - f"Subnetwork registered successfully. Would you like to set your identity? [y/n]", + "Subnetwork registered successfully. Would you like to set your identity? [y/n]", choices=["y", "n"], ) @@ -943,7 +922,7 @@ def run(cli: "bittensor.cli"): """Delegates stake to a chain delegate.""" try: config = cli.config.copy() - subtensor: "bittensor.subtensor" = bittensor.subtensor( + subtensor: bittensor.Subtensor = bittensor.Subtensor( config=config, log_verbose=False ) MyDelegatesCommand._run(cli, subtensor) @@ -953,7 +932,7 @@ def run(cli: "bittensor.cli"): bittensor.logging.debug("closing subtensor connection") @staticmethod - def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): + def _run(cli: "bittensor.cli", subtensor: "bittensor.Subtensor"): """Delegates stake to a chain delegate.""" config = cli.config.copy() if config.get("all", d=None): @@ -1080,7 +1059,7 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): ) bittensor.__console__.print(table) - bittensor.__console__.print("Total delegated Tao: {}".format(total_delegated)) + bittensor.__console__.print(f"Total delegated Tao: {total_delegated}") @staticmethod def add_args(parser: argparse.ArgumentParser): @@ -1136,7 +1115,7 @@ class SetTakeCommand: def run(cli: "bittensor.cli"): r"""Set delegate take.""" try: - subtensor: "bittensor.subtensor" = bittensor.subtensor( + subtensor: bittensor.Subtensor = bittensor.Subtensor( config=cli.config, log_verbose=False ) SetTakeCommand._run(cli, subtensor) @@ -1146,7 +1125,7 @@ def run(cli: "bittensor.cli"): bittensor.logging.debug("closing subtensor connection") @staticmethod - def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): + def _run(cli: "bittensor.cli", subtensor: "bittensor.Subtensor"): r"""Set delegate take.""" config = cli.config.copy() wallet = bittensor.wallet(config=cli.config) @@ -1158,16 +1137,14 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): # Check if the hotkey is not a delegate. if not subtensor.is_hotkey_delegate(wallet.hotkey.ss58_address): bittensor.__console__.print( - "Aborting: Hotkey {} is NOT a delegate.".format( - wallet.hotkey.ss58_address - ) + f"Aborting: Hotkey {wallet.hotkey.ss58_address} is NOT a delegate." ) return # Prompt user for take value. new_take_str = config.get("take") - if new_take_str == None: - new_take = FloatPrompt.ask(f"Enter take value (0.18 for 18%)") + if new_take_str is None: + new_take = FloatPrompt.ask("Enter take value (0.18 for 18%)") else: new_take = float(new_take_str) @@ -1187,13 +1164,11 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): is_delegate: bool = subtensor.is_hotkey_delegate(wallet.hotkey.ss58_address) if not is_delegate: bittensor.__console__.print( - "Could not set the take [white]{}[/white]".format(subtensor.network) + f"Could not set the take [white]{subtensor.network}[/white]" ) return bittensor.__console__.print( - "Successfully set the take on [white]{}[/white]".format( - subtensor.network - ) + f"Successfully set the take on [white]{subtensor.network}[/white]" ) @staticmethod diff --git a/bittensor/commands/identity.py b/bittensor/commands/identity.py index 15232c4440..3f6826720c 100644 --- a/bittensor/commands/identity.py +++ b/bittensor/commands/identity.py @@ -1,8 +1,9 @@ import argparse -from rich.table import Table -from rich.prompt import Prompt from sys import getsizeof +from rich.prompt import Prompt +from rich.table import Table + import bittensor @@ -58,7 +59,7 @@ class SetIdentityCommand: def run(cli: "bittensor.cli"): r"""Create a new or update existing identity on-chain.""" try: - subtensor: "bittensor.subtensor" = bittensor.subtensor( + subtensor: bittensor.Subtensor = bittensor.Subtensor( config=cli.config, log_verbose=False ) SetIdentityCommand._run(cli, subtensor) @@ -67,7 +68,7 @@ def run(cli: "bittensor.cli"): subtensor.close() bittensor.logging.debug("closing subtensor connection") - def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): + def _run(cli: "bittensor.cli", subtensor: "bittensor.Subtensor"): r"""Create a new or update existing identity on-chain.""" console = bittensor.__console__ @@ -275,7 +276,7 @@ class GetIdentityCommand: def run(cli: "bittensor.cli"): r"""Queries the subtensor chain for user identity.""" try: - subtensor: "bittensor.subtensor" = bittensor.subtensor( + subtensor: bittensor.Subtensor = bittensor.Subtensor( config=cli.config, log_verbose=False ) GetIdentityCommand._run(cli, subtensor) @@ -284,7 +285,7 @@ def run(cli: "bittensor.cli"): subtensor.close() bittensor.logging.debug("closing subtensor connection") - def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): + def _run(cli: "bittensor.cli", subtensor: "bittensor.Subtensor"): console = bittensor.__console__ with console.status(":satellite: [bold green]Querying chain identity..."): diff --git a/bittensor/commands/inspect.py b/bittensor/commands/inspect.py index 4ef0e84c4e..641faa617d 100644 --- a/bittensor/commands/inspect.py +++ b/bittensor/commands/inspect.py @@ -16,27 +16,28 @@ # DEALINGS IN THE SOFTWARE. import argparse -import bittensor -from tqdm import tqdm -from rich.table import Table +import os +from typing import Optional + from rich.prompt import Prompt +from rich.table import Table +from tqdm import tqdm + +import bittensor + +from . import defaults from .utils import ( - get_delegates_details, DelegatesDetails, - get_hotkey_wallets_for_wallet, - get_all_wallets_for_path, filter_netuids_by_registered_hotkeys, + get_all_wallets_for_path, + get_delegates_details, + get_hotkey_wallets_for_wallet, ) -from . import defaults console = bittensor.__console__ -import os -import bittensor -from typing import List, Tuple, Optional, Dict - -def _get_coldkey_wallets_for_path(path: str) -> List["bittensor.wallet"]: +def _get_coldkey_wallets_for_path(path: str) -> list["bittensor.wallet"]: try: wallet_names = next(os.walk(os.path.expanduser(path)))[1] return [bittensor.wallet(path=path, name=name) for name in wallet_names] @@ -46,7 +47,7 @@ def _get_coldkey_wallets_for_path(path: str) -> List["bittensor.wallet"]: return wallets -def _get_hotkey_wallets_for_wallet(wallet) -> List["bittensor.wallet"]: +def _get_hotkey_wallets_for_wallet(wallet) -> list["bittensor.wallet"]: hotkey_wallets = [] hotkeys_path = wallet.path + "/" + wallet.name + "/hotkeys" try: @@ -114,7 +115,7 @@ class InspectCommand: def run(cli: "bittensor.cli"): r"""Inspect a cold, hot pair.""" try: - subtensor: "bittensor.subtensor" = bittensor.subtensor( + subtensor: bittensor.Subtensor = bittensor.Subtensor( config=cli.config, log_verbose=False ) InspectCommand._run(cli, subtensor) @@ -124,8 +125,8 @@ def run(cli: "bittensor.cli"): bittensor.logging.debug("closing subtensor connection") @staticmethod - def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): - if cli.config.get("all", d=False) == True: + def _run(cli: "bittensor.cli", subtensor: "bittensor.Subtensor"): + if cli.config.get("all", d=False) is True: wallets = _get_coldkey_wallets_for_path(cli.config.wallet.path) all_hotkeys = get_all_wallets_for_path(cli.config.wallet.path) else: @@ -138,7 +139,7 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): ) bittensor.logging.debug(f"Netuids to check: {netuids}") - registered_delegate_info: Optional[Dict[str, DelegatesDetails]] = ( + registered_delegate_info: Optional[dict[str, DelegatesDetails]] = ( get_delegates_details(url=bittensor.__delegates_details_url__) ) if registered_delegate_info is None: @@ -150,7 +151,7 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): neuron_state_dict = {} for netuid in tqdm(netuids): neurons = subtensor.neurons_lite(netuid) - neuron_state_dict[netuid] = neurons if neurons != None else [] + neuron_state_dict[netuid] = neurons if neurons is not None else [] table = Table(show_footer=True, pad_edge=False, box=None, expand=True) table.add_column( @@ -181,7 +182,7 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): "[overline white]Emission", footer_style="overline white", style="green" ) for wallet in tqdm(wallets): - delegates: List[Tuple[bittensor.DelegateInfo, bittensor.Balance]] = ( + delegates: list[tuple[bittensor.DelegateInfo, bittensor.Balance]] = ( subtensor.get_delegated(coldkey_ss58=wallet.coldkeypub.ss58_address) ) if not wallet.coldkeypub_file.exists_on_device(): @@ -214,7 +215,7 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): if neuron.coldkey == wallet.coldkeypub.ss58_address: hotkey_name: str = "" - hotkey_names: List[str] = [ + hotkey_names: list[str] = [ wallet.hotkey_str for wallet in filter( lambda hotkey: hotkey.hotkey.ss58_address @@ -249,7 +250,7 @@ def check_config(config: "bittensor.config"): wallet_name = Prompt.ask("Enter wallet name", default=defaults.wallet.name) config.wallet.name = str(wallet_name) - if config.netuids != [] and config.netuids != None: + if config.netuids != [] and config.netuids is not None: if not isinstance(config.netuids, list): config.netuids = [int(config.netuids)] else: diff --git a/bittensor/commands/list.py b/bittensor/commands/list.py index 6079112ed1..1699543027 100644 --- a/bittensor/commands/list.py +++ b/bittensor/commands/list.py @@ -15,12 +15,14 @@ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. -import os import argparse -import bittensor +import os + from rich import print from rich.tree import Tree +import bittensor + console = bittensor.__console__ @@ -68,12 +70,10 @@ def run(cli): coldkeypub_str = wallet_for_name.coldkeypub.ss58_address else: coldkeypub_str = "?" - except: + except: # noqa: E722 # FIXME: This is a broad exception catch, should be narrowed down. coldkeypub_str = "?" - wallet_tree = root.add( - "\n[bold white]{} ({})".format(w_name, coldkeypub_str) - ) + wallet_tree = root.add(f"\n[bold white]{w_name} ({coldkeypub_str})") hotkeys_path = os.path.join(cli.config.wallet.path, w_name, "hotkeys") try: hotkeys = next(os.walk(os.path.expanduser(hotkeys_path))) @@ -90,10 +90,10 @@ def run(cli): hotkey_str = hotkey_for_name.hotkey.ss58_address else: hotkey_str = "?" - except: + except: # noqa: E722 # FIXME: This is a broad exception catch, should be narrowed down. hotkey_str = "?" - wallet_tree.add("[bold grey]{} ({})".format(h_name, hotkey_str)) - except: + wallet_tree.add(f"[bold grey]{h_name} ({hotkey_str})") + except: # noqa: E722 # FIXME: This is a broad exception catch, should be narrowed down. continue if len(wallets) == 0: diff --git a/bittensor/commands/metagraph.py b/bittensor/commands/metagraph.py index 1075f50d31..46430c53ed 100644 --- a/bittensor/commands/metagraph.py +++ b/bittensor/commands/metagraph.py @@ -16,8 +16,11 @@ # DEALINGS IN THE SOFTWARE. import argparse -import bittensor + from rich.table import Table + +import bittensor + from .utils import check_netuid_set console = bittensor.__console__ # type: ignore @@ -73,7 +76,7 @@ class MetagraphCommand: def run(cli: "bittensor.cli"): r"""Prints an entire metagraph.""" try: - subtensor: "bittensor.subtensor" = bittensor.subtensor( + subtensor: bittensor.Subtensor = bittensor.Subtensor( config=cli.config, log_verbose=False ) MetagraphCommand._run(cli, subtensor) @@ -82,18 +85,16 @@ def run(cli: "bittensor.cli"): subtensor.close() bittensor.logging.debug("closing subtensor connection") - def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): + def _run(cli: "bittensor.cli", subtensor: "bittensor.Subtensor"): r"""Prints an entire metagraph.""" console = bittensor.__console__ console.print( - ":satellite: Syncing with chain: [white]{}[/white] ...".format( - cli.config.subtensor.network - ) + f":satellite: Syncing with chain: [white]{cli.config.subtensor.network}[/white] ..." ) metagraph: bittensor.metagraph = subtensor.metagraph(netuid=cli.config.netuid) metagraph.save() difficulty = subtensor.difficulty(cli.config.netuid) - subnet_emission = bittensor.Balance.from_tao( + bittensor.Balance.from_tao( subtensor.get_emission_value_by_subnet(cli.config.netuid) ) total_issuance = bittensor.Balance.from_rao(subtensor.total_issuance().rao) @@ -112,16 +113,16 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): ep = metagraph.axons[uid] row = [ str(neuron.uid), - "{:.5f}".format(metagraph.total_stake[uid]), - "{:.5f}".format(metagraph.ranks[uid]), - "{:.5f}".format(metagraph.trust[uid]), - "{:.5f}".format(metagraph.consensus[uid]), - "{:.5f}".format(metagraph.incentive[uid]), - "{:.5f}".format(metagraph.dividends[uid]), - "{}".format(int(metagraph.emission[uid] * 1000000000)), - "{:.5f}".format(metagraph.validator_trust[uid]), + f"{metagraph.total_stake[uid]:.5f}", + f"{metagraph.ranks[uid]:.5f}", + f"{metagraph.trust[uid]:.5f}", + f"{metagraph.consensus[uid]:.5f}", + f"{metagraph.incentive[uid]:.5f}", + f"{metagraph.dividends[uid]:.5f}", + f"{int(metagraph.emission[uid] * 1000000000)}", + f"{metagraph.validator_trust[uid]:.5f}", "*" if metagraph.validator_permit[uid] else "", - str((metagraph.block.item() - metagraph.last_update[uid].item())), + str(metagraph.block.item() - metagraph.last_update[uid].item()), str(metagraph.active[uid].item()), ( ep.ip + ":" + str(ep.port) @@ -142,16 +143,7 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): TABLE_DATA.append(row) total_neurons = len(metagraph.uids) table = Table(show_footer=False) - table.title = "[white]Metagraph: net: {}:{}, block: {}, N: {}/{}, stake: {}, issuance: {}, difficulty: {}".format( - subtensor.network, - metagraph.netuid, - metagraph.block.item(), - sum(metagraph.active.tolist()), - metagraph.n.item(), - bittensor.Balance.from_tao(total_stake), - total_issuance, - difficulty, - ) + table.title = f"[white]Metagraph: net: {subtensor.network}:{metagraph.netuid}, block: {metagraph.block.item()}, N: {sum(metagraph.active.tolist())}/{metagraph.n.item()}, stake: {bittensor.Balance.from_tao(total_stake)}, issuance: {total_issuance}, difficulty: {difficulty}" table.add_column( "[overline white]UID", str(total_neurons), @@ -160,7 +152,7 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): ) table.add_column( "[overline white]STAKE(\u03c4)", - "\u03c4{:.5f}".format(total_stake), + f"\u03c4{total_stake:.5f}", footer_style="overline white", justify="right", style="green", @@ -168,7 +160,7 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): ) table.add_column( "[overline white]RANK", - "{:.5f}".format(total_rank), + f"{total_rank:.5f}", footer_style="overline white", justify="right", style="green", @@ -176,7 +168,7 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): ) table.add_column( "[overline white]TRUST", - "{:.5f}".format(total_trust), + f"{total_trust:.5f}", footer_style="overline white", justify="right", style="green", @@ -184,7 +176,7 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): ) table.add_column( "[overline white]CONSENSUS", - "{:.5f}".format(total_consensus), + f"{total_consensus:.5f}", footer_style="overline white", justify="right", style="green", @@ -192,7 +184,7 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): ) table.add_column( "[overline white]INCENTIVE", - "{:.5f}".format(total_incentive), + f"{total_incentive:.5f}", footer_style="overline white", justify="right", style="green", @@ -200,7 +192,7 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): ) table.add_column( "[overline white]DIVIDENDS", - "{:.5f}".format(total_dividends), + f"{total_dividends:.5f}", footer_style="overline white", justify="right", style="green", @@ -208,7 +200,7 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): ) table.add_column( "[overline white]EMISSION(\u03c1)", - "\u03c1{}".format(int(total_emission)), + f"\u03c1{int(total_emission)}", footer_style="overline white", justify="right", style="green", @@ -216,7 +208,7 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): ) table.add_column( "[overline white]VTRUST", - "{:.5f}".format(total_validator_trust), + f"{total_validator_trust:.5f}", footer_style="overline white", justify="right", style="green", @@ -246,7 +238,7 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): @staticmethod def check_config(config: "bittensor.config"): check_netuid_set( - config, subtensor=bittensor.subtensor(config=config, log_verbose=False) + config, subtensor=bittensor.Subtensor(config=config, log_verbose=False) ) @staticmethod diff --git a/bittensor/commands/misc.py b/bittensor/commands/misc.py index ded1c78042..269eb486a3 100644 --- a/bittensor/commands/misc.py +++ b/bittensor/commands/misc.py @@ -15,12 +15,14 @@ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. -import os import argparse -import bittensor +import os + from rich.prompt import Prompt from rich.table import Table +import bittensor + console = bittensor.__console__ diff --git a/bittensor/commands/network.py b/bittensor/commands/network.py index f20eac67a6..5a82ccb169 100644 --- a/bittensor/commands/network.py +++ b/bittensor/commands/network.py @@ -16,13 +16,16 @@ # DEALINGS IN THE SOFTWARE. import argparse -import bittensor -from . import defaults +from typing import Optional + from rich.prompt import Prompt from rich.table import Table -from typing import List, Optional, Dict -from .utils import get_delegates_details, DelegatesDetails, check_netuid_set + +import bittensor + +from . import defaults from .identity import SetIdentityCommand +from .utils import DelegatesDetails, check_netuid_set, get_delegates_details console = bittensor.__console__ @@ -63,7 +66,7 @@ def run(cli: "bittensor.cli"): r"""Register a subnetwork""" try: config = cli.config.copy() - subtensor: "bittensor.subtensor" = bittensor.subtensor( + subtensor: bittensor.Subtensor = bittensor.Subtensor( config=config, log_verbose=False ) RegisterSubnetworkCommand._run(cli, subtensor) @@ -73,7 +76,7 @@ def run(cli: "bittensor.cli"): bittensor.logging.debug("closing subtensor connection") @staticmethod - def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): + def _run(cli: "bittensor.cli", subtensor: "bittensor.Subtensor"): r"""Register a subnetwork""" wallet = bittensor.wallet(config=cli.config) @@ -85,7 +88,7 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): if success and not cli.config.no_prompt: # Prompt for user to set identity. do_set_identity = Prompt.ask( - f"Subnetwork registered successfully. Would you like to set your identity? [y/n]", + "Subnetwork registered successfully. Would you like to set your identity? [y/n]", choices=["y", "n"], ) @@ -150,7 +153,7 @@ def run(cli: "bittensor.cli"): r"""View locking cost of creating a new subnetwork""" try: config = cli.config.copy() - subtensor: "bittensor.subtensor" = bittensor.subtensor( + subtensor: bittensor.Subtensor = bittensor.Subtensor( config=config, log_verbose=False ) SubnetLockCostCommand._run(cli, subtensor) @@ -160,9 +163,9 @@ def run(cli: "bittensor.cli"): bittensor.logging.debug("closing subtensor connection") @staticmethod - def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): + def _run(cli: "bittensor.cli", subtensor: "bittensor.Subtensor"): r"""View locking cost of creating a new subnetwork""" - config = cli.config.copy() + cli.config.copy() try: bittensor.__console__.print( f"Subnet lock cost: [green]{bittensor.utils.balance.Balance( subtensor.get_subnet_burn_cost() )}[/green]" @@ -226,7 +229,7 @@ class SubnetListCommand: def run(cli: "bittensor.cli"): r"""List all subnet netuids in the network.""" try: - subtensor: "bittensor.subtensor" = bittensor.subtensor( + subtensor: bittensor.Subtensor = bittensor.Subtensor( config=cli.config, log_verbose=False ) SubnetListCommand._run(cli, subtensor) @@ -236,13 +239,13 @@ def run(cli: "bittensor.cli"): bittensor.logging.debug("closing subtensor connection") @staticmethod - def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): + def _run(cli: "bittensor.cli", subtensor: "bittensor.Subtensor"): r"""List all subnet netuids in the network.""" - subnets: List[bittensor.SubnetInfo] = subtensor.get_all_subnets_info() + subnets: list[bittensor.SubnetInfo] = subtensor.get_all_subnets_info() rows = [] total_neurons = 0 - delegate_info: Optional[Dict[str, DelegatesDetails]] = get_delegates_details( + delegate_info: Optional[dict[str, DelegatesDetails]] = get_delegates_details( url=bittensor.__delegates_details_url__ ) @@ -267,7 +270,7 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): box=None, show_edge=True, ) - table.title = "[white]Subnets - {}".format(subtensor.network) + table.title = f"[white]Subnets - {subtensor.network}" table.add_column( "[overline white]NETUID", str(len(subnets)), @@ -354,7 +357,7 @@ class SubnetSudoCommand: def run(cli: "bittensor.cli"): r"""Set subnet hyperparameters.""" try: - subtensor: "bittensor.subtensor" = bittensor.subtensor( + subtensor: bittensor.Subtensor = bittensor.Subtensor( config=cli.config, log_verbose=False ) SubnetSudoCommand._run(cli, subtensor) @@ -366,7 +369,7 @@ def run(cli: "bittensor.cli"): @staticmethod def _run( cli: "bittensor.cli", - subtensor: "bittensor.subtensor", + subtensor: "bittensor.Subtensor", ): r"""Set subnet hyperparameters.""" wallet = bittensor.wallet(config=cli.config) @@ -401,7 +404,7 @@ def check_config(config: "bittensor.config"): if not config.is_set("netuid") and not config.no_prompt: check_netuid_set( - config, bittensor.subtensor(config=config, log_verbose=False) + config, bittensor.Subtensor(config=config, log_verbose=False) ) @staticmethod @@ -463,7 +466,7 @@ class SubnetHyperparamsCommand: def run(cli: "bittensor.cli"): r"""View hyperparameters of a subnetwork.""" try: - subtensor: "bittensor.subtensor" = bittensor.subtensor( + subtensor: bittensor.Subtensor = bittensor.Subtensor( config=cli.config, log_verbose=False ) SubnetHyperparamsCommand._run(cli, subtensor) @@ -473,7 +476,7 @@ def run(cli: "bittensor.cli"): bittensor.logging.debug("closing subtensor connection") @staticmethod - def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): + def _run(cli: "bittensor.cli", subtensor: "bittensor.Subtensor"): r"""View hyperparameters of a subnetwork.""" subnet: bittensor.SubnetHyperparameters = subtensor.get_subnet_hyperparameters( cli.config.netuid @@ -486,9 +489,7 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): box=None, show_edge=True, ) - table.title = "[white]Subnet Hyperparameters - NETUID: {} - {}".format( - cli.config.netuid, subtensor.network - ) + table.title = f"[white]Subnet Hyperparameters - NETUID: {cli.config.netuid} - {subtensor.network}" table.add_column("[overline white]HYPERPARAMETER", style="bold white") table.add_column("[overline white]VALUE", style="green") @@ -501,7 +502,7 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): def check_config(config: "bittensor.config"): if not config.is_set("netuid") and not config.no_prompt: check_netuid_set( - config, bittensor.subtensor(config=config, log_verbose=False) + config, bittensor.Subtensor(config=config, log_verbose=False) ) @staticmethod @@ -567,7 +568,7 @@ class SubnetGetHyperparamsCommand: def run(cli: "bittensor.cli"): r"""View hyperparameters of a subnetwork.""" try: - subtensor: "bittensor.subtensor" = bittensor.subtensor( + subtensor: bittensor.Subtensor = bittensor.Subtensor( config=cli.config, log_verbose=False ) SubnetGetHyperparamsCommand._run(cli, subtensor) @@ -577,7 +578,7 @@ def run(cli: "bittensor.cli"): bittensor.logging.debug("closing subtensor connection") @staticmethod - def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): + def _run(cli: "bittensor.cli", subtensor: "bittensor.Subtensor"): r"""View hyperparameters of a subnetwork.""" subnet: bittensor.SubnetHyperparameters = subtensor.get_subnet_hyperparameters( cli.config.netuid @@ -590,9 +591,7 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): box=None, show_edge=True, ) - table.title = "[white]Subnet Hyperparameters - NETUID: {} - {}".format( - cli.config.netuid, subtensor.network - ) + table.title = f"[white]Subnet Hyperparameters - NETUID: {cli.config.netuid} - {subtensor.network}" table.add_column("[overline white]HYPERPARAMETER", style="white") table.add_column("[overline white]VALUE", style="green") @@ -605,7 +604,7 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): def check_config(config: "bittensor.config"): if not config.is_set("netuid") and not config.no_prompt: check_netuid_set( - config, bittensor.subtensor(config=config, log_verbose=False) + config, bittensor.Subtensor(config=config, log_verbose=False) ) @staticmethod diff --git a/bittensor/commands/overview.py b/bittensor/commands/overview.py index b572847e49..ad94ac23f3 100644 --- a/bittensor/commands/overview.py +++ b/bittensor/commands/overview.py @@ -16,22 +16,25 @@ # DEALINGS IN THE SOFTWARE. import argparse -import bittensor -from tqdm import tqdm -from concurrent.futures import ProcessPoolExecutor from collections import defaultdict +from concurrent.futures import ProcessPoolExecutor +from typing import Optional + from fuzzywuzzy import fuzz from rich.align import Align -from rich.table import Table from rich.prompt import Prompt -from typing import List, Optional, Dict, Tuple +from rich.table import Table +from tqdm import tqdm + +import bittensor + +from . import defaults from .utils import ( - get_hotkey_wallets_for_wallet, - get_coldkey_wallets_for_path, - get_all_wallets_for_path, filter_netuids_by_registered_hotkeys, + get_all_wallets_for_path, + get_coldkey_wallets_for_path, + get_hotkey_wallets_for_wallet, ) -from . import defaults console = bittensor.__console__ @@ -81,7 +84,7 @@ class OverviewCommand: def run(cli: "bittensor.cli"): r"""Prints an overview for the wallet's colkey.""" try: - subtensor: "bittensor.subtensor" = bittensor.subtensor( + subtensor: bittensor.Subtensor = bittensor.Subtensor( config=cli.config, log_verbose=False ) OverviewCommand._run(cli, subtensor) @@ -93,9 +96,9 @@ def run(cli: "bittensor.cli"): @staticmethod def _get_total_balance( total_balance: "bittensor.Balance", - subtensor: "bittensor.subtensor", + subtensor: "bittensor.Subtensor", cli: "bittensor.cli", - ) -> Tuple[List["bittensor.wallet"], "bittensor.Balance"]: + ) -> tuple[list["bittensor.wallet"], "bittensor.Balance"]: if cli.config.get("all", d=None): cold_wallets = get_coldkey_wallets_for_path(cli.config.wallet.path) for cold_wallet in tqdm(cold_wallets, desc="Pulling balances"): @@ -126,8 +129,8 @@ def _get_total_balance( @staticmethod def _get_hotkeys( - cli: "bittensor.cli", all_hotkeys: List["bittensor.wallet"] - ) -> List["bittensor.wallet"]: + cli: "bittensor.cli", all_hotkeys: list["bittensor.wallet"] + ) -> list["bittensor.wallet"]: if not cli.config.get("all_hotkeys", False): # We are only showing hotkeys that are specified. all_hotkeys = [ @@ -145,7 +148,7 @@ def _get_hotkeys( return all_hotkeys @staticmethod - def _get_key_address(all_hotkeys: List["bittensor.wallet"]): + def _get_key_address(all_hotkeys: list["bittensor.wallet"]): hotkey_coldkey_to_hotkey_wallet = {} for hotkey_wallet in all_hotkeys: if hotkey_wallet.hotkey.ss58_address not in hotkey_coldkey_to_hotkey_wallet: @@ -161,10 +164,10 @@ def _get_key_address(all_hotkeys: List["bittensor.wallet"]): @staticmethod def _process_neuron_results( - results: List[Tuple[int, List["bittensor.NeuronInfoLite"], Optional[str]]], - neurons: Dict[str, List["bittensor.NeuronInfoLite"]], - netuids: List[int], - ) -> Dict[str, List["bittensor.NeuronInfoLite"]]: + results: list[tuple[int, list["bittensor.NeuronInfoLite"], Optional[str]]], + neurons: dict[str, list["bittensor.NeuronInfoLite"]], + netuids: list[int], + ) -> dict[str, list["bittensor.NeuronInfoLite"]]: for result in results: netuid, neurons_result, err_msg = result if err_msg is not None: @@ -179,7 +182,7 @@ def _process_neuron_results( neurons[str(netuid)] = neurons_result return neurons - def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): + def _run(cli: "bittensor.cli", subtensor: "bittensor.Subtensor"): r"""Prints an overview for the wallet's colkey.""" console = bittensor.__console__ wallet = bittensor.wallet(config=cli.config) @@ -202,7 +205,7 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): return # Pull neuron info for all keys. - neurons: Dict[str, List[bittensor.NeuronInfoLite]] = {} + neurons: dict[str, list[bittensor.NeuronInfoLite]] = {} block = subtensor.block netuids = subtensor.get_all_subnet_netuids() @@ -283,9 +286,7 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): coldkeys_to_check.append(coldkey_wallet) alerts_table.add_row( - "Found {} stake with coldkey {} that is not registered.".format( - difference, coldkey_wallet.coldkeypub.ss58_address - ) + f"Found {difference} stake with coldkey {coldkey_wallet.coldkeypub.ss58_address} that is not registered." ) if coldkeys_to_check: @@ -351,9 +352,7 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): title: str = "" if not cli.config.get("all", d=None): - title = "[bold white italic]Wallet - {}:{}".format( - cli.config.wallet.name, wallet.coldkeypub.ss58_address - ) + title = f"[bold white italic]Wallet - {cli.config.wallet.name}:{wallet.coldkeypub.ss58_address}" else: title = "[bold whit italic]All Wallets:" @@ -404,14 +403,14 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): hotwallet.hotkey_str, str(uid), str(active), - "{:.5f}".format(stake), - "{:.5f}".format(rank), - "{:.5f}".format(trust), - "{:.5f}".format(consensus), - "{:.5f}".format(incentive), - "{:.5f}".format(dividends), - "{:_}".format(emission), - "{:.5f}".format(validator_trust), + f"{stake:.5f}", + f"{rank:.5f}", + f"{trust:.5f}", + f"{consensus:.5f}", + f"{incentive:.5f}", + f"{dividends:.5f}", + f"{emission:_}", + f"{validator_trust:.5f}", "*" if validator_permit else "", str(last_update), ( @@ -432,7 +431,7 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): total_emission += emission total_validator_trust += validator_trust - if not (nn.hotkey, nn.coldkey) in hotkeys_seen: + if (nn.hotkey, nn.coldkey) not in hotkeys_seen: # Don't double count stake on hotkey-coldkey pairs. hotkeys_seen.add((nn.hotkey, nn.coldkey)) total_stake += stake @@ -445,7 +444,7 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): # Add subnet header if netuid == "-1": - grid.add_row(f"Deregistered Neurons") + grid.add_row("Deregistered Neurons") else: grid.add_row(f"Subnet: [bold white]{netuid}[/bold white]") @@ -484,7 +483,7 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): if last_subnet: table.add_column( "[overline white]STAKE(\u03c4)", - "\u03c4{:.5f}".format(total_stake), + f"\u03c4{total_stake:.5f}", footer_style="overline white", justify="right", style="green", @@ -500,7 +499,7 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): ) table.add_column( "[overline white]RANK", - "{:.5f}".format(total_rank), + f"{total_rank:.5f}", footer_style="overline white", justify="right", style="green", @@ -508,7 +507,7 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): ) table.add_column( "[overline white]TRUST", - "{:.5f}".format(total_trust), + f"{total_trust:.5f}", footer_style="overline white", justify="right", style="green", @@ -516,7 +515,7 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): ) table.add_column( "[overline white]CONSENSUS", - "{:.5f}".format(total_consensus), + f"{total_consensus:.5f}", footer_style="overline white", justify="right", style="green", @@ -524,7 +523,7 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): ) table.add_column( "[overline white]INCENTIVE", - "{:.5f}".format(total_incentive), + f"{total_incentive:.5f}", footer_style="overline white", justify="right", style="green", @@ -532,7 +531,7 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): ) table.add_column( "[overline white]DIVIDENDS", - "{:.5f}".format(total_dividends), + f"{total_dividends:.5f}", footer_style="overline white", justify="right", style="green", @@ -540,7 +539,7 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): ) table.add_column( "[overline white]EMISSION(\u03c1)", - "\u03c1{:_}".format(total_emission), + f"\u03c1{total_emission:_}", footer_style="overline white", justify="right", style="green", @@ -548,7 +547,7 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): ) table.add_column( "[overline white]VTRUST", - "{:.5f}".format(total_validator_trust), + f"{total_validator_trust:.5f}", footer_style="overline white", justify="right", style="green", @@ -613,16 +612,16 @@ def overview_sort_function(row): @staticmethod def _get_neurons_for_netuid( - args_tuple: Tuple["bittensor.Config", int, List[str]], - ) -> Tuple[int, List["bittensor.NeuronInfoLite"], Optional[str]]: + args_tuple: tuple["bittensor.Config", int, list[str]], + ) -> tuple[int, list["bittensor.NeuronInfoLite"], Optional[str]]: subtensor_config, netuid, hot_wallets = args_tuple - result: List["bittensor.NeuronInfoLite"] = [] + result: list[bittensor.NeuronInfoLite] = [] try: - subtensor = bittensor.subtensor(config=subtensor_config, log_verbose=False) + subtensor = bittensor.Subtensor(config=subtensor_config, log_verbose=False) - all_neurons: List["bittensor.NeuronInfoLite"] = subtensor.neurons_lite( + all_neurons: list[bittensor.NeuronInfoLite] = subtensor.neurons_lite( netuid=netuid ) # Map the hotkeys to uids @@ -633,7 +632,7 @@ def _get_neurons_for_netuid( nn = all_neurons[uid] result.append(nn) except Exception as e: - return netuid, [], "Error: {}".format(e) + return netuid, [], f"Error: {e}" finally: if "subtensor" in locals(): subtensor.close() @@ -644,16 +643,16 @@ def _get_neurons_for_netuid( @staticmethod def _get_de_registered_stake_for_coldkey_wallet( args_tuple, - ) -> Tuple[ - "bittensor.Wallet", List[Tuple[str, "bittensor.Balance"]], Optional[str] + ) -> tuple[ + "bittensor.Wallet", list[tuple[str, "bittensor.Balance"]], Optional[str] ]: subtensor_config, all_hotkey_addresses, coldkey_wallet = args_tuple # List of (hotkey_addr, our_stake) tuples. - result: List[Tuple[str, "bittensor.Balance"]] = [] + result: list[tuple[str, bittensor.Balance]] = [] try: - subtensor = bittensor.subtensor(config=subtensor_config, log_verbose=False) + subtensor = bittensor.Subtensor(config=subtensor_config, log_verbose=False) # Pull all stake for our coldkey all_stake_info_for_coldkey = subtensor.get_stake_info_for_coldkey( @@ -682,7 +681,7 @@ def _filter_stake_info(stake_info: "bittensor.StakeInfo") -> bool: ] except Exception as e: - return coldkey_wallet, [], "Error: {}".format(e) + return coldkey_wallet, [], f"Error: {e}" finally: if "subtensor" in locals(): subtensor.close() @@ -771,7 +770,7 @@ def check_config(config: "bittensor.config"): wallet_name = Prompt.ask("Enter wallet name", default=defaults.wallet.name) config.wallet.name = str(wallet_name) - if config.netuids != [] and config.netuids != None: + if config.netuids != [] and config.netuids is not None: if not isinstance(config.netuids, list): config.netuids = [int(config.netuids)] else: diff --git a/bittensor/commands/register.py b/bittensor/commands/register.py index 8b21a33304..99385ef2f1 100644 --- a/bittensor/commands/register.py +++ b/bittensor/commands/register.py @@ -15,14 +15,16 @@ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. -import sys import argparse -import bittensor -from rich.prompt import Prompt, Confirm -from .utils import check_netuid_set, check_for_cuda_reg_config +import sys from copy import deepcopy +from rich.prompt import Confirm, Prompt + +import bittensor + from . import defaults +from .utils import check_for_cuda_reg_config, check_netuid_set console = bittensor.__console__ @@ -65,7 +67,7 @@ def run(cli: "bittensor.cli"): r"""Register neuron by recycling some TAO.""" try: config = cli.config.copy() - subtensor: "bittensor.subtensor" = bittensor.subtensor( + subtensor: bittensor.Subtensor = bittensor.Subtensor( config=config, log_verbose=False ) RegisterCommand._run(cli, subtensor) @@ -75,7 +77,7 @@ def run(cli: "bittensor.cli"): bittensor.logging.debug("closing subtensor connection") @staticmethod - def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): + def _run(cli: "bittensor.cli", subtensor: "bittensor.Subtensor"): r"""Register neuron by recycling some TAO.""" wallet = bittensor.wallet(config=cli.config) @@ -103,7 +105,7 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): f"Your balance is: [bold green]{balance}[/bold green]\nThe cost to register by recycle is [bold red]{current_recycle}[/bold red]\nDo you want to continue?", default=False, ) - == False + is False ): sys.exit(1) @@ -144,7 +146,7 @@ def check_config(config: "bittensor.config"): config.subtensor.chain_endpoint = endpoint check_netuid_set( - config, subtensor=bittensor.subtensor(config=config, log_verbose=False) + config, subtensor=bittensor.Subtensor(config=config, log_verbose=False) ) if not config.is_set("wallet.name") and not config.no_prompt: @@ -195,7 +197,7 @@ class PowRegisterCommand: def run(cli: "bittensor.cli"): r"""Register neuron.""" try: - subtensor: "bittensor.subtensor" = bittensor.subtensor( + subtensor: bittensor.Subtensor = bittensor.Subtensor( config=cli.config, log_verbose=False ) PowRegisterCommand._run(cli, subtensor) @@ -205,7 +207,7 @@ def run(cli: "bittensor.cli"): bittensor.logging.debug("closing subtensor connection") @staticmethod - def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): + def _run(cli: "bittensor.cli", subtensor: "bittensor.Subtensor"): r"""Register neuron.""" wallet = bittensor.wallet(config=cli.config) @@ -343,7 +345,7 @@ def check_config(config: "bittensor.config"): config.subtensor.chain_endpoint = endpoint check_netuid_set( - config, subtensor=bittensor.subtensor(config=config, log_verbose=False) + config, subtensor=bittensor.Subtensor(config=config, log_verbose=False) ) if not config.is_set("wallet.name") and not config.no_prompt: @@ -397,7 +399,7 @@ class RunFaucetCommand: def run(cli: "bittensor.cli"): r"""Register neuron.""" try: - subtensor: "bittensor.subtensor" = bittensor.subtensor( + subtensor: bittensor.Subtensor = bittensor.Subtensor( config=cli.config, log_verbose=False ) RunFaucetCommand._run(cli, subtensor) @@ -407,7 +409,7 @@ def run(cli: "bittensor.cli"): bittensor.logging.debug("closing subtensor connection") @staticmethod - def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): + def _run(cli: "bittensor.cli", subtensor: "bittensor.Subtensor"): r"""Register neuron.""" wallet = bittensor.wallet(config=cli.config) success = subtensor.run_faucet( @@ -525,7 +527,7 @@ class SwapHotkeyCommand: def run(cli: "bittensor.cli"): r"""Swap your hotkey for all registered axons on the network.""" try: - subtensor: "bittensor.subtensor" = bittensor.subtensor( + subtensor: bittensor.Subtensor = bittensor.Subtensor( config=cli.config, log_verbose=False ) SwapHotkeyCommand._run(cli, subtensor) @@ -535,7 +537,7 @@ def run(cli: "bittensor.cli"): bittensor.logging.debug("closing subtensor connection") @staticmethod - def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): + def _run(cli: "bittensor.cli", subtensor: "bittensor.Subtensor"): r"""Swap your hotkey for all registered axons on the network.""" wallet = bittensor.wallet(config=cli.config) diff --git a/bittensor/commands/root.py b/bittensor/commands/root.py index 5607921b19..ec3761e2d2 100644 --- a/bittensor/commands/root.py +++ b/bittensor/commands/root.py @@ -15,17 +15,18 @@ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. -import re -import typing import argparse +import re +from typing import Optional + import numpy as np -import bittensor -from typing import List, Optional, Dict from rich.prompt import Prompt from rich.table import Table -from .utils import get_delegates_details, DelegatesDetails + +import bittensor from . import defaults +from .utils import DelegatesDetails, get_delegates_details console = bittensor.__console__ @@ -56,7 +57,7 @@ class RootRegisterCommand: def run(cli: "bittensor.cli"): r"""Register to root network.""" try: - subtensor: "bittensor.subtensor" = bittensor.subtensor( + subtensor: bittensor.Subtensor = bittensor.Subtensor( config=cli.config, log_verbose=False ) RootRegisterCommand._run(cli, subtensor) @@ -66,7 +67,7 @@ def run(cli: "bittensor.cli"): bittensor.logging.debug("closing subtensor connection") @staticmethod - def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): + def _run(cli: "bittensor.cli", subtensor: "bittensor.Subtensor"): r"""Register to root network.""" wallet = bittensor.wallet(config=cli.config) @@ -126,7 +127,7 @@ class RootList: def run(cli: "bittensor.cli"): r"""List the root network""" try: - subtensor: "bittensor.subtensor" = bittensor.subtensor( + subtensor: bittensor.Subtensor = bittensor.Subtensor( config=cli.config, log_verbose=False ) RootList._run(cli, subtensor) @@ -136,19 +137,15 @@ def run(cli: "bittensor.cli"): bittensor.logging.debug("closing subtensor connection") @staticmethod - def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): + def _run(cli: "bittensor.cli", subtensor: "bittensor.Subtensor"): r"""List the root network""" console.print( - ":satellite: Syncing with chain: [white]{}[/white] ...".format( - subtensor.network - ) + f":satellite: Syncing with chain: [white]{subtensor.network}[/white] ..." ) senate_members = subtensor.get_senate_members() - root_neurons: typing.List[bittensor.NeuronInfoLite] = subtensor.neurons_lite( - netuid=0 - ) - delegate_info: Optional[Dict[str, DelegatesDetails]] = get_delegates_details( + root_neurons: list[bittensor.NeuronInfoLite] = subtensor.neurons_lite(netuid=0) + delegate_info: Optional[dict[str, DelegatesDetails]] = get_delegates_details( url=bittensor.__delegates_details_url__ ) @@ -196,9 +193,7 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): else "" ), neuron_data.hotkey, - "{:.5f}".format( - float(subtensor.get_total_stake_for_hotkey(neuron_data.hotkey)) - ), + f"{float(subtensor.get_total_stake_for_hotkey(neuron_data.hotkey)):.5f}", "Yes" if neuron_data.hotkey in senate_members else "No", ) @@ -269,7 +264,7 @@ class RootSetBoostCommand: def run(cli: "bittensor.cli"): r"""Set weights for root network.""" try: - subtensor: "bittensor.subtensor" = bittensor.subtensor( + subtensor: bittensor.Subtensor = bittensor.Subtensor( config=cli.config, log_verbose=False ) RootSetBoostCommand._run(cli, subtensor) @@ -279,7 +274,7 @@ def run(cli: "bittensor.cli"): bittensor.logging.debug("closing subtensor connection") @staticmethod - def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): + def _run(cli: "bittensor.cli", subtensor: "bittensor.Subtensor"): r"""Set weights for root network.""" wallet = bittensor.wallet(config=cli.config) @@ -288,7 +283,7 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): my_uid = root.hotkeys.index(wallet.hotkey.ss58_address) except ValueError: bittensor.__console__.print( - "Wallet hotkey: {} not found in root metagraph".format(wallet.hotkey) + f"Wallet hotkey: {wallet.hotkey} not found in root metagraph" ) exit() my_weights = root.weights[my_uid] @@ -332,9 +327,9 @@ def check_config(config: "bittensor.config"): hotkey = Prompt.ask("Enter hotkey name", default=defaults.wallet.hotkey) config.wallet.hotkey = str(hotkey) if not config.is_set("netuid") and not config.no_prompt: - config.netuid = int(Prompt.ask(f"Enter netuid (e.g. 1)")) + config.netuid = int(Prompt.ask("Enter netuid (e.g. 1)")) if not config.is_set("amount") and not config.no_prompt: - config.amount = float(Prompt.ask(f"Enter amount (e.g. 0.01)")) + config.amount = float(Prompt.ask("Enter amount (e.g. 0.01)")) class RootSetSlashCommand: @@ -387,7 +382,7 @@ class RootSetSlashCommand: def run(cli: "bittensor.cli"): """Set weights for root network with decreased values.""" try: - subtensor: "bittensor.subtensor" = bittensor.subtensor( + subtensor: bittensor.Subtensor = bittensor.Subtensor( config=cli.config, log_verbose=False ) RootSetSlashCommand._run(cli, subtensor) @@ -397,20 +392,18 @@ def run(cli: "bittensor.cli"): bittensor.logging.debug("closing subtensor connection") @staticmethod - def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): + def _run(cli: "bittensor.cli", subtensor: "bittensor.Subtensor"): wallet = bittensor.wallet(config=cli.config) bittensor.__console__.print( - "Slashing weight for subnet: {} by amount: {}".format( - cli.config.netuid, cli.config.amount - ) + f"Slashing weight for subnet: {cli.config.netuid} by amount: {cli.config.amount}" ) root = subtensor.metagraph(0, lite=False) try: my_uid = root.hotkeys.index(wallet.hotkey.ss58_address) except ValueError: bittensor.__console__.print( - "Wallet hotkey: {} not found in root metagraph".format(wallet.hotkey) + f"Wallet hotkey: {wallet.hotkey} not found in root metagraph" ) exit() my_weights = root.weights[my_uid] @@ -448,9 +441,9 @@ def check_config(config: "bittensor.config"): hotkey = Prompt.ask("Enter hotkey name", default=defaults.wallet.hotkey) config.wallet.hotkey = str(hotkey) if not config.is_set("netuid") and not config.no_prompt: - config.netuid = int(Prompt.ask(f"Enter netuid (e.g. 1)")) + config.netuid = int(Prompt.ask("Enter netuid (e.g. 1)")) if not config.is_set("amount") and not config.no_prompt: - config.amount = float(Prompt.ask(f"Enter decrease amount (e.g. 0.01)")) + config.amount = float(Prompt.ask("Enter decrease amount (e.g. 0.01)")) class RootSetWeightsCommand: @@ -479,7 +472,7 @@ class RootSetWeightsCommand: def run(cli: "bittensor.cli"): r"""Set weights for root network.""" try: - subtensor: "bittensor.subtensor" = bittensor.subtensor( + subtensor: bittensor.Subtensor = bittensor.Subtensor( config=cli.config, log_verbose=False ) RootSetWeightsCommand._run(cli, subtensor) @@ -489,10 +482,10 @@ def run(cli: "bittensor.cli"): bittensor.logging.debug("closing subtensor connection") @staticmethod - def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): + def _run(cli: "bittensor.cli", subtensor: "bittensor.Subtensor"): r"""Set weights for root network.""" wallet = bittensor.wallet(config=cli.config) - subnets: List[bittensor.SubnetInfo] = subtensor.get_all_subnets_info() + subnets: list[bittensor.SubnetInfo] = subtensor.get_all_subnets_info() # Get values if not set. if not cli.config.is_set("netuids"): @@ -506,10 +499,7 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): ", ".join( map( str, - [ - "{:.2f}".format(float(1 / len(subnets))) - for subnet in subnets - ][:3], + [f"{float(1 / len(subnets)):.2f}" for subnet in subnets][:3], ) ) + " ..." @@ -593,7 +583,7 @@ class RootGetWeightsCommand: def run(cli: "bittensor.cli"): r"""Get weights for root network.""" try: - subtensor: "bittensor.subtensor" = bittensor.subtensor( + subtensor: bittensor.Subtensor = bittensor.Subtensor( config=cli.config, log_verbose=False ) RootGetWeightsCommand._run(cli, subtensor) @@ -603,7 +593,7 @@ def run(cli: "bittensor.cli"): bittensor.logging.debug("closing subtensor connection") @staticmethod - def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): + def _run(cli: "bittensor.cli", subtensor: "bittensor.Subtensor"): r"""Get weights for root network.""" weights = subtensor.weights(0) @@ -655,7 +645,7 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): for netuid in netuids: if netuid in uid_weights: normalized_weight = uid_weights[netuid] - row.append("{:0.2f}%".format(normalized_weight * 100)) + row.append(f"{normalized_weight * 100:0.2f}%") else: row.append("-") table.add_row(*row) diff --git a/bittensor/commands/senate.py b/bittensor/commands/senate.py index 03a73cde5b..7ac3f7f531 100644 --- a/bittensor/commands/senate.py +++ b/bittensor/commands/senate.py @@ -17,12 +17,15 @@ import argparse -import bittensor -from rich.prompt import Prompt, Confirm +from typing import Optional + +from rich.prompt import Confirm, Prompt from rich.table import Table -from typing import Optional, Dict -from .utils import get_delegates_details, DelegatesDetails + +import bittensor + from . import defaults +from .utils import DelegatesDetails, get_delegates_details console = bittensor.__console__ @@ -50,7 +53,7 @@ def run(cli: "bittensor.cli"): r"""View Bittensor's governance protocol proposals""" try: config = cli.config.copy() - subtensor: "bittensor.subtensor" = bittensor.subtensor( + subtensor: bittensor.Subtensor = bittensor.Subtensor( config=config, log_verbose=False ) SenateCommand._run(cli, subtensor) @@ -60,17 +63,15 @@ def run(cli: "bittensor.cli"): bittensor.logging.debug("closing subtensor connection") @staticmethod - def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): + def _run(cli: "bittensor.cli", subtensor: "bittensor.Subtensor"): r"""View Bittensor's governance protocol proposals""" console = bittensor.__console__ console.print( - ":satellite: Syncing with chain: [white]{}[/white] ...".format( - cli.config.subtensor.network - ) + f":satellite: Syncing with chain: [white]{cli.config.subtensor.network}[/white] ..." ) senate_members = subtensor.get_senate_members() - delegate_info: Optional[Dict[str, DelegatesDetails]] = get_delegates_details( + delegate_info: Optional[dict[str, DelegatesDetails]] = get_delegates_details( url=bittensor.__delegates_details_url__ ) @@ -189,7 +190,7 @@ def run(cli: "bittensor.cli"): r"""View Bittensor's governance protocol proposals""" try: config = cli.config.copy() - subtensor: "bittensor.subtensor" = bittensor.subtensor( + subtensor: bittensor.Subtensor = bittensor.Subtensor( config=config, log_verbose=False ) ProposalsCommand._run(cli, subtensor) @@ -199,28 +200,22 @@ def run(cli: "bittensor.cli"): bittensor.logging.debug("closing subtensor connection") @staticmethod - def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): + def _run(cli: "bittensor.cli", subtensor: "bittensor.Subtensor"): r"""View Bittensor's governance protocol proposals""" console = bittensor.__console__ console.print( - ":satellite: Syncing with chain: [white]{}[/white] ...".format( - subtensor.network - ) + f":satellite: Syncing with chain: [white]{subtensor.network}[/white] ..." ) senate_members = subtensor.get_senate_members() proposals = subtensor.get_proposals() - registered_delegate_info: Optional[Dict[str, DelegatesDetails]] = ( + registered_delegate_info: Optional[dict[str, DelegatesDetails]] = ( get_delegates_details(url=bittensor.__delegates_details_url__) ) table = Table(show_footer=False) - table.title = ( - "[white]Proposals\t\tActive Proposals: {}\t\tSenate Size: {}".format( - len(proposals), len(senate_members) - ) - ) + table.title = f"[white]Proposals\t\tActive Proposals: {len(proposals)}\t\tSenate Size: {len(senate_members)}" table.add_column( "[overline white]HASH", footer_style="overline white", @@ -312,7 +307,7 @@ def run(cli: "bittensor.cli"): r"""View Bittensor's governance protocol proposals active votes""" try: config = cli.config.copy() - subtensor: "bittensor.subtensor" = bittensor.subtensor( + subtensor: bittensor.Subtensor = bittensor.Subtensor( config=config, log_verbose=False ) ShowVotesCommand._run(cli, subtensor) @@ -322,12 +317,10 @@ def run(cli: "bittensor.cli"): bittensor.logging.debug("closing subtensor connection") @staticmethod - def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): + def _run(cli: "bittensor.cli", subtensor: "bittensor.Subtensor"): r"""View Bittensor's governance protocol proposals active votes""" console.print( - ":satellite: Syncing with chain: [white]{}[/white] ...".format( - cli.config.subtensor.network - ) + f":satellite: Syncing with chain: [white]{cli.config.subtensor.network}[/white] ..." ) proposal_hash = cli.config.proposal_hash @@ -338,16 +331,16 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): return proposal_vote_data = subtensor.get_vote_data(proposal_hash) - if proposal_vote_data == None: + if proposal_vote_data is None: console.print(":cross_mark: [red]Failed[/red]: Proposal not found.") return - registered_delegate_info: Optional[Dict[str, DelegatesDetails]] = ( + registered_delegate_info: Optional[dict[str, DelegatesDetails]] = ( get_delegates_details(url=bittensor.__delegates_details_url__) ) table = Table(show_footer=False) - table.title = "[white]Votes for Proposal {}".format(proposal_hash) + table.title = f"[white]Votes for Proposal {proposal_hash}" table.add_column( "[overline white]ADDRESS", footer_style="overline white", @@ -416,7 +409,7 @@ def run(cli: "bittensor.cli"): r"""Register to participate in Bittensor's governance protocol proposals""" try: config = cli.config.copy() - subtensor: "bittensor.subtensor" = bittensor.subtensor( + subtensor: bittensor.Subtensor = bittensor.Subtensor( config=config, log_verbose=False ) SenateRegisterCommand._run(cli, subtensor) @@ -426,7 +419,7 @@ def run(cli: "bittensor.cli"): bittensor.logging.debug("closing subtensor connection") @staticmethod - def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): + def _run(cli: "bittensor.cli", subtensor: "bittensor.Subtensor"): r"""Register to participate in Bittensor's governance protocol proposals""" wallet = bittensor.wallet(config=cli.config) @@ -437,17 +430,13 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): # Check if the hotkey is a delegate. if not subtensor.is_hotkey_delegate(wallet.hotkey.ss58_address): console.print( - "Aborting: Hotkey {} isn't a delegate.".format( - wallet.hotkey.ss58_address - ) + f"Aborting: Hotkey {wallet.hotkey.ss58_address} isn't a delegate." ) return if subtensor.is_senate_member(hotkey_ss58=wallet.hotkey.ss58_address): console.print( - "Aborting: Hotkey {} is already a senate member.".format( - wallet.hotkey.ss58_address - ) + f"Aborting: Hotkey {wallet.hotkey.ss58_address} is already a senate member." ) return @@ -498,7 +487,7 @@ def run(cli: "bittensor.cli"): r"""Discard membership in Bittensor's governance protocol proposals""" try: config = cli.config.copy() - subtensor: "bittensor.subtensor" = bittensor.subtensor( + subtensor: bittensor.Subtensor = bittensor.Subtensor( config=config, log_verbose=False ) SenateLeaveCommand._run(cli, subtensor) @@ -518,9 +507,7 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.cli"): if not subtensor.is_senate_member(hotkey_ss58=wallet.hotkey.ss58_address): console.print( - "Aborting: Hotkey {} isn't a senate member.".format( - wallet.hotkey.ss58_address - ) + f"Aborting: Hotkey {wallet.hotkey.ss58_address} isn't a senate member." ) return @@ -572,7 +559,7 @@ def run(cli: "bittensor.cli"): r"""Vote in Bittensor's governance protocol proposals""" try: config = cli.config.copy() - subtensor: "bittensor.subtensor" = bittensor.subtensor( + subtensor: bittensor.Subtensor = bittensor.Subtensor( config=config, log_verbose=False ) VoteCommand._run(cli, subtensor) @@ -582,7 +569,7 @@ def run(cli: "bittensor.cli"): bittensor.logging.debug("closing subtensor connection") @staticmethod - def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): + def _run(cli: "bittensor.cli", subtensor: "bittensor.Subtensor"): r"""Vote in Bittensor's governance protocol proposals""" wallet = bittensor.wallet(config=cli.config) @@ -595,9 +582,7 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): if not subtensor.is_senate_member(hotkey_ss58=wallet.hotkey.ss58_address): console.print( - "Aborting: Hotkey {} isn't a senate member.".format( - wallet.hotkey.ss58_address - ) + f"Aborting: Hotkey {wallet.hotkey.ss58_address} isn't a senate member." ) return @@ -606,7 +591,7 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): wallet.coldkey vote_data = subtensor.get_vote_data(proposal_hash) - if vote_data == None: + if vote_data is None: console.print(":cross_mark: [red]Failed[/red]: Proposal not found.") return diff --git a/bittensor/commands/stake.py b/bittensor/commands/stake.py index 1bc2cf2786..48ec36cee3 100644 --- a/bittensor/commands/stake.py +++ b/bittensor/commands/stake.py @@ -18,7 +18,7 @@ import argparse import os import sys -from typing import List, Union, Optional, Dict, Tuple +from typing import Optional, Union from rich.prompt import Confirm, Prompt from rich.table import Table @@ -26,12 +26,13 @@ import bittensor from bittensor.utils.balance import Balance + +from . import defaults from .utils import ( - get_hotkey_wallets_for_wallet, - get_delegates_details, DelegatesDetails, + get_delegates_details, + get_hotkey_wallets_for_wallet, ) -from . import defaults console = bittensor.__console__ @@ -70,7 +71,7 @@ def run(cli: "bittensor.cli"): r"""Stake token of amount to hotkey(s).""" try: config = cli.config.copy() - subtensor: "bittensor.subtensor" = bittensor.subtensor( + subtensor: bittensor.Subtensor = bittensor.Subtensor( config=config, log_verbose=False ) StakeCommand._run(cli, subtensor) @@ -80,20 +81,20 @@ def run(cli: "bittensor.cli"): bittensor.logging.debug("closing subtensor connection") @staticmethod - def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): + def _run(cli: "bittensor.cli", subtensor: "bittensor.Subtensor"): r"""Stake token of amount to hotkey(s).""" config = cli.config.copy() wallet = bittensor.wallet(config=config) # Get the hotkey_names (if any) and the hotkey_ss58s. - hotkeys_to_stake_to: List[Tuple[Optional[str], str]] = [] + hotkeys_to_stake_to: list[tuple[Optional[str], str]] = [] if config.get("all_hotkeys"): # Stake to all hotkeys. - all_hotkeys: List[bittensor.wallet] = get_hotkey_wallets_for_wallet( + all_hotkeys: list[bittensor.wallet] = get_hotkey_wallets_for_wallet( wallet=wallet ) # Get the hotkeys to exclude. (d)efault to no exclusions. - hotkeys_to_exclude: List[str] = cli.config.get("hotkeys", d=[]) + hotkeys_to_exclude: list[str] = cli.config.get("hotkeys", d=[]) # Exclude hotkeys that are specified. hotkeys_to_stake_to = [ (wallet.hotkey_str, wallet.hotkey.ss58_address) @@ -138,10 +139,10 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): # Get coldkey balance wallet_balance: Balance = subtensor.get_balance(wallet.coldkeypub.ss58_address) - final_hotkeys: List[Tuple[str, str]] = [] - final_amounts: List[Union[float, Balance]] = [] + final_hotkeys: list[tuple[str, str]] = [] + final_amounts: list[Union[float, Balance]] = [] for hotkey in tqdm(hotkeys_to_stake_to): - hotkey: Tuple[Optional[str], str] # (hotkey_name (or None), hotkey_ss58) + hotkey: tuple[Optional[str], str] # (hotkey_name (or None), hotkey_ss58) if not subtensor.is_hotkey_registered_any(hotkey_ss58=hotkey[1]): # Hotkey is not registered. if len(hotkeys_to_stake_to) == 1: @@ -250,9 +251,7 @@ def check_config(cls, config: "bittensor.config"): config.amount = float(amount) except ValueError: console.print( - ":cross_mark:[red]Invalid Tao amount[/red] [bold white]{}[/bold white]".format( - amount - ) + f":cross_mark:[red]Invalid Tao amount[/red] [bold white]{amount}[/bold white]" ) sys.exit() else: @@ -299,7 +298,7 @@ def add_args(cls, parser: argparse.ArgumentParser): bittensor.subtensor.add_args(stake_parser) -def _get_coldkey_wallets_for_path(path: str) -> List["bittensor.wallet"]: +def _get_coldkey_wallets_for_path(path: str) -> list["bittensor.wallet"]: try: wallet_names = next(os.walk(os.path.expanduser(path)))[1] return [bittensor.wallet(path=path, name=name) for name in wallet_names] @@ -309,7 +308,7 @@ def _get_coldkey_wallets_for_path(path: str) -> List["bittensor.wallet"]: return wallets -def _get_hotkey_wallets_for_wallet(wallet) -> List["bittensor.wallet"]: +def _get_hotkey_wallets_for_wallet(wallet) -> list["bittensor.wallet"]: hotkey_wallets = [] hotkeys_path = wallet.path + "/" + wallet.name + "/hotkeys" try: @@ -365,7 +364,7 @@ class StakeShow: def run(cli: "bittensor.cli"): r"""Show all stake accounts.""" try: - subtensor: "bittensor.subtensor" = bittensor.subtensor( + subtensor: bittensor.Subtensor = bittensor.Subtensor( config=cli.config, log_verbose=False ) StakeShow._run(cli, subtensor) @@ -375,19 +374,19 @@ def run(cli: "bittensor.cli"): bittensor.logging.debug("closing subtensor connection") @staticmethod - def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): + def _run(cli: "bittensor.cli", subtensor: "bittensor.Subtensor"): r"""Show all stake accounts.""" - if cli.config.get("all", d=False) == True: + if cli.config.get("all", d=False) is True: wallets = _get_coldkey_wallets_for_path(cli.config.wallet.path) else: wallets = [bittensor.wallet(config=cli.config)] - registered_delegate_info: Optional[Dict[str, DelegatesDetails]] = ( + registered_delegate_info: Optional[dict[str, DelegatesDetails]] = ( get_delegates_details(url=bittensor.__delegates_details_url__) ) def get_stake_accounts( wallet, subtensor - ) -> Dict[str, Dict[str, Union[str, Balance]]]: + ) -> dict[str, dict[str, Union[str, Balance]]]: """Get stake account details for the given wallet. Args: @@ -416,7 +415,7 @@ def get_stake_accounts( def get_stakes_from_hotkeys( subtensor, wallet - ) -> Dict[str, Dict[str, Union[str, Balance]]]: + ) -> dict[str, dict[str, Union[str, Balance]]]: """Fetch stakes from hotkeys for the provided wallet. Args: @@ -449,7 +448,7 @@ def get_stakes_from_hotkeys( def get_stakes_from_delegates( subtensor, wallet - ) -> Dict[str, Dict[str, Union[str, Balance]]]: + ) -> dict[str, dict[str, Union[str, Balance]]]: """Fetch stakes from delegates for the provided wallet. Args: @@ -481,7 +480,7 @@ def get_stakes_from_delegates( def get_all_wallet_accounts( wallets, subtensor, - ) -> List[Dict[str, Dict[str, Union[str, Balance]]]]: + ) -> list[dict[str, dict[str, Union[str, Balance]]]]: """Fetch stake accounts for all provided wallets using a ThreadPool. Args: @@ -515,7 +514,7 @@ def get_all_wallet_accounts( ) table.add_column( "[overline white]Balance", - "\u03c4{:.5f}".format(total_balance), + f"\u03c4{total_balance:.5f}", footer_style="overline white", style="green", ) @@ -524,13 +523,13 @@ def get_all_wallet_accounts( ) table.add_column( "[overline white]Stake", - "\u03c4{:.5f}".format(total_stake), + f"\u03c4{total_stake:.5f}", footer_style="overline white", style="green", ) table.add_column( "[overline white]Rate", - "\u03c4{:.5f}/d".format(total_rate), + f"\u03c4{total_rate:.5f}/d", footer_style="overline white", style="green", ) diff --git a/bittensor/commands/transfer.py b/bittensor/commands/transfer.py index 24c6e78402..c85db9a9e9 100644 --- a/bittensor/commands/transfer.py +++ b/bittensor/commands/transfer.py @@ -16,10 +16,13 @@ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. -import sys import argparse -import bittensor +import sys + from rich.prompt import Prompt + +import bittensor + from . import defaults console = bittensor.__console__ @@ -53,7 +56,7 @@ class TransferCommand: def run(cli: "bittensor.cli"): r"""Transfer token of amount to destination.""" try: - subtensor: "bittensor.subtensor" = bittensor.subtensor( + subtensor: bittensor.Subtensor = bittensor.Subtensor( config=cli.config, log_verbose=False ) TransferCommand._run(cli, subtensor) @@ -63,7 +66,7 @@ def run(cli: "bittensor.cli"): bittensor.logging.debug("closing subtensor connection") @staticmethod - def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): + def _run(cli: "bittensor.cli", subtensor: "bittensor.Subtensor"): r"""Transfer token of amount to destination.""" wallet = bittensor.wallet(config=cli.config) subtensor.transfer( @@ -91,11 +94,11 @@ def check_config(config: "bittensor.config"): # Get current balance and print to user. if not config.no_prompt: wallet = bittensor.wallet(config=config) - subtensor = bittensor.subtensor(config=config, log_verbose=False) + subtensor = bittensor.Subtensor(config=config, log_verbose=False) with bittensor.__console__.status(":satellite: Checking Balance..."): account_balance = subtensor.get_balance(wallet.coldkeypub.ss58_address) bittensor.__console__.print( - "Balance: [green]{}[/green]".format(account_balance) + f"Balance: [green]{account_balance}[/green]" ) # Get amount. @@ -106,16 +109,12 @@ def check_config(config: "bittensor.config"): config.amount = float(amount) except ValueError: console.print( - ":cross_mark:[red] Invalid TAO amount[/red] [bold white]{}[/bold white]".format( - amount - ) + f":cross_mark:[red] Invalid TAO amount[/red] [bold white]{amount}[/bold white]" ) sys.exit() else: console.print( - ":cross_mark:[red] Invalid TAO amount[/red] [bold white]{}[/bold white]".format( - amount - ) + f":cross_mark:[red] Invalid TAO amount[/red] [bold white]{amount}[/bold white]" ) sys.exit(1) diff --git a/bittensor/commands/unstake.py b/bittensor/commands/unstake.py index 87d13aab91..3525863783 100644 --- a/bittensor/commands/unstake.py +++ b/bittensor/commands/unstake.py @@ -16,13 +16,16 @@ # DEALINGS IN THE SOFTWARE. import sys -import bittensor -from tqdm import tqdm +from typing import Optional, Union + from rich.prompt import Confirm, Prompt +from tqdm import tqdm + +import bittensor from bittensor.utils.balance import Balance -from typing import List, Union, Optional, Tuple -from .utils import get_hotkey_wallets_for_wallet + from . import defaults +from .utils import get_hotkey_wallets_for_wallet console = bittensor.__console__ @@ -155,7 +158,7 @@ def run(cli: "bittensor.cli"): r"""Unstake token of amount from hotkey(s).""" try: config = cli.config.copy() - subtensor: "bittensor.subtensor" = bittensor.subtensor( + subtensor: bittensor.Subtensor = bittensor.Subtensor( config=config, log_verbose=False ) UnStakeCommand._run(cli, subtensor) @@ -165,23 +168,23 @@ def run(cli: "bittensor.cli"): bittensor.logging.debug("closing subtensor connection") @staticmethod - def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): + def _run(cli: "bittensor.cli", subtensor: "bittensor.Subtensor"): r"""Unstake token of amount from hotkey(s).""" config = cli.config.copy() wallet = bittensor.wallet(config=config) # Get the hotkey_names (if any) and the hotkey_ss58s. - hotkeys_to_unstake_from: List[Tuple[Optional[str], str]] = [] + hotkeys_to_unstake_from: list[tuple[Optional[str], str]] = [] if cli.config.get("hotkey_ss58address"): # Stake to specific hotkey. hotkeys_to_unstake_from = [(None, cli.config.get("hotkey_ss58address"))] elif cli.config.get("all_hotkeys"): # Stake to all hotkeys. - all_hotkeys: List[bittensor.wallet] = get_hotkey_wallets_for_wallet( + all_hotkeys: list[bittensor.wallet] = get_hotkey_wallets_for_wallet( wallet=wallet ) # Get the hotkeys to exclude. (d)efault to no exclusions. - hotkeys_to_exclude: List[str] = cli.config.get("hotkeys", d=[]) + hotkeys_to_exclude: list[str] = cli.config.get("hotkeys", d=[]) # Exclude hotkeys that are specified. hotkeys_to_unstake_from = [ (wallet.hotkey_str, wallet.hotkey.ss58_address) @@ -226,17 +229,17 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): (None, bittensor.wallet(config=cli.config).hotkey.ss58_address) ] - final_hotkeys: List[Tuple[str, str]] = [] - final_amounts: List[Union[float, Balance]] = [] + final_hotkeys: list[tuple[str, str]] = [] + final_amounts: list[Union[float, Balance]] = [] for hotkey in tqdm(hotkeys_to_unstake_from): - hotkey: Tuple[Optional[str], str] # (hotkey_name (or None), hotkey_ss58) + hotkey: tuple[Optional[str], str] # (hotkey_name (or None), hotkey_ss58) unstake_amount_tao: float = cli.config.get( "amount" ) # The amount specified to unstake. hotkey_stake: Balance = subtensor.get_stake_for_coldkey_and_hotkey( hotkey_ss58=hotkey[1], coldkey_ss58=wallet.coldkeypub.ss58_address ) - if unstake_amount_tao == None: + if unstake_amount_tao is None: unstake_amount_tao = hotkey_stake.tao if cli.config.get("max_stake"): # Get the current stake of the hotkey from this coldkey. diff --git a/bittensor/commands/utils.py b/bittensor/commands/utils.py index 4ea8fa3dd1..1e8ee210e8 100644 --- a/bittensor/commands/utils.py +++ b/bittensor/commands/utils.py @@ -15,14 +15,17 @@ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. -import sys import os -import bittensor +import sys +from dataclasses import dataclass +from typing import Any, Optional + import requests -from bittensor.utils.registration import torch -from typing import List, Dict, Any, Optional from rich.prompt import Confirm, PromptBase -from dataclasses import dataclass + +import bittensor +from bittensor.utils.registration import torch + from . import defaults console = bittensor.__console__ @@ -45,7 +48,7 @@ def check_choice(self, value: str) -> bool: def check_netuid_set( config: "bittensor.config", - subtensor: "bittensor.subtensor", + subtensor: "bittensor.Subtensor", allow_none: bool = False, ): if subtensor.network != "nakamoto": @@ -72,7 +75,7 @@ def check_netuid_set( netuid = netuid[0] try: config.netuid = int(netuid) - except: + except: # noqa: E722 # FIXME: This is a broad exception catch, should be narrowed down. raise ValueError('netuid must be an integer or "None" (if applicable)') @@ -90,15 +93,15 @@ def check_for_cuda_reg_config(config: "bittensor.config") -> None: config.pow_register.cuda.use_cuda and config.pow_register.cuda.get("dev_id") is None ): - devices: List[str] = [str(x) for x in range(torch.cuda.device_count())] - device_names: List[str] = [ + devices: list[str] = [str(x) for x in range(torch.cuda.device_count())] + device_names: list[str] = [ torch.cuda.get_device_name(x) for x in range(torch.cuda.device_count()) ] console.print("Available CUDA devices:") choices_str: str = "" for i, device in enumerate(devices): - choices_str += " {}: {}\n".format(device, device_names[i]) + choices_str += f" {device}: {device_names[i]}\n" console.print(choices_str) dev_id = IntListPrompt.ask( "Which GPU(s) would you like to use? Please list one, or comma-separated", @@ -117,9 +120,7 @@ def check_for_cuda_reg_config(config: "bittensor.config") -> None: ] except ValueError: console.log( - ":cross_mark:[red]Invalid GPU device[/red] [bold white]{}[/bold white]\nAvailable CUDA devices:{}".format( - dev_id, choices_str - ) + f":cross_mark:[red]Invalid GPU device[/red] [bold white]{dev_id}[/bold white]\nAvailable CUDA devices:{choices_str}" ) sys.exit(1) config.pow_register.cuda.dev_id = dev_id @@ -129,7 +130,7 @@ def check_for_cuda_reg_config(config: "bittensor.config") -> None: config.pow_register.cuda.use_cuda = defaults.pow_register.cuda.use_cuda -def get_hotkey_wallets_for_wallet(wallet) -> List["bittensor.wallet"]: +def get_hotkey_wallets_for_wallet(wallet) -> list["bittensor.wallet"]: hotkey_wallets = [] hotkeys_path = wallet.path + "/" + wallet.name + "/hotkeys" try: @@ -151,7 +152,7 @@ def get_hotkey_wallets_for_wallet(wallet) -> List["bittensor.wallet"]: return hotkey_wallets -def get_coldkey_wallets_for_path(path: str) -> List["bittensor.wallet"]: +def get_coldkey_wallets_for_path(path: str) -> list["bittensor.wallet"]: try: wallet_names = next(os.walk(os.path.expanduser(path)))[1] return [bittensor.wallet(path=path, name=name) for name in wallet_names] @@ -161,7 +162,7 @@ def get_coldkey_wallets_for_path(path: str) -> List["bittensor.wallet"]: return wallets -def get_all_wallets_for_path(path: str) -> List["bittensor.wallet"]: +def get_all_wallets_for_path(path: str) -> list["bittensor.wallet"]: all_wallets = [] cold_wallets = get_coldkey_wallets_for_path(path) for cold_wallet in cold_wallets: @@ -175,7 +176,7 @@ def get_all_wallets_for_path(path: str) -> List["bittensor.wallet"]: def filter_netuids_by_registered_hotkeys( cli, subtensor, netuids, all_hotkeys -) -> List[int]: +) -> list[int]: netuids_with_registered_hotkeys = [] for wallet in all_hotkeys: netuids_list = subtensor.get_netuids_for_hotkey(wallet.hotkey.ss58_address) @@ -184,7 +185,7 @@ def filter_netuids_by_registered_hotkeys( ) netuids_with_registered_hotkeys.extend(netuids_list) - if cli.config.netuids == None or cli.config.netuids == []: + if cli.config.netuids is None or cli.config.netuids == []: netuids = netuids_with_registered_hotkeys elif cli.config.netuids != []: @@ -202,7 +203,7 @@ class DelegatesDetails: signature: str @classmethod - def from_json(cls, json: Dict[str, any]) -> "DelegatesDetails": + def from_json(cls, json: dict[str, any]) -> "DelegatesDetails": return cls( name=json["name"], url=json["url"], @@ -213,11 +214,11 @@ def from_json(cls, json: Dict[str, any]) -> "DelegatesDetails": def _get_delegates_details_from_github( requests_get, url: str -) -> Dict[str, DelegatesDetails]: +) -> dict[str, DelegatesDetails]: response = requests_get(url) if response.status_code == 200: - all_delegates: Dict[str, Any] = response.json() + all_delegates: dict[str, Any] = response.json() all_delegates_details = {} for delegate_hotkey, delegates_details in all_delegates.items(): all_delegates_details[delegate_hotkey] = DelegatesDetails.from_json( @@ -228,7 +229,7 @@ def _get_delegates_details_from_github( return {} -def get_delegates_details(url: str) -> Optional[Dict[str, DelegatesDetails]]: +def get_delegates_details(url: str) -> Optional[dict[str, DelegatesDetails]]: try: return _get_delegates_details_from_github(requests.get, url) except Exception: diff --git a/bittensor/commands/wallets.py b/bittensor/commands/wallets.py index 0f665db7e4..cf3040d5b3 100644 --- a/bittensor/commands/wallets.py +++ b/bittensor/commands/wallets.py @@ -16,15 +16,18 @@ # DEALINGS IN THE SOFTWARE. import argparse -import bittensor import os import sys -from rich.prompt import Prompt, Confirm -from rich.table import Table -from typing import Optional, List, Tuple -from . import defaults +from typing import Optional + import requests +from rich.prompt import Confirm, Prompt +from rich.table import Table + +import bittensor + from ..utils import RAOPERTAO +from . import defaults class RegenColdkeyCommand: @@ -63,8 +66,8 @@ def run(cli): if cli.config.get("json"): file_name: str = cli.config.get("json") if not os.path.exists(file_name) or not os.path.isfile(file_name): - raise ValueError("File {} does not exist".format(file_name)) - with open(cli.config.get("json"), "r") as f: + raise ValueError(f"File {file_name} does not exist") + with open(cli.config.get("json")) as f: json_str = f.read() # Password can be "", assume if None json_password = cli.config.get("json_password", "") @@ -82,9 +85,9 @@ def check_config(config: "bittensor.config"): wallet_name = Prompt.ask("Enter wallet name", default=defaults.wallet.name) config.wallet.name = str(wallet_name) if ( - config.mnemonic == None - and config.get("seed", d=None) == None - and config.get("json", d=None) == None + config.mnemonic is None + and config.get("seed", d=None) is None + and config.get("json", d=None) is None ): prompt_answer = Prompt.ask("Enter mnemonic, seed, or json file location") if prompt_answer.startswith("0x"): @@ -94,7 +97,7 @@ def check_config(config: "bittensor.config"): else: config.json = prompt_answer - if config.get("json", d=None) and config.get("json_password", d=None) == None: + if config.get("json", d=None) and config.get("json_password", d=None) is None: config.json_password = Prompt.ask( "Enter json backup password", password=True ) @@ -188,7 +191,7 @@ def check_config(config: "bittensor.config"): if not config.is_set("wallet.name") and not config.no_prompt: wallet_name = Prompt.ask("Enter wallet name", default=defaults.wallet.name) config.wallet.name = str(wallet_name) - if config.ss58_address == None and config.public_key_hex == None: + if config.ss58_address is None and config.public_key_hex is None: prompt_answer = Prompt.ask( "Enter the ss58_address or the public key in hex" ) @@ -275,8 +278,8 @@ def run(cli): if cli.config.get("json"): file_name: str = cli.config.get("json") if not os.path.exists(file_name) or not os.path.isfile(file_name): - raise ValueError("File {} does not exist".format(file_name)) - with open(cli.config.get("json"), "r") as f: + raise ValueError(f"File {file_name} does not exist") + with open(cli.config.get("json")) as f: json_str = f.read() # Password can be "", assume if None @@ -300,9 +303,9 @@ def check_config(config: "bittensor.config"): hotkey = Prompt.ask("Enter hotkey name", default=defaults.wallet.hotkey) config.wallet.hotkey = str(hotkey) if ( - config.mnemonic == None - and config.get("seed", d=None) == None - and config.get("json", d=None) == None + config.mnemonic is None + and config.get("seed", d=None) is None + and config.get("json", d=None) is None ): prompt_answer = Prompt.ask("Enter mnemonic, seed, or json file location") if prompt_answer.startswith("0x"): @@ -312,7 +315,7 @@ def check_config(config: "bittensor.config"): else: config.json = prompt_answer - if config.get("json", d=None) and config.get("json_password", d=None) == None: + if config.get("json", d=None) and config.get("json_password", d=None) is None: config.json_password = Prompt.ask( "Enter json backup password", password=True ) @@ -614,7 +617,7 @@ def add_args(parser: argparse.ArgumentParser): bittensor.subtensor.add_args(new_coldkey_parser) -def _get_coldkey_wallets_for_path(path: str) -> List["bittensor.wallet"]: +def _get_coldkey_wallets_for_path(path: str) -> list["bittensor.wallet"]: """Get all coldkey wallet names from path.""" try: wallet_names = next(os.walk(os.path.expanduser(path)))[1] @@ -652,7 +655,7 @@ class UpdateWalletCommand: def run(cli): """Check if any of the wallets needs an update.""" config = cli.config.copy() - if config.get("all", d=False) == True: + if config.get("all", d=False) is True: wallets = _get_coldkey_wallets_for_path(config.wallet.path) else: wallets = [bittensor.wallet(config=config)] @@ -673,14 +676,14 @@ def add_args(parser: argparse.ArgumentParser): @staticmethod def check_config(config: "bittensor.Config"): - if config.get("all", d=False) == False: + if config.get("all", d=False) is False: if not config.no_prompt: if Confirm.ask("Do you want to update all legacy wallets?"): config["all"] = True # Ask the user to specify the wallet if the wallet name is not clear. if ( - config.get("all", d=False) == False + config.get("all", d=False) is False and config.wallet.get("name") == bittensor.defaults.wallet.name and not config.no_prompt ): @@ -690,7 +693,7 @@ def check_config(config: "bittensor.Config"): config.wallet.name = str(wallet_name) -def _get_coldkey_ss58_addresses_for_path(path: str) -> Tuple[List[str], List[str]]: +def _get_coldkey_ss58_addresses_for_path(path: str) -> tuple[list[str], list[str]]: """Get all coldkey ss58 addresses from path.""" def list_coldkeypub_files(dir_path): @@ -763,7 +766,7 @@ class WalletBalanceCommand: def run(cli: "bittensor.cli"): """Check the balance of the wallet.""" try: - subtensor: "bittensor.subtensor" = bittensor.subtensor( + subtensor: bittensor.Subtensor = bittensor.Subtensor( config=cli.config, log_verbose=False ) WalletBalanceCommand._run(cli, subtensor) @@ -773,8 +776,8 @@ def run(cli: "bittensor.cli"): bittensor.logging.debug("closing subtensor connection") @staticmethod - def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): - wallet = bittensor.wallet(config=cli.config) + def _run(cli: "bittensor.cli", subtensor: "bittensor.Subtensor"): + bittensor.wallet(config=cli.config) wallet_names = [] coldkeys = [] @@ -1013,7 +1016,7 @@ def check_config(config: "bittensor.config"): config.wallet.name = str(wallet_name) -def get_wallet_transfers(wallet_address) -> List[dict]: +def get_wallet_transfers(wallet_address) -> list[dict]: """Get all transfers associated with the provided wallet address.""" variables = { @@ -1080,7 +1083,7 @@ def create_transfer_history_table(transfers): for item in transfers: try: tao_amount = int(item["amount"]) / RAOPERTAO - except: + except: # noqa: E722 # FIXME: This is a broad exception catch, should be narrowed down. tao_amount = item["amount"] table.add_row( item["id"], diff --git a/bittensor/commands/weights.py b/bittensor/commands/weights.py index ac4d9dfc36..84bcd845e2 100644 --- a/bittensor/commands/weights.py +++ b/bittensor/commands/weights.py @@ -24,10 +24,11 @@ import re import numpy as np -from rich.prompt import Prompt, Confirm +from rich.prompt import Confirm, Prompt import bittensor import bittensor.utils.weight_utils as weight_utils + from . import defaults # type: ignore @@ -54,7 +55,7 @@ class CommitWeightCommand: def run(cli: "bittensor.cli"): r"""Commit weights for a specific subnet.""" try: - subtensor: "bittensor.subtensor" = bittensor.subtensor( + subtensor: bittensor.Subtensor = bittensor.Subtensor( config=cli.config, log_verbose=False ) CommitWeightCommand._run(cli, subtensor) @@ -64,19 +65,19 @@ def run(cli: "bittensor.cli"): bittensor.logging.debug("closing subtensor connection") @staticmethod - def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): + def _run(cli: "bittensor.cli", subtensor: "bittensor.Subtensor"): r"""Commit weights for a specific subnet""" wallet = bittensor.wallet(config=cli.config) # Get values if not set if not cli.config.is_set("netuid"): - cli.config.netuid = int(Prompt.ask(f"Enter netuid")) + cli.config.netuid = int(Prompt.ask("Enter netuid")) if not cli.config.is_set("uids"): - cli.config.uids = Prompt.ask(f"Enter UIDs (comma-separated)") + cli.config.uids = Prompt.ask("Enter UIDs (comma-separated)") if not cli.config.is_set("weights"): - cli.config.weights = Prompt.ask(f"Enter weights (comma-separated)") + cli.config.weights = Prompt.ask("Enter weights (comma-separated)") # Parse from string netuid = cli.config.netuid @@ -120,7 +121,7 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): # Result if success: - bittensor.__console__.print(f"Weights committed successfully") + bittensor.__console__.print("Weights committed successfully") else: bittensor.__console__.print(f"Failed to commit weights: {message}") @@ -185,7 +186,7 @@ class RevealWeightCommand: def run(cli: "bittensor.cli"): r"""Reveal weights for a specific subnet.""" try: - subtensor: "bittensor.subtensor" = bittensor.subtensor( + subtensor: bittensor.Subtensor = bittensor.Subtensor( config=cli.config, log_verbose=False ) RevealWeightCommand._run(cli, subtensor) @@ -195,22 +196,22 @@ def run(cli: "bittensor.cli"): bittensor.logging.debug("closing subtensor connection") @staticmethod - def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): + def _run(cli: "bittensor.cli", subtensor: "bittensor.Subtensor"): r"""Reveal weights for a specific subnet.""" wallet = bittensor.wallet(config=cli.config) # Get values if not set. if not cli.config.is_set("netuid"): - cli.config.netuid = int(Prompt.ask(f"Enter netuid")) + cli.config.netuid = int(Prompt.ask("Enter netuid")) if not cli.config.is_set("uids"): - cli.config.uids = Prompt.ask(f"Enter UIDs (comma-separated)") + cli.config.uids = Prompt.ask("Enter UIDs (comma-separated)") if not cli.config.is_set("weights"): - cli.config.weights = Prompt.ask(f"Enter weights (comma-separated)") + cli.config.weights = Prompt.ask("Enter weights (comma-separated)") if not cli.config.is_set("salt"): - cli.config.salt = Prompt.ask(f"Enter salt (comma-separated)") + cli.config.salt = Prompt.ask("Enter salt (comma-separated)") # Parse from string netuid = cli.config.netuid @@ -245,7 +246,7 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): ) if success: - bittensor.__console__.print(f"Weights revealed successfully") + bittensor.__console__.print("Weights revealed successfully") else: bittensor.__console__.print(f"Failed to reveal weights: {message}") diff --git a/bittensor/config.py b/bittensor/config.py index 59ad4451b8..6094dd5806 100644 --- a/bittensor/config.py +++ b/bittensor/config.py @@ -20,14 +20,15 @@ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. +import argparse +import copy import os import sys -import yaml -import copy from copy import deepcopy +from typing import Any, Optional, TypeVar + +import yaml from munch import DefaultMunch -from typing import List, Optional, Dict, Any, TypeVar, Type -import argparse class InvalidConfigFile(Exception): @@ -41,7 +42,7 @@ class config(DefaultMunch): Implementation of the config class, which manages the configuration of different Bittensor modules. """ - __is_set: Dict[str, bool] + __is_set: dict[str, bool] r""" Translates the passed parser into a nested Bittensor config. @@ -63,7 +64,7 @@ class config(DefaultMunch): def __init__( self, parser: argparse.ArgumentParser = None, - args: Optional[List[str]] = None, + args: Optional[list[str]] = None, strict: bool = False, default: Optional[Any] = None, ) -> None: @@ -71,7 +72,7 @@ def __init__( self["__is_set"] = {} - if parser == None: + if parser is None: return None # Optionally add config specific arguments @@ -81,7 +82,7 @@ def __init__( type=str, help="If set, defaults are overridden by passed file.", ) - except: + except: # noqa: E722 # FIXME: This is a broad exception catch, should be narrowed down. # this can fail if --config has already been added. pass @@ -92,7 +93,7 @@ def __init__( help="""If flagged, config will check that only exact arguments have been set.""", default=False, ) - except: + except: # noqa: E722 # FIXME: This is a broad exception catch, should be narrowed down. # this can fail if --strict has already been added. pass @@ -103,7 +104,7 @@ def __init__( help="Set ``true`` to stop cli version checking.", default=False, ) - except: + except: # noqa: E722 # FIXME: This is a broad exception catch, should be narrowed down. # this can fail if --no_version_checking has already been added. pass @@ -115,12 +116,12 @@ def __init__( help="Set ``true`` to stop cli from prompting the user.", default=False, ) - except: + except: # noqa: E722 # FIXME: This is a broad exception catch, should be narrowed down. # this can fail if --no_version_checking has already been added. pass # Get args from argv if not passed in. - if args == None: + if args is None: args = sys.argv[1:] # Check for missing required arguments before proceeding @@ -138,7 +139,7 @@ def __init__( + "/" + vars(parser.parse_known_args(args)[0])["config"] ) - except Exception as e: + except Exception: config_file_path = None # Parse args not strict @@ -148,15 +149,15 @@ def __init__( ## strict=True when passed in OR when --strict is set strict = config_params.strict or strict - if config_file_path != None: + if config_file_path is not None: config_file_path = os.path.expanduser(config_file_path) try: with open(config_file_path) as f: params_config = yaml.safe_load(f) - print("Loading config defaults from: {}".format(config_file_path)) + print(f"Loading config defaults from: {config_file_path}") parser.set_defaults(**params_config) except Exception as e: - print("Error in loading: {} using default parser settings".format(e)) + print(f"Error in loading: {e} using default parser settings") # 2. Continue with loading in params. params = config.__parse_args__(args=args, parser=parser, strict=strict) @@ -175,10 +176,10 @@ def __init__( # Only command as the arg, else no args default_param_args = ( [_config.get("command")] - if _config.get("command") != None and _config.get("subcommand") == None + if _config.get("command") is not None and _config.get("subcommand") is None else [] ) - if _config.get("command") != None and _config.get("subcommand") != None: + if _config.get("command") is not None and _config.get("subcommand") is not None: default_param_args = [_config.get("command"), _config.get("subcommand")] ## Get all args by name @@ -192,7 +193,7 @@ def __init__( parser_no_defaults._defaults.clear() # Needed for quirk of argparse ### Check for subparsers and do the same - if parser_no_defaults._subparsers != None: + if parser_no_defaults._subparsers is not None: for action in parser_no_defaults._subparsers._actions: # Should only be the "command" subparser action if isinstance(action, argparse._SubParsersAction): @@ -240,7 +241,7 @@ def __split_params__(params: argparse.Namespace, _config: "config"): keys = split_keys while len(keys) > 1: if ( - hasattr(head, keys[0]) and head[keys[0]] != None + hasattr(head, keys[0]) and head[keys[0]] is not None ): # Needs to be Config head = getattr(head, keys[0]) keys = keys[1:] @@ -253,7 +254,7 @@ def __split_params__(params: argparse.Namespace, _config: "config"): @staticmethod def __parse_args__( - args: List[str], parser: argparse.ArgumentParser = None, strict: bool = False + args: list[str], parser: argparse.ArgumentParser = None, strict: bool = False ) -> argparse.Namespace: """Parses the passed args use the passed parser. @@ -354,7 +355,7 @@ def merge(self, b): self = self._merge(self, b) @classmethod - def merge_all(cls, configs: List["config"]) -> "config": + def merge_all(cls, configs: list["config"]) -> "config": """ 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. @@ -382,14 +383,14 @@ def is_set(self, param_name: str) -> bool: return self.get("__is_set")[param_name] def __check_for_missing_required_args( - self, parser: argparse.ArgumentParser, args: List[str] - ) -> List[str]: + self, parser: argparse.ArgumentParser, args: list[str] + ) -> list[str]: required_args = self.__get_required_args_from_parser(parser) missing_args = [arg for arg in required_args if not any(arg in s for s in args)] return missing_args @staticmethod - def __get_required_args_from_parser(parser: argparse.ArgumentParser) -> List[str]: + def __get_required_args_from_parser(parser: argparse.ArgumentParser) -> list[str]: required_args = [] for action in parser._actions: if action.required: @@ -408,7 +409,7 @@ class DefaultConfig(config): """ @classmethod - def default(cls: Type[T]) -> T: + def default(cls: type[T]) -> T: """ Get default config. """ diff --git a/bittensor/dendrite.py b/bittensor/dendrite.py index 47a3ba6f95..0f439290d6 100644 --- a/bittensor/dendrite.py +++ b/bittensor/dendrite.py @@ -20,11 +20,14 @@ from __future__ import annotations import asyncio -import uuid import time +import uuid +from collections.abc import AsyncGenerator +from typing import Any + import aiohttp + import bittensor -from typing import Optional, List, Union, AsyncGenerator, Any from bittensor.utils.registration import torch, use_torch @@ -94,9 +97,7 @@ class DendriteMixin: >>> d( bittensor.axon(), bittensor.Synapse ) """ - def __init__( - self, wallet: Optional[Union[bittensor.wallet, bittensor.Keypair]] = None - ): + def __init__(self, wallet: bittensor.wallet | bittensor.Keypair | None = None): """ Initializes the Dendrite object, setting up essential properties. @@ -105,7 +106,7 @@ def __init__( The user's wallet or keypair used for signing messages. Defaults to ``None``, in which case a new :func:`bittensor.wallet().hotkey` is generated and used. """ # Initialize the parent class - super(DendriteMixin, self).__init__() + super().__init__() # Unique identifier for the instance self.uuid = str(uuid.uuid1()) @@ -120,7 +121,7 @@ def __init__( self.synapse_history: list = [] - self._session: Optional[aiohttp.ClientSession] = None + self._session: aiohttp.ClientSession | None = None @property async def session(self) -> aiohttp.ClientSession: @@ -290,8 +291,8 @@ def _log_incoming_response(self, synapse): def query( self, *args, **kwargs - ) -> List[ - Union[AsyncGenerator[Any, Any], bittensor.Synapse, bittensor.StreamingSynapse] + ) -> list[ + AsyncGenerator[Any, Any] | bittensor.Synapse | bittensor.StreamingSynapse ]: """ Makes a synchronous request to multiple target Axons and returns the server responses. @@ -311,7 +312,7 @@ def query( try: loop = asyncio.get_event_loop() result = loop.run_until_complete(self.forward(*args, **kwargs)) - except: + except: # noqa: E722 # FIXME: This is a broad exception catch, should be narrowed down. new_loop = asyncio.new_event_loop() asyncio.set_event_loop(new_loop) result = loop.run_until_complete(self.forward(*args, **kwargs)) @@ -322,17 +323,16 @@ def query( async def forward( self, - axons: Union[ - List[Union[bittensor.AxonInfo, bittensor.axon]], - Union[bittensor.AxonInfo, bittensor.axon], - ], + axons: list[bittensor.AxonInfo | bittensor.axon] + | bittensor.AxonInfo + | bittensor.axon, synapse: bittensor.Synapse = bittensor.Synapse(), timeout: float = 12, deserialize: bool = True, run_async: bool = True, streaming: bool = False, - ) -> List[ - Union[AsyncGenerator[Any, Any], bittensor.Synapse, bittensor.StreamingSynapse] + ) -> list[ + AsyncGenerator[Any, Any] | bittensor.Synapse | bittensor.StreamingSynapse ]: """ Asynchronously sends requests to one or multiple Axons and collates their responses. @@ -398,9 +398,7 @@ async def forward( async def query_all_axons( is_stream: bool, - ) -> Union[ - AsyncGenerator[Any, Any], bittensor.Synapse, bittensor.StreamingSynapse - ]: + ) -> AsyncGenerator[Any, Any] | bittensor.Synapse | bittensor.StreamingSynapse: """ Handles the processing of requests to all targeted axons, accommodating both streaming and non-streaming responses. @@ -420,9 +418,11 @@ async def query_all_axons( async def single_axon_response( target_axon, - ) -> Union[ - AsyncGenerator[Any, Any], bittensor.Synapse, bittensor.StreamingSynapse - ]: + ) -> ( + AsyncGenerator[Any, Any] + | bittensor.Synapse + | bittensor.StreamingSynapse + ): """ Manages the request and response process for a single axon, supporting both streaming and non-streaming modes. @@ -474,7 +474,7 @@ async def single_axon_response( async def call( self, - target_axon: Union[bittensor.AxonInfo, bittensor.axon], + target_axon: bittensor.AxonInfo | bittensor.axon, synapse: bittensor.Synapse = bittensor.Synapse(), timeout: float = 12.0, deserialize: bool = True, @@ -549,7 +549,7 @@ async def call( async def call_stream( self, - target_axon: Union[bittensor.AxonInfo, bittensor.axon], + target_axon: bittensor.AxonInfo | bittensor.axon, synapse: bittensor.StreamingSynapse = bittensor.Synapse(), # type: ignore timeout: float = 12.0, deserialize: bool = True, @@ -705,7 +705,7 @@ def process_server_response( # Set the attribute in the local synapse from the corresponding # attribute in the server synapse setattr(local_synapse, key, getattr(server_synapse, key)) - except: + except: # noqa: E722 # FIXME: This is a broad exception catch, should be narrowed down. # Ignore errors during attribute setting pass else: @@ -745,7 +745,7 @@ def __str__(self) -> str: Returns: str: The string representation of the Dendrite object in the format :func:`dendrite()`. """ - return "dendrite({})".format(self.keypair.ss58_address) + return f"dendrite({self.keypair.ss58_address})" def __repr__(self) -> str: """ @@ -815,13 +815,11 @@ def __del__(self): # For back-compatibility with torch -BaseModel: Union["torch.nn.Module", object] = torch.nn.Module if use_torch() else object +BaseModel: torch.nn.Module | object = torch.nn.Module if use_torch() else object class dendrite(DendriteMixin, BaseModel): # type: ignore - def __init__( - self, wallet: Optional[Union[bittensor.wallet, bittensor.Keypair]] = None - ): + def __init__(self, wallet: bittensor.wallet | bittensor.Keypair | None = None): if use_torch(): torch.nn.Module.__init__(self) DendriteMixin.__init__(self, wallet) diff --git a/bittensor/errors.py b/bittensor/errors.py index b8366ee681..6bbf3e2f89 100644 --- a/bittensor/errors.py +++ b/bittensor/errors.py @@ -120,7 +120,7 @@ class InvalidRequestNameError(Exception): class SynapseException(Exception): def __init__( - self, message="Synapse Exception", synapse: "bittensor.Synapse" | None = None + self, message="Synapse Exception", synapse: bittensor.Synapse | None = None ): self.message = message self.synapse = synapse @@ -179,7 +179,7 @@ class SynapseDendriteNoneException(SynapseException): def __init__( self, message="Synapse Dendrite is None", - synapse: "bittensor.Synapse" | None = None, + synapse: bittensor.Synapse | None = None, ): self.message = message super().__init__(self.message, synapse) diff --git a/bittensor/extrinsics/commit_weights.py b/bittensor/extrinsics/commit_weights.py index 2a526f5e96..edb49a8e19 100644 --- a/bittensor/extrinsics/commit_weights.py +++ b/bittensor/extrinsics/commit_weights.py @@ -18,22 +18,20 @@ """Module commit weights and reveal weights extrinsic.""" -from typing import Tuple, List - from rich.prompt import Confirm import bittensor def commit_weights_extrinsic( - subtensor: "bittensor.subtensor", + subtensor: "bittensor.Subtensor", wallet: "bittensor.wallet", netuid: int, commit_hash: str, wait_for_inclusion: bool = False, wait_for_finalization: bool = False, prompt: bool = False, -) -> Tuple[bool, str]: +) -> tuple[bool, str]: """ Commits a hash of the neuron's weights to the Bittensor blockchain using the provided wallet. This function is a wrapper around the `_do_commit_weights` method, handling user prompts and error messages. @@ -51,7 +49,7 @@ def commit_weights_extrinsic( This function provides a user-friendly interface for committing weights to the Bittensor blockchain, ensuring proper error handling and user interaction when required. """ - if prompt and not Confirm.ask(f"Would you like to commit weights?"): + if prompt and not Confirm.ask("Would you like to commit weights?"): return False, "User cancelled the operation." success, error_message = subtensor._do_commit_weights( @@ -71,17 +69,17 @@ def commit_weights_extrinsic( def reveal_weights_extrinsic( - subtensor: "bittensor.subtensor", + subtensor: "bittensor.Subtensor", wallet: "bittensor.wallet", netuid: int, - uids: List[int], - weights: List[int], - salt: List[int], + uids: list[int], + weights: list[int], + salt: list[int], version_key: int, wait_for_inclusion: bool = False, wait_for_finalization: bool = False, prompt: bool = False, -) -> Tuple[bool, str]: +) -> tuple[bool, str]: """ Reveals the weights for a specific subnet on the Bittensor blockchain using the provided wallet. This function is a wrapper around the `_do_reveal_weights` method, handling user prompts and error messages. @@ -103,7 +101,7 @@ def reveal_weights_extrinsic( error handling and user interaction when required. """ - if prompt and not Confirm.ask(f"Would you like to reveal weights?"): + if prompt and not Confirm.ask("Would you like to reveal weights?"): return False, "User cancelled the operation." success, error_message = subtensor._do_reveal_weights( diff --git a/bittensor/extrinsics/delegation.py b/bittensor/extrinsics/delegation.py index 9583b80a76..468ec6aae2 100644 --- a/bittensor/extrinsics/delegation.py +++ b/bittensor/extrinsics/delegation.py @@ -17,7 +17,14 @@ # DEALINGS IN THE SOFTWARE. import logging +from typing import Optional, Union + +from rich.prompt import Confirm + import bittensor +from bittensor.btlogging.defines import BITTENSOR_LOGGER_NAME +from bittensor.utils.balance import Balance + from ..errors import ( NominationError, NotDelegateError, @@ -25,16 +32,12 @@ StakeError, TakeError, ) -from rich.prompt import Confirm -from typing import Union, Optional -from bittensor.utils.balance import Balance -from bittensor.btlogging.defines import BITTENSOR_LOGGER_NAME logger = logging.getLogger(BITTENSOR_LOGGER_NAME) def nominate_extrinsic( - subtensor: "bittensor.subtensor", + subtensor: "bittensor.Subtensor", wallet: "bittensor.wallet", wait_for_finalization: bool = False, wait_for_inclusion: bool = True, @@ -52,15 +55,11 @@ def nominate_extrinsic( # Check if the hotkey is already a delegate. if subtensor.is_hotkey_delegate(wallet.hotkey.ss58_address): - logger.error( - "Hotkey {} is already a delegate.".format(wallet.hotkey.ss58_address) - ) + logger.error(f"Hotkey {wallet.hotkey.ss58_address} is already a delegate.") return False with bittensor.__console__.status( - ":satellite: Sending nominate call on [white]{}[/white] ...".format( - subtensor.network - ) + f":satellite: Sending nominate call on [white]{subtensor.network}[/white] ..." ): try: success = subtensor._do_nominate( @@ -69,7 +68,7 @@ def nominate_extrinsic( wait_for_finalization=wait_for_finalization, ) - if success == True: + if success is True: bittensor.__console__.print( ":white_heavy_check_mark: [green]Finalized[/green]" ) @@ -82,16 +81,12 @@ def nominate_extrinsic( return success except Exception as e: - bittensor.__console__.print( - ":cross_mark: [red]Failed[/red]: error:{}".format(e) - ) + bittensor.__console__.print(f":cross_mark: [red]Failed[/red]: error:{e}") bittensor.logging.warning( prefix="Set weights", suffix="Failed: " + str(e) ) except NominationError as e: - bittensor.__console__.print( - ":cross_mark: [red]Failed[/red]: error:{}".format(e) - ) + bittensor.__console__.print(f":cross_mark: [red]Failed[/red]: error:{e}") bittensor.logging.warning( prefix="Set weights", suffix="Failed: " + str(e) ) @@ -100,7 +95,7 @@ def nominate_extrinsic( def delegate_extrinsic( - subtensor: "bittensor.subtensor", + subtensor: "bittensor.Subtensor", wallet: "bittensor.wallet", delegate_ss58: Optional[str] = None, amount: Optional[Union[Balance, float]] = None, @@ -127,18 +122,18 @@ def delegate_extrinsic( # Decrypt keys, wallet.coldkey if not subtensor.is_hotkey_delegate(delegate_ss58): - raise NotDelegateError("Hotkey: {} is not a delegate.".format(delegate_ss58)) + raise NotDelegateError(f"Hotkey: {delegate_ss58} is not a delegate.") # Get state. my_prev_coldkey_balance = subtensor.get_balance(wallet.coldkey.ss58_address) - delegate_take = subtensor.get_delegate_take(delegate_ss58) + subtensor.get_delegate_take(delegate_ss58) delegate_owner = subtensor.get_hotkey_owner(delegate_ss58) my_prev_delegated_stake = subtensor.get_stake_for_coldkey_and_hotkey( coldkey_ss58=wallet.coldkeypub.ss58_address, hotkey_ss58=delegate_ss58 ) # Convert to bittensor.Balance - if amount == None: + if amount is None: # Stake it all. staking_balance = bittensor.Balance.from_tao(my_prev_coldkey_balance.tao) elif not isinstance(amount, bittensor.Balance): @@ -155,26 +150,20 @@ def delegate_extrinsic( # Check enough balance to stake. if staking_balance > my_prev_coldkey_balance: bittensor.__console__.print( - ":cross_mark: [red]Not enough balance[/red]:[bold white]\n balance:{}\n amount: {}\n coldkey: {}[/bold white]".format( - my_prev_coldkey_balance, staking_balance, wallet.name - ) + f":cross_mark: [red]Not enough balance[/red]:[bold white]\n balance:{my_prev_coldkey_balance}\n amount: {staking_balance}\n coldkey: {wallet.name}[/bold white]" ) return False # Ask before moving on. if prompt: if not Confirm.ask( - "Do you want to delegate:[bold white]\n amount: {}\n to: {}\n owner: {}[/bold white]".format( - staking_balance, delegate_ss58, delegate_owner - ) + f"Do you want to delegate:[bold white]\n amount: {staking_balance}\n to: {delegate_ss58}\n owner: {delegate_owner}[/bold white]" ): return False try: with bittensor.__console__.status( - ":satellite: Staking to: [bold white]{}[/bold white] ...".format( - subtensor.network - ) + f":satellite: Staking to: [bold white]{subtensor.network}[/bold white] ..." ): staking_response: bool = subtensor._do_delegation( wallet=wallet, @@ -184,7 +173,7 @@ def delegate_extrinsic( wait_for_finalization=wait_for_finalization, ) - if staking_response == True: # If we successfully staked. + if staking_response is True: # If we successfully staked. # We only wait here if we expect finalization. if not wait_for_finalization and not wait_for_inclusion: return True @@ -193,9 +182,7 @@ def delegate_extrinsic( ":white_heavy_check_mark: [green]Finalized[/green]" ) with bittensor.__console__.status( - ":satellite: Checking Balance on: [white]{}[/white] ...".format( - subtensor.network - ) + f":satellite: Checking Balance on: [white]{subtensor.network}[/white] ..." ): new_balance = subtensor.get_balance(address=wallet.coldkey.ss58_address) block = subtensor.get_current_block() @@ -206,14 +193,10 @@ def delegate_extrinsic( ) # Get current stake bittensor.__console__.print( - "Balance:\n [blue]{}[/blue] :arrow_right: [green]{}[/green]".format( - my_prev_coldkey_balance, new_balance - ) + f"Balance:\n [blue]{my_prev_coldkey_balance}[/blue] :arrow_right: [green]{new_balance}[/green]" ) bittensor.__console__.print( - "Stake:\n [blue]{}[/blue] :arrow_right: [green]{}[/green]".format( - my_prev_delegated_stake, new_delegate_stake - ) + f"Stake:\n [blue]{my_prev_delegated_stake}[/blue] :arrow_right: [green]{new_delegate_stake}[/green]" ) return True else: @@ -222,20 +205,18 @@ def delegate_extrinsic( ) return False - except NotRegisteredError as e: + except NotRegisteredError: bittensor.__console__.print( - ":cross_mark: [red]Hotkey: {} is not registered.[/red]".format( - wallet.hotkey_str - ) + f":cross_mark: [red]Hotkey: {wallet.hotkey_str} is not registered.[/red]" ) return False except StakeError as e: - bittensor.__console__.print(":cross_mark: [red]Stake Error: {}[/red]".format(e)) + bittensor.__console__.print(f":cross_mark: [red]Stake Error: {e}[/red]") return False def undelegate_extrinsic( - subtensor: "bittensor.subtensor", + subtensor: "bittensor.Subtensor", wallet: "bittensor.wallet", delegate_ss58: Optional[str] = None, amount: Optional[Union[Balance, float]] = None, @@ -262,18 +243,18 @@ def undelegate_extrinsic( # Decrypt keys, wallet.coldkey if not subtensor.is_hotkey_delegate(delegate_ss58): - raise NotDelegateError("Hotkey: {} is not a delegate.".format(delegate_ss58)) + raise NotDelegateError(f"Hotkey: {delegate_ss58} is not a delegate.") # Get state. my_prev_coldkey_balance = subtensor.get_balance(wallet.coldkey.ss58_address) - delegate_take = subtensor.get_delegate_take(delegate_ss58) + subtensor.get_delegate_take(delegate_ss58) delegate_owner = subtensor.get_hotkey_owner(delegate_ss58) my_prev_delegated_stake = subtensor.get_stake_for_coldkey_and_hotkey( coldkey_ss58=wallet.coldkeypub.ss58_address, hotkey_ss58=delegate_ss58 ) # Convert to bittensor.Balance - if amount == None: + if amount is None: # Stake it all. unstaking_balance = bittensor.Balance.from_tao(my_prev_delegated_stake.tao) @@ -286,26 +267,20 @@ def undelegate_extrinsic( # Check enough stake to unstake. if unstaking_balance > my_prev_delegated_stake: bittensor.__console__.print( - ":cross_mark: [red]Not enough delegated stake[/red]:[bold white]\n stake:{}\n amount: {}\n coldkey: {}[/bold white]".format( - my_prev_delegated_stake, unstaking_balance, wallet.name - ) + f":cross_mark: [red]Not enough delegated stake[/red]:[bold white]\n stake:{my_prev_delegated_stake}\n amount: {unstaking_balance}\n coldkey: {wallet.name}[/bold white]" ) return False # Ask before moving on. if prompt: if not Confirm.ask( - "Do you want to un-delegate:[bold white]\n amount: {}\n from: {}\n owner: {}[/bold white]".format( - unstaking_balance, delegate_ss58, delegate_owner - ) + f"Do you want to un-delegate:[bold white]\n amount: {unstaking_balance}\n from: {delegate_ss58}\n owner: {delegate_owner}[/bold white]" ): return False try: with bittensor.__console__.status( - ":satellite: Unstaking from: [bold white]{}[/bold white] ...".format( - subtensor.network - ) + f":satellite: Unstaking from: [bold white]{subtensor.network}[/bold white] ..." ): staking_response: bool = subtensor._do_undelegation( wallet=wallet, @@ -315,7 +290,7 @@ def undelegate_extrinsic( wait_for_finalization=wait_for_finalization, ) - if staking_response == True: # If we successfully staked. + if staking_response is True: # If we successfully staked. # We only wait here if we expect finalization. if not wait_for_finalization and not wait_for_inclusion: return True @@ -324,9 +299,7 @@ def undelegate_extrinsic( ":white_heavy_check_mark: [green]Finalized[/green]" ) with bittensor.__console__.status( - ":satellite: Checking Balance on: [white]{}[/white] ...".format( - subtensor.network - ) + f":satellite: Checking Balance on: [white]{subtensor.network}[/white] ..." ): new_balance = subtensor.get_balance(address=wallet.coldkey.ss58_address) block = subtensor.get_current_block() @@ -337,14 +310,10 @@ def undelegate_extrinsic( ) # Get current stake bittensor.__console__.print( - "Balance:\n [blue]{}[/blue] :arrow_right: [green]{}[/green]".format( - my_prev_coldkey_balance, new_balance - ) + f"Balance:\n [blue]{my_prev_coldkey_balance}[/blue] :arrow_right: [green]{new_balance}[/green]" ) bittensor.__console__.print( - "Stake:\n [blue]{}[/blue] :arrow_right: [green]{}[/green]".format( - my_prev_delegated_stake, new_delegate_stake - ) + f"Stake:\n [blue]{my_prev_delegated_stake}[/blue] :arrow_right: [green]{new_delegate_stake}[/green]" ) return True else: @@ -353,20 +322,18 @@ def undelegate_extrinsic( ) return False - except NotRegisteredError as e: + except NotRegisteredError: bittensor.__console__.print( - ":cross_mark: [red]Hotkey: {} is not registered.[/red]".format( - wallet.hotkey_str - ) + f":cross_mark: [red]Hotkey: {wallet.hotkey_str} is not registered.[/red]" ) return False except StakeError as e: - bittensor.__console__.print(":cross_mark: [red]Stake Error: {}[/red]".format(e)) + bittensor.__console__.print(f":cross_mark: [red]Stake Error: {e}[/red]") return False def decrease_take_extrinsic( - subtensor: "bittensor.subtensor", + subtensor: "bittensor.Subtensor", wallet: "bittensor.wallet", hotkey_ss58: Optional[str] = None, take: int = 0, @@ -390,9 +357,7 @@ def decrease_take_extrinsic( wallet.hotkey with bittensor.__console__.status( - ":satellite: Sending decrease_take_extrinsic call on [white]{}[/white] ...".format( - subtensor.network - ) + f":satellite: Sending decrease_take_extrinsic call on [white]{subtensor.network}[/white] ..." ): try: success = subtensor._do_decrease_take( @@ -403,7 +368,7 @@ def decrease_take_extrinsic( wait_for_finalization=wait_for_finalization, ) - if success == True: + if success is True: bittensor.__console__.print( ":white_heavy_check_mark: [green]Finalized[/green]" ) @@ -415,9 +380,7 @@ def decrease_take_extrinsic( return success except (TakeError, Exception) as e: - bittensor.__console__.print( - ":cross_mark: [red]Failed[/red]: error:{}".format(e) - ) + bittensor.__console__.print(f":cross_mark: [red]Failed[/red]: error:{e}") bittensor.logging.warning( prefix="Set weights", suffix="Failed: " + str(e) ) @@ -426,7 +389,7 @@ def decrease_take_extrinsic( def increase_take_extrinsic( - subtensor: "bittensor.subtensor", + subtensor: "bittensor.Subtensor", wallet: "bittensor.wallet", hotkey_ss58: Optional[str] = None, take: int = 0, @@ -450,9 +413,7 @@ def increase_take_extrinsic( wallet.hotkey with bittensor.__console__.status( - ":satellite: Sending increase_take_extrinsic call on [white]{}[/white] ...".format( - subtensor.network - ) + f":satellite: Sending increase_take_extrinsic call on [white]{subtensor.network}[/white] ..." ): try: success = subtensor._do_increase_take( @@ -463,7 +424,7 @@ def increase_take_extrinsic( wait_for_finalization=wait_for_finalization, ) - if success == True: + if success is True: bittensor.__console__.print( ":white_heavy_check_mark: [green]Finalized[/green]" ) @@ -475,16 +436,12 @@ def increase_take_extrinsic( return success except Exception as e: - bittensor.__console__.print( - ":cross_mark: [red]Failed[/red]: error:{}".format(e) - ) + bittensor.__console__.print(f":cross_mark: [red]Failed[/red]: error:{e}") bittensor.logging.warning( prefix="Set weights", suffix="Failed: " + str(e) ) except TakeError as e: - bittensor.__console__.print( - ":cross_mark: [red]Failed[/red]: error:{}".format(e) - ) + bittensor.__console__.print(f":cross_mark: [red]Failed[/red]: error:{e}") bittensor.logging.warning( prefix="Set weights", suffix="Failed: " + str(e) ) diff --git a/bittensor/extrinsics/network.py b/bittensor/extrinsics/network.py index 3e0c3d8661..13381d991e 100644 --- a/bittensor/extrinsics/network.py +++ b/bittensor/extrinsics/network.py @@ -16,13 +16,16 @@ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. import time -import bittensor from rich.prompt import Confirm +import bittensor + +from ..commands.network import HYPERPARAMS + def register_subnetwork_extrinsic( - subtensor: "bittensor.subtensor", + subtensor: "bittensor.Subtensor", wallet: "bittensor.wallet", wait_for_inclusion: bool = False, wait_for_finalization: bool = True, @@ -86,9 +89,7 @@ def register_subnetwork_extrinsic( response.process_events() if not response.is_success: bittensor.__console__.print( - ":cross_mark: [red]Failed[/red]: error:{}".format( - response.error_message - ) + f":cross_mark: [red]Failed[/red]: error:{response.error_message}" ) time.sleep(0.5) @@ -114,11 +115,8 @@ def find_event_attributes_in_extrinsic_receipt(response, event_name) -> list: return [-1] -from ..commands.network import HYPERPARAMS - - def set_hyperparameter_extrinsic( - subtensor: "bittensor.subtensor", + subtensor: "bittensor.Subtensor", wallet: "bittensor.wallet", netuid: int, parameter: str, @@ -158,7 +156,7 @@ def set_hyperparameter_extrinsic( wallet.coldkey # unlock coldkey extrinsic = HYPERPARAMS.get(parameter) - if extrinsic == None: + if extrinsic is None: bittensor.__console__.print( ":cross_mark: [red]Invalid hyperparameter specified.[/red]" ) @@ -198,9 +196,7 @@ def set_hyperparameter_extrinsic( response.process_events() if not response.is_success: bittensor.__console__.print( - ":cross_mark: [red]Failed[/red]: error:{}".format( - response.error_message - ) + f":cross_mark: [red]Failed[/red]: error:{response.error_message}" ) time.sleep(0.5) diff --git a/bittensor/extrinsics/prometheus.py b/bittensor/extrinsics/prometheus.py index 350817e11f..b0eca05362 100644 --- a/bittensor/extrinsics/prometheus.py +++ b/bittensor/extrinsics/prometheus.py @@ -15,14 +15,14 @@ # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. -import bittensor - import json + +import bittensor import bittensor.utils.networking as net def prometheus_extrinsic( - subtensor: "bittensor.subtensor", + subtensor: "bittensor.Subtensor", wallet: "bittensor.wallet", port: int, netuid: int, @@ -54,27 +54,23 @@ def prometheus_extrinsic( """ # ---- Get external ip ---- - if ip == None: + if ip is None: try: external_ip = net.get_external_ip() bittensor.__console__.print( - ":white_heavy_check_mark: [green]Found external ip: {}[/green]".format( - external_ip - ) + f":white_heavy_check_mark: [green]Found external ip: {external_ip}[/green]" ) bittensor.logging.success( - prefix="External IP", suffix="{}".format(external_ip) + prefix="External IP", suffix=f"{external_ip}" ) except Exception as E: raise RuntimeError( - "Unable to attain your external ip. Check your internet connection. error: {}".format( - E - ) + f"Unable to attain your external ip. Check your internet connection. error: {E}" ) from E else: external_ip = ip - call_params: "bittensor.PrometheusServeCallParams" = { + call_params: bittensor.PrometheusServeCallParams = { "version": bittensor.__version_as_int__, "ip": net.ip_to_int(external_ip), "port": port, @@ -103,9 +99,7 @@ def prometheus_extrinsic( ) bittensor.__console__.print( - ":white_heavy_check_mark: [white]Prometheus already served.[/white]".format( - external_ip - ) + ":white_heavy_check_mark: [white]Prometheus already served.[/white]".format() ) return True @@ -113,9 +107,7 @@ def prometheus_extrinsic( call_params["netuid"] = netuid with bittensor.__console__.status( - ":satellite: Serving prometheus on: [white]{}:{}[/white] ...".format( - subtensor.network, netuid - ) + f":satellite: Serving prometheus on: [white]{subtensor.network}:{netuid}[/white] ..." ): success, err = subtensor._do_serve_prometheus( wallet=wallet, @@ -125,18 +117,14 @@ def prometheus_extrinsic( ) if wait_for_inclusion or wait_for_finalization: - if success == True: + if success is True: bittensor.__console__.print( - ":white_heavy_check_mark: [green]Served prometheus[/green]\n [bold white]{}[/bold white]".format( - json.dumps(call_params, indent=4, sort_keys=True) - ) + f":white_heavy_check_mark: [green]Served prometheus[/green]\n [bold white]{json.dumps(call_params, indent=4, sort_keys=True)}[/bold white]" ) return True else: bittensor.__console__.print( - ":cross_mark: [green]Failed to serve prometheus[/green] error: {}".format( - err - ) + f":cross_mark: [green]Failed to serve prometheus[/green] error: {err}" ) return False else: diff --git a/bittensor/extrinsics/registration.py b/bittensor/extrinsics/registration.py index 879214ad92..5ee8efe87a 100644 --- a/bittensor/extrinsics/registration.py +++ b/bittensor/extrinsics/registration.py @@ -16,20 +16,22 @@ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. -import bittensor import time +from typing import Optional, Union + from rich.prompt import Confirm -from typing import List, Union, Optional, Tuple + +import bittensor from bittensor.utils.registration import ( POWSolution, create_pow, - torch, log_no_torch_error, + torch, ) def register_extrinsic( - subtensor: "bittensor.subtensor", + subtensor: "bittensor.Subtensor", wallet: "bittensor.wallet", netuid: int, wait_for_inclusion: bool = False, @@ -38,7 +40,7 @@ def register_extrinsic( max_allowed_attempts: int = 3, output_in_place: bool = True, cuda: bool = False, - dev_id: Union[List[int], int] = 0, + dev_id: Union[list[int], int] = 0, tpb: int = 256, num_processes: Optional[int] = None, update_interval: Optional[int] = None, @@ -77,9 +79,7 @@ def register_extrinsic( """ if not subtensor.subnet_exists(netuid): bittensor.__console__.print( - ":cross_mark: [red]Failed[/red]: error: [bold white]subnet:{}[/bold white] does not exist.".format( - netuid - ) + f":cross_mark: [red]Failed[/red]: error: [bold white]subnet:{netuid}[/bold white] does not exist." ) return False @@ -97,11 +97,7 @@ def register_extrinsic( if prompt: if not Confirm.ask( - "Continue Registration?\n hotkey: [bold white]{}[/bold white]\n coldkey: [bold white]{}[/bold white]\n network: [bold white]{}[/bold white]".format( - wallet.hotkey.ss58_address, - wallet.coldkeypub.ss58_address, - subtensor.network, - ) + f"Continue Registration?\n hotkey: [bold white]{wallet.hotkey.ss58_address}[/bold white]\n coldkey: [bold white]{wallet.coldkeypub.ss58_address}[/bold white]\n network: [bold white]{subtensor.network}[/bold white]" ): return False @@ -113,7 +109,7 @@ def register_extrinsic( attempts = 1 while True: bittensor.__console__.print( - ":satellite: Registering...({}/{})".format(attempts, max_allowed_attempts) + f":satellite: Registering...({attempts}/{max_allowed_attempts})" ) # Solve latest POW. if cuda: @@ -162,7 +158,7 @@ def register_extrinsic( with bittensor.__console__.status(":satellite: Submitting POW..."): # check if pow result is still valid while not pow_result.is_stale(subtensor=subtensor): - result: Tuple[bool, Optional[str]] = subtensor._do_pow_register( + result: tuple[bool, Optional[str]] = subtensor._do_pow_register( netuid=netuid, wallet=wallet, pow_result=pow_result, @@ -171,7 +167,7 @@ def register_extrinsic( ) success, err_msg = result - if success != True or success == False: + if success is not True or success is False: if "key is already registered" in err_msg: # Error meant that the key is already registered. bittensor.__console__.print( @@ -180,7 +176,7 @@ def register_extrinsic( return True bittensor.__console__.print( - ":cross_mark: [red]Failed[/red]: error:{}".format(err_msg) + f":cross_mark: [red]Failed[/red]: error:{err_msg}" ) time.sleep(0.5) @@ -211,9 +207,7 @@ def register_extrinsic( # Failed registration, retry pow attempts += 1 bittensor.__console__.print( - ":satellite: Failed registration, retrying pow ...({}/{})".format( - attempts, max_allowed_attempts - ) + f":satellite: Failed registration, retrying pow ...({attempts}/{max_allowed_attempts})" ) else: # Failed to register after max attempts. @@ -222,7 +216,7 @@ def register_extrinsic( def burned_register_extrinsic( - subtensor: "bittensor.subtensor", + subtensor: "bittensor.Subtensor", wallet: "bittensor.wallet", netuid: int, wait_for_inclusion: bool = False, @@ -248,9 +242,7 @@ def burned_register_extrinsic( """ if not subtensor.subnet_exists(netuid): bittensor.__console__.print( - ":cross_mark: [red]Failed[/red]: error: [bold white]subnet:{}[/bold white] does not exist.".format( - netuid - ) + f":cross_mark: [red]Failed[/red]: error: [bold white]subnet:{netuid}[/bold white] does not exist." ) return False @@ -268,12 +260,10 @@ def burned_register_extrinsic( if not neuron.is_null: bittensor.__console__.print( ":white_heavy_check_mark: [green]Already Registered[/green]:\n" - "uid: [bold white]{}[/bold white]\n" - "netuid: [bold white]{}[/bold white]\n" - "hotkey: [bold white]{}[/bold white]\n" - "coldkey: [bold white]{}[/bold white]".format( - neuron.uid, neuron.netuid, neuron.hotkey, neuron.coldkey - ) + f"uid: [bold white]{neuron.uid}[/bold white]\n" + f"netuid: [bold white]{neuron.netuid}[/bold white]\n" + f"hotkey: [bold white]{neuron.hotkey}[/bold white]\n" + f"coldkey: [bold white]{neuron.coldkey}[/bold white]" ) return True @@ -290,9 +280,9 @@ def burned_register_extrinsic( wait_for_finalization=wait_for_finalization, ) - if success != True or success == False: + if success is not True or success is False: bittensor.__console__.print( - ":cross_mark: [red]Failed[/red]: error:{}".format(err_msg) + f":cross_mark: [red]Failed[/red]: error:{err_msg}" ) time.sleep(0.5) return False @@ -305,9 +295,7 @@ def burned_register_extrinsic( ) bittensor.__console__.print( - "Balance:\n [blue]{}[/blue] :arrow_right: [green]{}[/green]".format( - old_balance, new_balance - ) + f"Balance:\n [blue]{old_balance}[/blue] :arrow_right: [green]{new_balance}[/green]" ) is_registered = subtensor.is_hotkey_registered( netuid=netuid, hotkey_ss58=wallet.hotkey.ss58_address @@ -334,7 +322,7 @@ class MaxAttemptsException(Exception): def run_faucet_extrinsic( - subtensor: "bittensor.subtensor", + subtensor: "bittensor.Subtensor", wallet: "bittensor.wallet", wait_for_inclusion: bool = False, wait_for_finalization: bool = True, @@ -342,12 +330,12 @@ def run_faucet_extrinsic( max_allowed_attempts: int = 3, output_in_place: bool = True, cuda: bool = False, - dev_id: Union[List[int], int] = 0, + dev_id: Union[list[int], int] = 0, tpb: int = 256, num_processes: Optional[int] = None, update_interval: Optional[int] = None, log_verbose: bool = False, -) -> Tuple[bool, str]: +) -> tuple[bool, str]: r"""Runs a continual POW to get a faucet of TAO on the test net. Args: @@ -379,10 +367,7 @@ def run_faucet_extrinsic( """ if prompt: if not Confirm.ask( - "Run Faucet ?\n coldkey: [bold white]{}[/bold white]\n network: [bold white]{}[/bold white]".format( - wallet.coldkeypub.ss58_address, - subtensor.network, - ) + f"Run Faucet ?\n coldkey: [bold white]{wallet.coldkeypub.ss58_address}[/bold white]\n network: [bold white]{subtensor.network}[/bold white]" ): return False, "" @@ -483,7 +468,7 @@ def run_faucet_extrinsic( def swap_hotkey_extrinsic( - subtensor: "bittensor.subtensor", + subtensor: "bittensor.Subtensor", wallet: "bittensor.wallet", new_wallet: "bittensor.wallet", wait_for_inclusion: bool = False, @@ -506,9 +491,9 @@ def swap_hotkey_extrinsic( wait_for_finalization=wait_for_finalization, ) - if success != True or success == False: + if success is not True or success is False: bittensor.__console__.print( - ":cross_mark: [red]Failed[/red]: error:{}".format(err_msg) + f":cross_mark: [red]Failed[/red]: error:{err_msg}" ) time.sleep(0.5) return False diff --git a/bittensor/extrinsics/root.py b/bittensor/extrinsics/root.py index 2cb11bbd69..6844711bd3 100644 --- a/bittensor/extrinsics/root.py +++ b/bittensor/extrinsics/root.py @@ -16,23 +16,24 @@ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. -import bittensor - -import time import logging +import time +from typing import Union + import numpy as np from numpy.typing import NDArray from rich.prompt import Confirm -from typing import Union, List + +import bittensor import bittensor.utils.weight_utils as weight_utils from bittensor.btlogging.defines import BITTENSOR_LOGGER_NAME -from bittensor.utils.registration import torch, legacy_torch_api_compat +from bittensor.utils.registration import legacy_torch_api_compat, torch logger = logging.getLogger(BITTENSOR_LOGGER_NAME) def root_register_extrinsic( - subtensor: "bittensor.subtensor", + subtensor: "bittensor.Subtensor", wallet: "bittensor.wallet", wait_for_inclusion: bool = False, wait_for_finalization: bool = True, @@ -61,13 +62,13 @@ def root_register_extrinsic( ) if is_registered: bittensor.__console__.print( - f":white_heavy_check_mark: [green]Already registered on root network.[/green]" + ":white_heavy_check_mark: [green]Already registered on root network.[/green]" ) return True if prompt: # Prompt user for confirmation. - if not Confirm.ask(f"Register to root network?"): + if not Confirm.ask("Register to root network?"): return False with bittensor.__console__.status(":satellite: Registering to root network..."): @@ -77,9 +78,9 @@ def root_register_extrinsic( wait_for_finalization=wait_for_finalization, ) - if success != True or success == False: + if success is not True or success is False: bittensor.__console__.print( - ":cross_mark: [red]Failed[/red]: error:{}".format(err_msg) + f":cross_mark: [red]Failed[/red]: error:{err_msg}" ) time.sleep(0.5) @@ -102,10 +103,10 @@ def root_register_extrinsic( @legacy_torch_api_compat def set_root_weights_extrinsic( - subtensor: "bittensor.subtensor", + subtensor: "bittensor.Subtensor", wallet: "bittensor.wallet", - netuids: Union[NDArray[np.int64], "torch.LongTensor", List[int]], - weights: Union[NDArray[np.float32], "torch.FloatTensor", List[float]], + netuids: Union[NDArray[np.int64], "torch.LongTensor", list[int]], + weights: Union[NDArray[np.float32], "torch.FloatTensor", list[float]], version_key: int = 0, wait_for_inclusion: bool = False, wait_for_finalization: bool = False, @@ -144,13 +145,11 @@ def set_root_weights_extrinsic( # Get non zero values. non_zero_weight_idx = np.argwhere(weights > 0).squeeze(axis=1) - non_zero_weight_uids = netuids[non_zero_weight_idx] + netuids[non_zero_weight_idx] non_zero_weights = weights[non_zero_weight_idx] if non_zero_weights.size < min_allowed_weights: raise ValueError( - "The minimum number of weights required to set weights is {}, got {}".format( - min_allowed_weights, non_zero_weights.size - ) + f"The minimum number of weights required to set weights is {min_allowed_weights}, got {non_zero_weights.size}" ) # Normalize the weights to max value. @@ -164,16 +163,12 @@ def set_root_weights_extrinsic( # Ask before moving on. if prompt: if not Confirm.ask( - "Do you want to set the following root weights?:\n[bold white] weights: {}\n uids: {}[/bold white ]?".format( - formatted_weights, netuids - ) + f"Do you want to set the following root weights?:\n[bold white] weights: {formatted_weights}\n uids: {netuids}[/bold white ]?" ): return False with bittensor.__console__.status( - ":satellite: Setting root weights on [white]{}[/white] ...".format( - subtensor.network - ) + f":satellite: Setting root weights on [white]{subtensor.network}[/white] ..." ): try: weight_uids, weight_vals = weight_utils.convert_weights_and_uids_for_emit( @@ -205,7 +200,7 @@ def set_root_weights_extrinsic( return True else: bittensor.__console__.print( - ":cross_mark: [red]Failed[/red]: error:{}".format(error_message) + f":cross_mark: [red]Failed[/red]: error:{error_message}" ) bittensor.logging.warning( prefix="Set weights", @@ -215,9 +210,7 @@ def set_root_weights_extrinsic( except Exception as e: # TODO( devs ): lets remove all of the bittensor.__console__ calls and replace with the bittensor logger. - bittensor.__console__.print( - ":cross_mark: [red]Failed[/red]: error:{}".format(e) - ) + bittensor.__console__.print(f":cross_mark: [red]Failed[/red]: error:{e}") bittensor.logging.warning( prefix="Set weights", suffix="Failed: " + str(e) ) diff --git a/bittensor/extrinsics/senate.py b/bittensor/extrinsics/senate.py index 233a78d614..2c810744a6 100644 --- a/bittensor/extrinsics/senate.py +++ b/bittensor/extrinsics/senate.py @@ -17,14 +17,15 @@ # DEALINGS IN THE SOFTWARE. # Imports -import bittensor - import time + from rich.prompt import Confirm +import bittensor + def register_senate_extrinsic( - subtensor: "bittensor.subtensor", + subtensor: "bittensor.Subtensor", wallet: "bittensor.wallet", wait_for_inclusion: bool = False, wait_for_finalization: bool = True, @@ -50,7 +51,7 @@ def register_senate_extrinsic( if prompt: # Prompt user for confirmation. - if not Confirm.ask(f"Register delegate hotkey to senate?"): + if not Confirm.ask("Register delegate hotkey to senate?"): return False with bittensor.__console__.status(":satellite: Registering with senate..."): @@ -78,9 +79,7 @@ def register_senate_extrinsic( response.process_events() if not response.is_success: bittensor.__console__.print( - ":cross_mark: [red]Failed[/red]: error:{}".format( - response.error_message - ) + f":cross_mark: [red]Failed[/red]: error:{response.error_message}" ) time.sleep(0.5) @@ -101,7 +100,7 @@ def register_senate_extrinsic( def leave_senate_extrinsic( - subtensor: "bittensor.subtensor", + subtensor: "bittensor.Subtensor", wallet: "bittensor.wallet", wait_for_inclusion: bool = False, wait_for_finalization: bool = True, @@ -127,7 +126,7 @@ def leave_senate_extrinsic( if prompt: # Prompt user for confirmation. - if not Confirm.ask(f"Remove delegate hotkey from senate?"): + if not Confirm.ask("Remove delegate hotkey from senate?"): return False with bittensor.__console__.status(":satellite: Leaving senate..."): @@ -155,9 +154,7 @@ def leave_senate_extrinsic( response.process_events() if not response.is_success: bittensor.__console__.print( - ":cross_mark: [red]Failed[/red]: error:{}".format( - response.error_message - ) + f":cross_mark: [red]Failed[/red]: error:{response.error_message}" ) time.sleep(0.5) @@ -178,7 +175,7 @@ def leave_senate_extrinsic( def vote_senate_extrinsic( - subtensor: "bittensor.subtensor", + subtensor: "bittensor.Subtensor", wallet: "bittensor.wallet", proposal_hash: str, proposal_idx: int, @@ -207,7 +204,7 @@ def vote_senate_extrinsic( if prompt: # Prompt user for confirmation. - if not Confirm.ask("Cast a vote of {}?".format(vote)): + if not Confirm.ask(f"Cast a vote of {vote}?"): return False with bittensor.__console__.status(":satellite: Casting vote.."): @@ -240,9 +237,7 @@ def vote_senate_extrinsic( response.process_events() if not response.is_success: bittensor.__console__.print( - ":cross_mark: [red]Failed[/red]: error:{}".format( - response.error_message - ) + f":cross_mark: [red]Failed[/red]: error:{response.error_message}" ) time.sleep(0.5) diff --git a/bittensor/extrinsics/serving.py b/bittensor/extrinsics/serving.py index 1aefa091ad..65cc3d20ca 100644 --- a/bittensor/extrinsics/serving.py +++ b/bittensor/extrinsics/serving.py @@ -16,14 +16,19 @@ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. import json +from typing import Optional + +from retry import retry +from rich.prompt import Confirm + import bittensor import bittensor.utils.networking as net -from rich.prompt import Confirm + from ..errors import MetadataError def serve_extrinsic( - subtensor: "bittensor.subtensor", + subtensor: "bittensor.Subtensor", wallet: "bittensor.wallet", ip: str, port: int, @@ -64,7 +69,7 @@ def serve_extrinsic( """ # Decrypt hotkey wallet.hotkey - params: "bittensor.AxonServeCallParams" = { + params: bittensor.AxonServeCallParams = { "version": bittensor.__version_as_int__, "ip": net.ip_to_int(ip), "port": port, @@ -106,9 +111,7 @@ def serve_extrinsic( output["coldkey"] = wallet.coldkeypub.ss58_address output["hotkey"] = wallet.hotkey.ss58_address if not Confirm.ask( - "Do you want to serve axon:\n [bold white]{}[/bold white]".format( - json.dumps(output, indent=4, sort_keys=True) - ) + f"Do you want to serve axon:\n [bold white]{json.dumps(output, indent=4, sort_keys=True)}[/bold white]" ): return False @@ -123,7 +126,7 @@ def serve_extrinsic( ) if wait_for_inclusion or wait_for_finalization: - if success == True: + if success is True: bittensor.logging.debug( f"Axon served with: AxonInfo({wallet.hotkey.ss58_address},{ip}:{port}) on {subtensor.network}:{netuid} " ) @@ -138,7 +141,7 @@ def serve_extrinsic( def serve_axon_extrinsic( - subtensor: "bittensor.subtensor", + subtensor: "bittensor.Subtensor", netuid: int, axon: "bittensor.Axon", wait_for_inclusion: bool = False, @@ -167,22 +170,18 @@ def serve_axon_extrinsic( external_port = axon.external_port # ---- Get external ip ---- - if axon.external_ip == None: + if axon.external_ip is None: try: external_ip = net.get_external_ip() bittensor.__console__.print( - ":white_heavy_check_mark: [green]Found external ip: {}[/green]".format( - external_ip - ) + f":white_heavy_check_mark: [green]Found external ip: {external_ip}[/green]" ) bittensor.logging.success( - prefix="External IP", suffix="{}".format(external_ip) + prefix="External IP", suffix=f"{external_ip}" ) except Exception as E: raise RuntimeError( - "Unable to attain your external ip. Check your internet connection. error: {}".format( - E - ) + f"Unable to attain your external ip. Check your internet connection. error: {E}" ) from E else: external_ip = axon.external_ip @@ -201,7 +200,7 @@ def serve_axon_extrinsic( def publish_metadata( - subtensor: "bittensor.subtensor", + subtensor: "bittensor.Subtensor", wallet: "bittensor.wallet", netuid: int, type: str, @@ -262,10 +261,6 @@ def publish_metadata( raise MetadataError(response.error_message) -from retry import retry -from typing import Optional - - def get_metadata(self, netuid: int, hotkey: str, block: Optional[int] = None) -> str: @retry(delay=2, tries=3, backoff=2, max_delay=4) def make_substrate_call_with_retry(): @@ -274,7 +269,7 @@ def make_substrate_call_with_retry(): module="Commitments", storage_function="CommitmentOf", params=[netuid, hotkey], - block_hash=None if block == None else substrate.get_block_hash(block), + block_hash=None if block is None else substrate.get_block_hash(block), ) commit_data = make_substrate_call_with_retry() diff --git a/bittensor/extrinsics/set_weights.py b/bittensor/extrinsics/set_weights.py index 5db0a1a7a9..61ccffc34f 100644 --- a/bittensor/extrinsics/set_weights.py +++ b/bittensor/extrinsics/set_weights.py @@ -16,13 +16,14 @@ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. -import bittensor - import logging +from typing import Union + import numpy as np from numpy.typing import NDArray from rich.prompt import Confirm -from typing import Union, Tuple + +import bittensor import bittensor.utils.weight_utils as weight_utils from bittensor.btlogging.defines import BITTENSOR_LOGGER_NAME from bittensor.utils.registration import torch, use_torch @@ -31,7 +32,7 @@ def set_weights_extrinsic( - subtensor: "bittensor.subtensor", + subtensor: "bittensor.Subtensor", wallet: "bittensor.wallet", netuid: int, uids: Union[NDArray[np.int64], "torch.LongTensor", list], @@ -40,7 +41,7 @@ def set_weights_extrinsic( wait_for_inclusion: bool = False, wait_for_finalization: bool = False, prompt: bool = False, -) -> Tuple[bool, str]: +) -> tuple[bool, str]: r"""Sets the given weights and values on chain for wallet hotkey account. Args: @@ -86,14 +87,12 @@ def set_weights_extrinsic( # Ask before moving on. if prompt: if not Confirm.ask( - "Do you want to set weights:\n[bold white] weights: {}\n uids: {}[/bold white ]?".format( - [float(v / 65535) for v in weight_vals], weight_uids - ) + f"Do you want to set weights:\n[bold white] weights: {[float(v / 65535) for v in weight_vals]}\n uids: {weight_uids}[/bold white ]?" ): return False, "Prompt refused." with bittensor.__console__.status( - ":satellite: Setting weights on [white]{}[/white] ...".format(subtensor.network) + f":satellite: Setting weights on [white]{subtensor.network}[/white] ..." ): try: success, error_message = subtensor._do_set_weights( @@ -109,7 +108,7 @@ def set_weights_extrinsic( if not wait_for_finalization and not wait_for_inclusion: return True, "Not waiting for finalization or inclusion." - if success == True: + if success is True: bittensor.__console__.print( ":white_heavy_check_mark: [green]Finalized[/green]" ) @@ -120,7 +119,7 @@ def set_weights_extrinsic( return True, "Successfully set weights and Finalized." else: bittensor.__console__.print( - ":cross_mark: [red]Failed[/red]: error:{}".format(error_message) + f":cross_mark: [red]Failed[/red]: error:{error_message}" ) bittensor.logging.warning( prefix="Set weights", @@ -129,9 +128,7 @@ def set_weights_extrinsic( return False, error_message except Exception as e: - bittensor.__console__.print( - ":cross_mark: [red]Failed[/red]: error:{}".format(e) - ) + bittensor.__console__.print(f":cross_mark: [red]Failed[/red]: error:{e}") bittensor.logging.warning( prefix="Set weights", suffix="Failed: " + str(e) ) diff --git a/bittensor/extrinsics/staking.py b/bittensor/extrinsics/staking.py index f3249a8b1c..e20cf38468 100644 --- a/bittensor/extrinsics/staking.py +++ b/bittensor/extrinsics/staking.py @@ -16,15 +16,17 @@ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. -import bittensor -from rich.prompt import Confirm from time import sleep -from typing import List, Union, Optional +from typing import Optional, Union + +from rich.prompt import Confirm + +import bittensor from bittensor.utils.balance import Balance def add_stake_extrinsic( - subtensor: "bittensor.subtensor", + subtensor: "bittensor.Subtensor", wallet: "bittensor.wallet", hotkey_ss58: Optional[str] = None, amount: Optional[Union[Balance, float]] = None, @@ -68,9 +70,7 @@ def add_stake_extrinsic( own_hotkey: bool with bittensor.__console__.status( - ":satellite: Syncing with chain: [white]{}[/white] ...".format( - subtensor.network - ) + f":satellite: Syncing with chain: [white]{subtensor.network}[/white] ..." ): old_balance = subtensor.get_balance(wallet.coldkeypub.ss58_address) # Get hotkey owner @@ -80,7 +80,7 @@ def add_stake_extrinsic( # This is not the wallet's own hotkey so we are delegating. if not subtensor.is_hotkey_delegate(hotkey_ss58): raise bittensor.errors.NotDelegateError( - "Hotkey: {} is not a delegate.".format(hotkey_ss58) + f"Hotkey: {hotkey_ss58} is not a delegate." ) # Get hotkey take @@ -92,7 +92,7 @@ def add_stake_extrinsic( ) # Convert to bittensor.Balance - if amount == None: + if amount is None: # Stake it all. staking_balance = bittensor.Balance.from_tao(old_balance.tao) elif not isinstance(amount, bittensor.Balance): @@ -109,9 +109,7 @@ def add_stake_extrinsic( # Check enough to stake. if staking_balance > old_balance: bittensor.__console__.print( - ":cross_mark: [red]Not enough stake[/red]:[bold white]\n balance:{}\n amount: {}\n coldkey: {}[/bold white]".format( - old_balance, staking_balance, wallet.name - ) + f":cross_mark: [red]Not enough stake[/red]:[bold white]\n balance:{old_balance}\n amount: {staking_balance}\n coldkey: {wallet.name}[/bold white]" ) return False @@ -120,24 +118,18 @@ def add_stake_extrinsic( if not own_hotkey: # We are delegating. if not Confirm.ask( - "Do you want to delegate:[bold white]\n amount: {}\n to: {}\n take: {}\n owner: {}[/bold white]".format( - staking_balance, wallet.hotkey_str, hotkey_take, hotkey_owner - ) + f"Do you want to delegate:[bold white]\n amount: {staking_balance}\n to: {wallet.hotkey_str}\n take: {hotkey_take}\n owner: {hotkey_owner}[/bold white]" ): return False else: if not Confirm.ask( - "Do you want to stake:[bold white]\n amount: {}\n to: {}[/bold white]".format( - staking_balance, wallet.hotkey_str - ) + f"Do you want to stake:[bold white]\n amount: {staking_balance}\n to: {wallet.hotkey_str}[/bold white]" ): return False try: with bittensor.__console__.status( - ":satellite: Staking to: [bold white]{}[/bold white] ...".format( - subtensor.network - ) + f":satellite: Staking to: [bold white]{subtensor.network}[/bold white] ..." ): staking_response: bool = __do_add_stake_single( subtensor=subtensor, @@ -148,7 +140,7 @@ def add_stake_extrinsic( wait_for_finalization=wait_for_finalization, ) - if staking_response == True: # If we successfully staked. + if staking_response is True: # If we successfully staked. # We only wait here if we expect finalization. if not wait_for_finalization and not wait_for_inclusion: return True @@ -157,9 +149,7 @@ def add_stake_extrinsic( ":white_heavy_check_mark: [green]Finalized[/green]" ) with bittensor.__console__.status( - ":satellite: Checking Balance on: [white]{}[/white] ...".format( - subtensor.network - ) + f":satellite: Checking Balance on: [white]{subtensor.network}[/white] ..." ): new_balance = subtensor.get_balance( address=wallet.coldkeypub.ss58_address @@ -172,14 +162,10 @@ def add_stake_extrinsic( ) # Get current stake bittensor.__console__.print( - "Balance:\n [blue]{}[/blue] :arrow_right: [green]{}[/green]".format( - old_balance, new_balance - ) + f"Balance:\n [blue]{old_balance}[/blue] :arrow_right: [green]{new_balance}[/green]" ) bittensor.__console__.print( - "Stake:\n [blue]{}[/blue] :arrow_right: [green]{}[/green]".format( - old_stake, new_stake - ) + f"Stake:\n [blue]{old_stake}[/blue] :arrow_right: [green]{new_stake}[/green]" ) return True else: @@ -188,23 +174,21 @@ def add_stake_extrinsic( ) return False - except bittensor.errors.NotRegisteredError as e: + except bittensor.errors.NotRegisteredError: bittensor.__console__.print( - ":cross_mark: [red]Hotkey: {} is not registered.[/red]".format( - wallet.hotkey_str - ) + f":cross_mark: [red]Hotkey: {wallet.hotkey_str} is not registered.[/red]" ) return False except bittensor.errors.StakeError as e: - bittensor.__console__.print(":cross_mark: [red]Stake Error: {}[/red]".format(e)) + bittensor.__console__.print(f":cross_mark: [red]Stake Error: {e}[/red]") return False def add_stake_multiple_extrinsic( - subtensor: "bittensor.subtensor", + subtensor: "bittensor.Subtensor", wallet: "bittensor.wallet", - hotkey_ss58s: List[str], - amounts: Optional[List[Union[Balance, float]]] = None, + hotkey_ss58s: list[str], + amounts: Optional[list[Union[Balance, float]]] = None, wait_for_inclusion: bool = True, wait_for_finalization: bool = False, prompt: bool = False, @@ -264,9 +248,7 @@ def add_stake_multiple_extrinsic( old_stakes = [] with bittensor.__console__.status( - ":satellite: Syncing with chain: [white]{}[/white] ...".format( - subtensor.network - ) + f":satellite: Syncing with chain: [white]{subtensor.network}[/white] ..." ): old_balance = subtensor.get_balance(wallet.coldkeypub.ss58_address) @@ -305,7 +287,7 @@ def add_stake_multiple_extrinsic( ): staking_all = False # Convert to bittensor.Balance - if amount == None: + if amount is None: # Stake it all. staking_balance = bittensor.Balance.from_tao(old_balance.tao) staking_all = True @@ -317,18 +299,14 @@ def add_stake_multiple_extrinsic( # Check enough to stake if staking_balance > old_balance: bittensor.__console__.print( - ":cross_mark: [red]Not enough balance[/red]: [green]{}[/green] to stake: [blue]{}[/blue] from coldkey: [white]{}[/white]".format( - old_balance, staking_balance, wallet.name - ) + f":cross_mark: [red]Not enough balance[/red]: [green]{old_balance}[/green] to stake: [blue]{staking_balance}[/blue] from coldkey: [white]{wallet.name}[/white]" ) continue # Ask before moving on. if prompt: if not Confirm.ask( - "Do you want to stake:\n[bold white] amount: {}\n hotkey: {}[/bold white ]?".format( - staking_balance, wallet.hotkey_str - ) + f"Do you want to stake:\n[bold white] amount: {staking_balance}\n hotkey: {wallet.hotkey_str}[/bold white ]?" ): continue @@ -342,7 +320,7 @@ def add_stake_multiple_extrinsic( wait_for_finalization=wait_for_finalization, ) - if staking_response == True: # If we successfully staked. + if staking_response is True: # If we successfully staked. # We only wait here if we expect finalization. if idx < len(hotkey_ss58s) - 1: @@ -350,9 +328,7 @@ def add_stake_multiple_extrinsic( tx_rate_limit_blocks = subtensor.tx_rate_limit() if tx_rate_limit_blocks > 0: bittensor.__console__.print( - ":hourglass: [yellow]Waiting for tx rate limit: [white]{}[/white] blocks[/yellow]".format( - tx_rate_limit_blocks - ) + f":hourglass: [yellow]Waiting for tx rate limit: [white]{tx_rate_limit_blocks}[/white] blocks[/yellow]" ) sleep(tx_rate_limit_blocks * 12) # 12 seconds per block @@ -379,9 +355,7 @@ def add_stake_multiple_extrinsic( wallet.coldkeypub.ss58_address, block=block ) bittensor.__console__.print( - "Stake ({}): [blue]{}[/blue] :arrow_right: [green]{}[/green]".format( - hotkey_ss58, old_stake, new_stake - ) + f"Stake ({hotkey_ss58}): [blue]{old_stake}[/blue] :arrow_right: [green]{new_stake}[/green]" ) old_balance = new_balance successful_stakes += 1 @@ -395,30 +369,22 @@ def add_stake_multiple_extrinsic( ) continue - except bittensor.errors.NotRegisteredError as e: + except bittensor.errors.NotRegisteredError: bittensor.__console__.print( - ":cross_mark: [red]Hotkey: {} is not registered.[/red]".format( - hotkey_ss58 - ) + f":cross_mark: [red]Hotkey: {hotkey_ss58} is not registered.[/red]" ) continue except bittensor.errors.StakeError as e: - bittensor.__console__.print( - ":cross_mark: [red]Stake Error: {}[/red]".format(e) - ) + bittensor.__console__.print(f":cross_mark: [red]Stake Error: {e}[/red]") continue if successful_stakes != 0: with bittensor.__console__.status( - ":satellite: Checking Balance on: ([white]{}[/white] ...".format( - subtensor.network - ) + f":satellite: Checking Balance on: ([white]{subtensor.network}[/white] ..." ): new_balance = subtensor.get_balance(wallet.coldkeypub.ss58_address) bittensor.__console__.print( - "Balance: [blue]{}[/blue] :arrow_right: [green]{}[/green]".format( - old_balance, new_balance - ) + f"Balance: [blue]{old_balance}[/blue] :arrow_right: [green]{new_balance}[/green]" ) return True @@ -426,7 +392,7 @@ def add_stake_multiple_extrinsic( def __do_add_stake_single( - subtensor: "bittensor.subtensor", + subtensor: "bittensor.Subtensor", wallet: "bittensor.wallet", hotkey_ss58: str, amount: "bittensor.Balance", @@ -471,7 +437,7 @@ def __do_add_stake_single( # Verify that the hotkey is a delegate. if not subtensor.is_hotkey_delegate(hotkey_ss58=hotkey_ss58): raise bittensor.errors.NotDelegateError( - "Hotkey: {} is not a delegate.".format(hotkey_ss58) + f"Hotkey: {hotkey_ss58} is not a delegate." ) success = subtensor._do_stake( diff --git a/bittensor/extrinsics/transfer.py b/bittensor/extrinsics/transfer.py index ae09803199..cca3e45f05 100644 --- a/bittensor/extrinsics/transfer.py +++ b/bittensor/extrinsics/transfer.py @@ -16,16 +16,18 @@ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. -import bittensor +from typing import Union from rich.prompt import Confirm -from typing import Union -from ..utils.balance import Balance + +import bittensor + from ..utils import is_valid_bittensor_address_or_public_key +from ..utils.balance import Balance def transfer_extrinsic( - subtensor: "bittensor.subtensor", + subtensor: "bittensor.Subtensor", wallet: "bittensor.wallet", dest: str, amount: Union[Balance, float], @@ -58,9 +60,7 @@ def transfer_extrinsic( # Validate destination address. if not is_valid_bittensor_address_or_public_key(dest): bittensor.__console__.print( - ":cross_mark: [red]Invalid destination address[/red]:[bold white]\n {}[/bold white]".format( - dest - ) + f":cross_mark: [red]Invalid destination address[/red]:[bold white]\n {dest}[/bold white]" ) return False @@ -95,18 +95,14 @@ def transfer_extrinsic( # Check if we have enough balance. if account_balance < (transfer_balance + fee + existential_deposit): bittensor.__console__.print( - ":cross_mark: [red]Not enough balance[/red]:[bold white]\n balance: {}\n amount: {}\n for fee: {}[/bold white]".format( - account_balance, transfer_balance, fee - ) + f":cross_mark: [red]Not enough balance[/red]:[bold white]\n balance: {account_balance}\n amount: {transfer_balance}\n for fee: {fee}[/bold white]" ) return False # Ask before moving on. if prompt: if not Confirm.ask( - "Do you want to transfer:[bold white]\n amount: {}\n from: {}:{}\n to: {}\n for fee: {}[/bold white]".format( - transfer_balance, wallet.name, wallet.coldkey.ss58_address, dest, fee - ) + f"Do you want to transfer:[bold white]\n amount: {transfer_balance}\n from: {wallet.name}:{wallet.coldkey.ss58_address}\n to: {dest}\n for fee: {fee}[/bold white]" ): return False @@ -123,9 +119,7 @@ def transfer_extrinsic( bittensor.__console__.print( ":white_heavy_check_mark: [green]Finalized[/green]" ) - bittensor.__console__.print( - "[green]Block Hash: {}[/green]".format(block_hash) - ) + bittensor.__console__.print(f"[green]Block Hash: {block_hash}[/green]") explorer_urls = bittensor.utils.get_explorer_url_for_network( subtensor.network, block_hash, bittensor.__network_explorer_map__ @@ -143,16 +137,14 @@ def transfer_extrinsic( ) else: bittensor.__console__.print( - ":cross_mark: [red]Failed[/red]: error:{}".format(err_msg) + f":cross_mark: [red]Failed[/red]: error:{err_msg}" ) if success: with bittensor.__console__.status(":satellite: Checking Balance..."): new_balance = subtensor.get_balance(wallet.coldkey.ss58_address) bittensor.__console__.print( - "Balance:\n [blue]{}[/blue] :arrow_right: [green]{}[/green]".format( - account_balance, new_balance - ) + f"Balance:\n [blue]{account_balance}[/blue] :arrow_right: [green]{new_balance}[/green]" ) return True diff --git a/bittensor/extrinsics/unstaking.py b/bittensor/extrinsics/unstaking.py index 6046124f40..c88f85db5a 100644 --- a/bittensor/extrinsics/unstaking.py +++ b/bittensor/extrinsics/unstaking.py @@ -16,15 +16,17 @@ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. -import bittensor -from rich.prompt import Confirm from time import sleep -from typing import List, Union, Optional +from typing import Optional, Union + +from rich.prompt import Confirm + +import bittensor from bittensor.utils.balance import Balance def __do_remove_stake_single( - subtensor: "bittensor.subtensor", + subtensor: "bittensor.Subtensor", wallet: "bittensor.wallet", hotkey_ss58: str, amount: "bittensor.Balance", @@ -72,7 +74,7 @@ def __do_remove_stake_single( def check_threshold_amount( - subtensor: "bittensor.subtensor", unstaking_balance: Balance + subtensor: "bittensor.Subtensor", unstaking_balance: Balance ) -> bool: """ Checks if the unstaking amount is above the threshold or 0 @@ -98,7 +100,7 @@ def check_threshold_amount( def unstake_extrinsic( - subtensor: "bittensor.subtensor", + subtensor: "bittensor.Subtensor", wallet: "bittensor.wallet", hotkey_ss58: Optional[str] = None, amount: Optional[Union[Balance, float]] = None, @@ -132,9 +134,7 @@ def unstake_extrinsic( hotkey_ss58 = wallet.hotkey.ss58_address # Default to wallet's own hotkey. with bittensor.__console__.status( - ":satellite: Syncing with chain: [white]{}[/white] ...".format( - subtensor.network - ) + f":satellite: Syncing with chain: [white]{subtensor.network}[/white] ..." ): old_balance = subtensor.get_balance(wallet.coldkeypub.ss58_address) old_stake = subtensor.get_stake_for_coldkey_and_hotkey( @@ -142,7 +142,7 @@ def unstake_extrinsic( ) # Convert to bittensor.Balance - if amount == None: + if amount is None: # Unstake it all. unstaking_balance = old_stake elif not isinstance(amount, bittensor.Balance): @@ -154,9 +154,7 @@ def unstake_extrinsic( stake_on_uid = old_stake if unstaking_balance > stake_on_uid: bittensor.__console__.print( - ":cross_mark: [red]Not enough stake[/red]: [green]{}[/green] to unstake: [blue]{}[/blue] from hotkey: [white]{}[/white]".format( - stake_on_uid, unstaking_balance, wallet.hotkey_str - ) + f":cross_mark: [red]Not enough stake[/red]: [green]{stake_on_uid}[/green] to unstake: [blue]{unstaking_balance}[/blue] from hotkey: [white]{wallet.hotkey_str}[/white]" ) return False @@ -168,17 +166,13 @@ def unstake_extrinsic( # Ask before moving on. if prompt: if not Confirm.ask( - "Do you want to unstake:\n[bold white] amount: {}\n hotkey: {}[/bold white ]?".format( - unstaking_balance, wallet.hotkey_str - ) + f"Do you want to unstake:\n[bold white] amount: {unstaking_balance}\n hotkey: {wallet.hotkey_str}[/bold white ]?" ): return False try: with bittensor.__console__.status( - ":satellite: Unstaking from chain: [white]{}[/white] ...".format( - subtensor.network - ) + f":satellite: Unstaking from chain: [white]{subtensor.network}[/white] ..." ): staking_response: bool = __do_remove_stake_single( subtensor=subtensor, @@ -189,7 +183,7 @@ def unstake_extrinsic( wait_for_finalization=wait_for_finalization, ) - if staking_response == True: # If we successfully unstaked. + if staking_response is True: # If we successfully unstaked. # We only wait here if we expect finalization. if not wait_for_finalization and not wait_for_inclusion: return True @@ -198,9 +192,7 @@ def unstake_extrinsic( ":white_heavy_check_mark: [green]Finalized[/green]" ) with bittensor.__console__.status( - ":satellite: Checking Balance on: [white]{}[/white] ...".format( - subtensor.network - ) + f":satellite: Checking Balance on: [white]{subtensor.network}[/white] ..." ): new_balance = subtensor.get_balance( address=wallet.coldkeypub.ss58_address @@ -209,14 +201,10 @@ def unstake_extrinsic( coldkey_ss58=wallet.coldkeypub.ss58_address, hotkey_ss58=hotkey_ss58 ) # Get stake on hotkey. bittensor.__console__.print( - "Balance:\n [blue]{}[/blue] :arrow_right: [green]{}[/green]".format( - old_balance, new_balance - ) + f"Balance:\n [blue]{old_balance}[/blue] :arrow_right: [green]{new_balance}[/green]" ) bittensor.__console__.print( - "Stake:\n [blue]{}[/blue] :arrow_right: [green]{}[/green]".format( - old_stake, new_stake - ) + f"Stake:\n [blue]{old_stake}[/blue] :arrow_right: [green]{new_stake}[/green]" ) return True else: @@ -225,23 +213,21 @@ def unstake_extrinsic( ) return False - except bittensor.errors.NotRegisteredError as e: + except bittensor.errors.NotRegisteredError: bittensor.__console__.print( - ":cross_mark: [red]Hotkey: {} is not registered.[/red]".format( - wallet.hotkey_str - ) + f":cross_mark: [red]Hotkey: {wallet.hotkey_str} is not registered.[/red]" ) return False except bittensor.errors.StakeError as e: - bittensor.__console__.print(":cross_mark: [red]Stake Error: {}[/red]".format(e)) + bittensor.__console__.print(f":cross_mark: [red]Stake Error: {e}[/red]") return False def unstake_multiple_extrinsic( - subtensor: "bittensor.subtensor", + subtensor: "bittensor.Subtensor", wallet: "bittensor.wallet", - hotkey_ss58s: List[str], - amounts: Optional[List[Union[Balance, float]]] = None, + hotkey_ss58s: list[str], + amounts: Optional[list[Union[Balance, float]]] = None, wait_for_inclusion: bool = True, wait_for_finalization: bool = False, prompt: bool = False, @@ -301,9 +287,7 @@ def unstake_multiple_extrinsic( old_stakes = [] with bittensor.__console__.status( - ":satellite: Syncing with chain: [white]{}[/white] ...".format( - subtensor.network - ) + f":satellite: Syncing with chain: [white]{subtensor.network}[/white] ..." ): old_balance = subtensor.get_balance(wallet.coldkeypub.ss58_address) @@ -318,7 +302,7 @@ def unstake_multiple_extrinsic( zip(hotkey_ss58s, amounts, old_stakes) ): # Covert to bittensor.Balance - if amount == None: + if amount is None: # Unstake it all. unstaking_balance = old_stake elif not isinstance(amount, bittensor.Balance): @@ -330,9 +314,7 @@ def unstake_multiple_extrinsic( stake_on_uid = old_stake if unstaking_balance > stake_on_uid: bittensor.__console__.print( - ":cross_mark: [red]Not enough stake[/red]: [green]{}[/green] to unstake: [blue]{}[/blue] from hotkey: [white]{}[/white]".format( - stake_on_uid, unstaking_balance, wallet.hotkey_str - ) + f":cross_mark: [red]Not enough stake[/red]: [green]{stake_on_uid}[/green] to unstake: [blue]{unstaking_balance}[/blue] from hotkey: [white]{wallet.hotkey_str}[/white]" ) continue @@ -344,17 +326,13 @@ def unstake_multiple_extrinsic( # Ask before moving on. if prompt: if not Confirm.ask( - "Do you want to unstake:\n[bold white] amount: {}\n hotkey: {}[/bold white ]?".format( - unstaking_balance, wallet.hotkey_str - ) + f"Do you want to unstake:\n[bold white] amount: {unstaking_balance}\n hotkey: {wallet.hotkey_str}[/bold white ]?" ): continue try: with bittensor.__console__.status( - ":satellite: Unstaking from chain: [white]{}[/white] ...".format( - subtensor.network - ) + f":satellite: Unstaking from chain: [white]{subtensor.network}[/white] ..." ): staking_response: bool = __do_remove_stake_single( subtensor=subtensor, @@ -365,7 +343,7 @@ def unstake_multiple_extrinsic( wait_for_finalization=wait_for_finalization, ) - if staking_response == True: # If we successfully unstaked. + if staking_response is True: # If we successfully unstaked. # We only wait here if we expect finalization. if idx < len(hotkey_ss58s) - 1: @@ -373,9 +351,7 @@ def unstake_multiple_extrinsic( tx_rate_limit_blocks = subtensor.tx_rate_limit() if tx_rate_limit_blocks > 0: bittensor.__console__.print( - ":hourglass: [yellow]Waiting for tx rate limit: [white]{}[/white] blocks[/yellow]".format( - tx_rate_limit_blocks - ) + f":hourglass: [yellow]Waiting for tx rate limit: [white]{tx_rate_limit_blocks}[/white] blocks[/yellow]" ) sleep(tx_rate_limit_blocks * 12) # 12 seconds per block @@ -387,9 +363,7 @@ def unstake_multiple_extrinsic( ":white_heavy_check_mark: [green]Finalized[/green]" ) with bittensor.__console__.status( - ":satellite: Checking Balance on: [white]{}[/white] ...".format( - subtensor.network - ) + f":satellite: Checking Balance on: [white]{subtensor.network}[/white] ..." ): block = subtensor.get_current_block() new_stake = subtensor.get_stake_for_coldkey_and_hotkey( @@ -398,9 +372,7 @@ def unstake_multiple_extrinsic( block=block, ) bittensor.__console__.print( - "Stake ({}): [blue]{}[/blue] :arrow_right: [green]{}[/green]".format( - hotkey_ss58, stake_on_uid, new_stake - ) + f"Stake ({hotkey_ss58}): [blue]{stake_on_uid}[/blue] :arrow_right: [green]{new_stake}[/green]" ) successful_unstakes += 1 else: @@ -409,28 +381,22 @@ def unstake_multiple_extrinsic( ) continue - except bittensor.errors.NotRegisteredError as e: + except bittensor.errors.NotRegisteredError: bittensor.__console__.print( - ":cross_mark: [red]{} is not registered.[/red]".format(hotkey_ss58) + f":cross_mark: [red]{hotkey_ss58} is not registered.[/red]" ) continue except bittensor.errors.StakeError as e: - bittensor.__console__.print( - ":cross_mark: [red]Stake Error: {}[/red]".format(e) - ) + bittensor.__console__.print(f":cross_mark: [red]Stake Error: {e}[/red]") continue if successful_unstakes != 0: with bittensor.__console__.status( - ":satellite: Checking Balance on: ([white]{}[/white] ...".format( - subtensor.network - ) + f":satellite: Checking Balance on: ([white]{subtensor.network}[/white] ..." ): new_balance = subtensor.get_balance(wallet.coldkeypub.ss58_address) bittensor.__console__.print( - "Balance: [blue]{}[/blue] :arrow_right: [green]{}[/green]".format( - old_balance, new_balance - ) + f"Balance: [blue]{old_balance}[/blue] :arrow_right: [green]{new_balance}[/green]" ) return True diff --git a/bittensor/keyfile.py b/bittensor/keyfile.py index b5157cea4a..fba5204af4 100644 --- a/bittensor/keyfile.py +++ b/bittensor/keyfile.py @@ -15,29 +15,29 @@ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. -import os import base64 +import getpass import json +import os import stat -import getpass -import bittensor -from bittensor.errors import KeyFileError -from typing import Optional from pathlib import Path +from typing import Optional -from ansible_vault import Vault from ansible.parsing.vault import AnsibleVaultError -from cryptography.exceptions import InvalidSignature, InvalidKey +from ansible_vault import Vault +from cryptography.exceptions import InvalidKey, InvalidSignature from cryptography.fernet import Fernet, InvalidToken -from cryptography.hazmat.primitives import hashes from cryptography.hazmat.backends import default_backend +from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC from nacl import pwhash, secret from password_strength import PasswordPolicy +from rich.prompt import Confirm from substrateinterface.utils.ss58 import ss58_encode from termcolor import colored -from rich.prompt import Confirm +import bittensor +from bittensor.errors import KeyFileError NACL_SALT = b"\x13q\x83\xdf\xf1Z\t\xbc\x9c\x90\xb5Q\x879\xe9\xb1" @@ -84,7 +84,7 @@ def deserialize_keypair_from_keyfile_data(keyfile_data: bytes) -> "bittensor.Key keyfile_data = keyfile_data.decode() try: keyfile_dict = dict(json.loads(keyfile_data)) - except: + except: # noqa: E722 # FIXME: This is a broad exception catch, should be narrowed down. string_value = str(keyfile_data) if string_value[:2] == "0x": string_value = ss58_encode(string_value) @@ -98,9 +98,7 @@ def deserialize_keypair_from_keyfile_data(keyfile_data: bytes) -> "bittensor.Key } else: raise bittensor.KeyFileError( - "Keypair could not be created from keyfile data: {}".format( - string_value - ) + f"Keypair could not be created from keyfile data: {string_value}" ) if "secretSeed" in keyfile_dict and keyfile_dict["secretSeed"] is not None: @@ -122,7 +120,7 @@ def deserialize_keypair_from_keyfile_data(keyfile_data: bytes) -> "bittensor.Key else: raise bittensor.KeyFileError( - "Keypair could not be created from keyfile data: {}".format(keyfile_dict) + f"Keypair could not be created from keyfile data: {keyfile_dict}" ) @@ -346,9 +344,7 @@ def decrypt_keyfile_data( decrypted_keyfile_data = cipher_suite.decrypt(keyfile_data) # Unknown. else: - raise bittensor.KeyFileError( - "keyfile data: {} is corrupt".format(keyfile_data) - ) + raise bittensor.KeyFileError(f"keyfile data: {keyfile_data} is corrupt") except (InvalidSignature, InvalidKey, InvalidToken): raise bittensor.KeyFileError("Invalid password") @@ -367,14 +363,11 @@ def __init__(self, path: str): def __str__(self): if not self.exists_on_device(): - return "keyfile (empty, {})>".format(self.path) + return f"keyfile (empty, {self.path})>" if self.is_encrypted(): - return "Keyfile ({} encrypted, {})>".format( - keyfile_data_encryption_method(self._read_keyfile_data_from_file()), - self.path, - ) + return f"Keyfile ({keyfile_data_encryption_method(self._read_keyfile_data_from_file())} encrypted, {self.path})>" else: - return "keyfile (decrypted, {})>".format(self.path) + return f"keyfile (decrypted, {self.path})>" def __repr__(self): return self.__str__() @@ -510,7 +503,7 @@ def _may_overwrite(self) -> bool: Returns: may_overwrite (bool): ``True`` if the user allows overwriting the file. """ - choice = input("File {} already exists. Overwrite? (y/N) ".format(self.path)) + choice = input(f"File {self.path} already exists. Overwrite? (y/N) ") return choice == "y" def check_and_update_encryption( @@ -560,7 +553,7 @@ def check_and_update_encryption( stored_mnemonic = False while not stored_mnemonic: bittensor.__console__.print( - f"\nPlease make sure you have the mnemonic stored in case an error occurs during the transfer.", + "\nPlease make sure you have the mnemonic stored in case an error occurs during the transfer.", style="white on red", ) stored_mnemonic = Confirm.ask("Have you stored the mnemonic?") @@ -571,7 +564,7 @@ def check_and_update_encryption( break decrypted_keyfile_data = None - while decrypted_keyfile_data == None and not terminate: + while decrypted_keyfile_data is None and not terminate: try: password = getpass.getpass( "\nEnter password to update keyfile: " @@ -625,17 +618,11 @@ def encrypt(self, password: str = None): KeyFileError: Raised if the file does not exist, is not readable, or writable. """ if not self.exists_on_device(): - raise bittensor.KeyFileError( - "Keyfile at: {} does not exist".format(self.path) - ) + raise bittensor.KeyFileError(f"Keyfile at: {self.path} does not exist") if not self.is_readable(): - raise bittensor.KeyFileError( - "Keyfile at: {} is not readable".format(self.path) - ) + raise bittensor.KeyFileError(f"Keyfile at: {self.path} is not readable") if not self.is_writable(): - raise bittensor.KeyFileError( - "Keyfile at: {} is not writable".format(self.path) - ) + raise bittensor.KeyFileError(f"Keyfile at: {self.path} is not writable") keyfile_data = self._read_keyfile_data_from_file() if not keyfile_data_is_encrypted(keyfile_data): as_keypair = deserialize_keypair_from_keyfile_data(keyfile_data) @@ -652,17 +639,11 @@ def decrypt(self, password: str = None): KeyFileError: Raised if the file does not exist, is not readable, writable, corrupted, or if the password is incorrect. """ if not self.exists_on_device(): - raise bittensor.KeyFileError( - "Keyfile at: {} does not exist".format(self.path) - ) + raise bittensor.KeyFileError(f"Keyfile at: {self.path} does not exist") if not self.is_readable(): - raise bittensor.KeyFileError( - "Keyfile at: {} is not readable".format(self.path) - ) + raise bittensor.KeyFileError(f"Keyfile at: {self.path} is not readable") if not self.is_writable(): - raise bittensor.KeyFileError( - "Keyfile at: {} is not writable".format(self.path) - ) + raise bittensor.KeyFileError(f"Keyfile at: {self.path} is not writable") keyfile_data = self._read_keyfile_data_from_file() if keyfile_data_is_encrypted(keyfile_data): keyfile_data = decrypt_keyfile_data( @@ -681,13 +662,9 @@ def _read_keyfile_data_from_file(self) -> bytes: KeyFileError: Raised if the file does not exist or is not readable. """ if not self.exists_on_device(): - raise bittensor.KeyFileError( - "Keyfile at: {} does not exist".format(self.path) - ) + raise bittensor.KeyFileError(f"Keyfile at: {self.path} does not exist") if not self.is_readable(): - raise bittensor.KeyFileError( - "Keyfile at: {} is not readable".format(self.path) - ) + raise bittensor.KeyFileError(f"Keyfile at: {self.path} is not readable") with open(self.path, "rb") as file: data = file.read() return data @@ -704,9 +681,7 @@ def _write_keyfile_data_to_file(self, keyfile_data: bytes, overwrite: bool = Fal # Check overwrite. if self.exists_on_device() and not overwrite: if not self._may_overwrite(): - raise bittensor.KeyFileError( - "Keyfile at: {} is not writable".format(self.path) - ) + raise bittensor.KeyFileError(f"Keyfile at: {self.path} is not writable") with open(self.path, "wb") as keyfile: keyfile.write(keyfile_data) # Set file permissions. diff --git a/bittensor/metagraph.py b/bittensor/metagraph.py index 8d7e97bcc0..4037e0c78b 100644 --- a/bittensor/metagraph.py +++ b/bittensor/metagraph.py @@ -17,16 +17,17 @@ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. -from abc import ABC, abstractmethod import os import pickle -import numpy as np -from numpy.typing import NDArray -import bittensor +from abc import ABC, abstractmethod from os import listdir from os.path import join -from typing import List, Optional, Union, Tuple +from typing import Optional, Union +import numpy as np +from numpy.typing import NDArray + +import bittensor from bittensor.chain_data import AxonInfo from bittensor.utils.registration import torch, use_torch @@ -85,7 +86,7 @@ def latest_block_path(dir_path: str) -> str: if block_number > latest_block: latest_block = block_number latest_file_full_path = full_path_filename - except Exception as e: + except Exception: pass if not latest_file_full_path: raise ValueError(f"Metagraph not found at: {dir_path}") @@ -152,7 +153,7 @@ class MetagraphMixin(ABC): netuid: int network: str - version: Union["torch.nn.Parameter", Tuple[NDArray]] + version: Union["torch.nn.Parameter", tuple[NDArray]] n: Union["torch.nn.Parameter", NDArray] block: Union["torch.nn.Parameter", NDArray] stake: Union["torch.nn.Parameter", NDArray] @@ -170,7 +171,7 @@ class MetagraphMixin(ABC): weights: Union["torch.nn.Parameter", NDArray] bonds: Union["torch.nn.Parameter", NDArray] uids: Union["torch.nn.Parameter", NDArray] - axons: List[AxonInfo] + axons: list[AxonInfo] @property def S(self) -> Union[NDArray, "torch.nn.Parameter"]: @@ -199,7 +200,7 @@ def R(self) -> Union[NDArray, "torch.nn.Parameter"]: return self.ranks @property - def I(self) -> Union[NDArray, "torch.nn.Parameter"]: + def I(self) -> Union[NDArray, "torch.nn.Parameter"]: # noqa: E743 """ Incentive values of neurons represent the rewards they receive for their contributions to the network. The Bittensor network employs an incentive mechanism that rewards neurons based on their @@ -315,7 +316,7 @@ def W(self) -> Union[NDArray, "torch.nn.Parameter"]: return self.weights @property - def hotkeys(self) -> List[str]: + def hotkeys(self) -> list[str]: """ Represents a list of ``hotkeys`` for each neuron in the Bittensor network. @@ -333,7 +334,7 @@ def hotkeys(self) -> List[str]: return [axon.hotkey for axon in self.axons] @property - def coldkeys(self) -> List[str]: + def coldkeys(self) -> list[str]: """ Contains a list of ``coldkeys`` for each neuron in the Bittensor network. @@ -349,7 +350,7 @@ def coldkeys(self) -> List[str]: return [axon.coldkey for axon in self.axons] @property - def addresses(self) -> List[str]: + def addresses(self) -> list[str]: """ Provides a list of IP addresses for each neuron in the Bittensor network. These addresses are used for network communication, allowing neurons to connect, interact, and exchange information with each other. @@ -397,9 +398,7 @@ def __str__(self) -> str: print(metagraph) # Output: "metagraph(netuid:1, n:100, block:500, network:finney)" """ - return "metagraph(netuid:{}, n:{}, block:{}, network:{})".format( - self.netuid, self.n.item(), self.block.item(), self.network - ) + return f"metagraph(netuid:{self.netuid}, n:{self.n.item()}, block:{self.block.item()}, network:{self.network})" def __repr__(self) -> str: """ @@ -506,7 +505,7 @@ def sync( For example:: - subtensor = bittensor.subtensor(network='archive') + subtensor = bittensor.Subtensor(network='archive') """ # Initialize subtensor @@ -553,7 +552,7 @@ def _initialize_subtensor(self, subtensor): """ if not subtensor: # TODO: Check and test the initialization of the new subtensor - subtensor = bittensor.subtensor(network=self.network) + subtensor = bittensor.Subtensor(network=self.network) return subtensor def _assign_neurons(self, block, lite, subtensor): @@ -672,7 +671,7 @@ def _process_weights_or_bonds( len(self.neurons), list(uids), list(values) ).astype(np.float32) ) - tensor_param: Union["torch.nn.Parameter", NDArray] = ( + tensor_param: Union["torch.nn.Parameter", NDArray] = ( # noqa: UP037 ( torch.nn.Parameter(torch.stack(data_array), requires_grad=False) if len(data_array) @@ -735,7 +734,7 @@ def _process_root_weights( ) ) - tensor_param: Union[NDArray, "torch.nn.Parameter"] = ( + tensor_param: Union[NDArray, "torch.nn.Parameter"] = ( # noqa: UP037 ( torch.nn.Parameter(torch.stack(data_array), requires_grad=False) if len(data_array) @@ -928,7 +927,7 @@ def __init__( self.uids = torch.nn.Parameter( torch.tensor([], dtype=torch.int64), requires_grad=False ) - self.axons: List[AxonInfo] = [] + self.axons: list[AxonInfo] = [] if sync: self.sync(block=None, lite=lite) @@ -1065,7 +1064,7 @@ def __init__( self.weights = np.array([], dtype=np.float32) self.bonds = np.array([], dtype=np.int64) self.uids = np.array([], dtype=np.int64) - self.axons: List[AxonInfo] = [] + self.axons: list[AxonInfo] = [] if sync: self.sync(block=None, lite=lite) diff --git a/bittensor/mock/keyfile_mock.py b/bittensor/mock/keyfile_mock.py index e13126cc17..91a597a3bc 100644 --- a/bittensor/mock/keyfile_mock.py +++ b/bittensor/mock/keyfile_mock.py @@ -18,7 +18,7 @@ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. -from bittensor import serialized_keypair_to_keyfile_data, keyfile, Keypair +from bittensor import Keypair, keyfile, serialized_keypair_to_keyfile_data class MockKeyfile(keyfile): @@ -34,11 +34,11 @@ def __init__(self, path: str): def __str__(self): if not self.exists_on_device(): - return "Keyfile (empty, {})>".format(self.path) + return f"Keyfile (empty, {self.path})>" if self.is_encrypted(): - return "Keyfile (encrypted, {})>".format(self.path) + return f"Keyfile (encrypted, {self.path})>" else: - return "Keyfile (decrypted, {})>".format(self.path) + return f"Keyfile (decrypted, {self.path})>" def __repr__(self): return self.__str__() diff --git a/bittensor/mock/subtensor_mock.py b/bittensor/mock/subtensor_mock.py index 30d58f22e0..05151ce578 100644 --- a/bittensor/mock/subtensor_mock.py +++ b/bittensor/mock/subtensor_mock.py @@ -15,33 +15,29 @@ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. -from random import randint -from types import SimpleNamespace -from typing import Any, Dict, List, Optional, Tuple, TypedDict, Union -from unittest.mock import MagicMock -from dataclasses import dataclass from abc import abstractclassmethod from collections.abc import Mapping - +from dataclasses import dataclass from hashlib import sha256 -from ..wallet import wallet +from random import randint +from types import SimpleNamespace +from typing import Any, Optional, TypedDict, Union +from unittest.mock import MagicMock from ..chain_data import ( + AxonInfo, + DelegateInfo, NeuronInfo, NeuronInfoLite, PrometheusInfo, - DelegateInfo, SubnetInfo, - AxonInfo, ) from ..errors import ChainQueryError from ..subtensor import Subtensor from ..utils import RAOPERTAO, U16_NORMALIZED_FLOAT from ..utils.balance import Balance from ..utils.registration import POWSolution - -from typing import TypedDict - +from ..wallet import wallet # Mock Testing Constant __GLOBAL_MOCK_STATE__ = {} @@ -136,12 +132,12 @@ class MockSubtensorValue: class MockMapResult: - records: Optional[List[Tuple[MockSubtensorValue, MockSubtensorValue]]] + records: Optional[list[tuple[MockSubtensorValue, MockSubtensorValue]]] def __init__( self, records: Optional[ - List[Tuple[Union[Any, MockSubtensorValue], Union[Any, MockSubtensorValue]]] + list[tuple[Union[Any, MockSubtensorValue], Union[Any, MockSubtensorValue]]] ] = None, ): _records = [ @@ -170,25 +166,25 @@ def __iter__(self): class MockSystemState(TypedDict): - Account: Dict[str, Dict[int, int]] # address -> block -> balance + Account: dict[str, dict[int, int]] # address -> block -> balance class MockSubtensorState(TypedDict): - Rho: Dict[int, Dict[BlockNumber, int]] # netuid -> block -> rho - Kappa: Dict[int, Dict[BlockNumber, int]] # netuid -> block -> kappa - Difficulty: Dict[int, Dict[BlockNumber, int]] # netuid -> block -> difficulty - ImmunityPeriod: Dict[ - int, Dict[BlockNumber, int] + Rho: dict[int, dict[BlockNumber, int]] # netuid -> block -> rho + Kappa: dict[int, dict[BlockNumber, int]] # netuid -> block -> kappa + Difficulty: dict[int, dict[BlockNumber, int]] # netuid -> block -> difficulty + ImmunityPeriod: dict[ + int, dict[BlockNumber, int] ] # netuid -> block -> immunity_period - ValidatorBatchSize: Dict[ - int, Dict[BlockNumber, int] + ValidatorBatchSize: dict[ + int, dict[BlockNumber, int] ] # netuid -> block -> validator_batch_size - Active: Dict[int, Dict[BlockNumber, bool]] # (netuid, uid), block -> active - Stake: Dict[str, Dict[str, Dict[int, int]]] # (hotkey, coldkey) -> block -> stake + Active: dict[int, dict[BlockNumber, bool]] # (netuid, uid), block -> active + Stake: dict[str, dict[str, dict[int, int]]] # (hotkey, coldkey) -> block -> stake - Delegates: Dict[str, Dict[int, float]] # address -> block -> delegate_take + Delegates: dict[str, dict[int, float]] # address -> block -> delegate_take - NetworksAdded: Dict[int, Dict[BlockNumber, bool]] # netuid -> block -> added + NetworksAdded: dict[int, dict[BlockNumber, bool]] # netuid -> block -> added class MockChainState(TypedDict): @@ -523,7 +519,7 @@ def force_register_neuron( def force_set_balance( self, ss58_address: str, balance: Union["Balance", float, int] = Balance(0) - ) -> Tuple[bool, Optional[str]]: + ) -> tuple[bool, Optional[str]]: """ Returns: Tuple[bool, Optional[str]]: (success, err_msg) @@ -568,7 +564,7 @@ def do_block_step(self) -> None: + 1 ) - def _handle_type_default(self, name: str, params: List[object]) -> object: + def _handle_type_default(self, name: str, params: list[object]) -> object: defaults_mapping = { "TotalStake": 0, "TotalHotkeyStake": 0, @@ -600,7 +596,7 @@ def query_subtensor( self, name: str, block: Optional[int] = None, - params: Optional[List[object]] = [], + params: Optional[list[object]] = [], ) -> MockSubtensorValue: if block: if self.block_number < block: @@ -636,7 +632,7 @@ def query_map_subtensor( self, name: str, block: Optional[int] = None, - params: Optional[List[object]] = [], + params: Optional[list[object]] = [], ) -> Optional[MockMapResult]: """ Note: Double map requires one param @@ -743,7 +739,7 @@ def get_balance(self, address: str, block: int = None) -> "Balance": else: return Balance(0) - def get_balances(self, block: int = None) -> Dict[str, "Balance"]: + def get_balances(self, block: int = None) -> dict[str, "Balance"]: balances = {} for address in self.chain_state["System"]["Account"]: balances[address] = self.get_balance(address, block) @@ -775,7 +771,7 @@ def neuron_for_uid( else: return neuron_info - def neurons(self, netuid: int, block: Optional[int] = None) -> List[NeuronInfo]: + def neurons(self, netuid: int, block: Optional[int] = None) -> list[NeuronInfo]: if netuid not in self.chain_state["SubtensorModule"]["NetworksAdded"]: raise Exception("Subnet does not exist") @@ -792,7 +788,7 @@ def neurons(self, netuid: int, block: Optional[int] = None) -> List[NeuronInfo]: @staticmethod def _get_most_recent_storage( - storage: Dict[BlockNumber, Any], block_number: Optional[int] = None + storage: dict[BlockNumber, Any], block_number: Optional[int] = None ) -> Any: if block_number is None: items = list(storage.items()) @@ -989,7 +985,7 @@ def neuron_for_uid_lite( def neurons_lite( self, netuid: int, block: Optional[int] = None - ) -> List[NeuronInfoLite]: + ) -> list[NeuronInfoLite]: if netuid not in self.chain_state["SubtensorModule"]["NetworksAdded"]: raise Exception("Subnet does not exist") @@ -1056,7 +1052,6 @@ def _do_nominate( wait_for_finalization: bool = False, ) -> bool: hotkey_ss58 = wallet.hotkey.ss58_address - coldkey_ss58 = wallet.coldkeypub.ss58_address subtensor_state = self.chain_state["SubtensorModule"] if self.is_hotkey_delegate(hotkey_ss58=hotkey_ss58): @@ -1082,7 +1077,7 @@ def _do_transfer( transfer_balance: "Balance", wait_for_inclusion: bool = True, wait_for_finalization: bool = False, - ) -> Tuple[bool, Optional[str], Optional[str]]: + ) -> tuple[bool, Optional[str], Optional[str]]: bal = self.get_balance(wallet.coldkeypub.ss58_address) dest_bal = self.get_balance(dest) transfer_fee = self.get_transfer_fee(wallet, dest, transfer_balance) @@ -1114,7 +1109,7 @@ def _do_pow_register( pow_result: "POWSolution", wait_for_inclusion: bool = False, wait_for_finalization: bool = True, - ) -> Tuple[bool, Optional[str]]: + ) -> tuple[bool, Optional[str]]: # Assume pow result is valid subtensor_state = self.chain_state["SubtensorModule"] @@ -1135,7 +1130,7 @@ def _do_burned_register( wallet: "wallet", wait_for_inclusion: bool = False, wait_for_finalization: bool = True, - ) -> Tuple[bool, Optional[str]]: + ) -> tuple[bool, Optional[str]]: subtensor_state = self.chain_state["SubtensorModule"] if netuid not in subtensor_state["NetworksAdded"]: raise Exception("Subnet does not exist") @@ -1184,9 +1179,9 @@ def _do_stake( stake_state = subtensor_state["Stake"] # Stake the funds - if not hotkey_ss58 in stake_state: + if hotkey_ss58 not in stake_state: stake_state[hotkey_ss58] = {} - if not wallet.coldkeypub.ss58_address in stake_state[hotkey_ss58]: + if wallet.coldkeypub.ss58_address not in stake_state[hotkey_ss58]: stake_state[hotkey_ss58][wallet.coldkeypub.ss58_address] = {} stake_state[hotkey_ss58][wallet.coldkeypub.ss58_address][self.block_number] = ( @@ -1199,11 +1194,11 @@ def _do_stake( ) total_hotkey_stake_state = subtensor_state["TotalHotkeyStake"] - if not hotkey_ss58 in total_hotkey_stake_state: + if hotkey_ss58 not in total_hotkey_stake_state: total_hotkey_stake_state[hotkey_ss58] = {} total_coldkey_stake_state = subtensor_state["TotalColdkeyStake"] - if not wallet.coldkeypub.ss58_address in total_coldkey_stake_state: + if wallet.coldkeypub.ss58_address not in total_coldkey_stake_state: total_coldkey_stake_state[wallet.coldkeypub.ss58_address] = {} curr_total_hotkey_stake = self.query_subtensor( @@ -1273,14 +1268,14 @@ def _do_unstake( ) total_hotkey_stake_state = subtensor_state["TotalHotkeyStake"] - if not hotkey_ss58 in total_hotkey_stake_state: + if hotkey_ss58 not in total_hotkey_stake_state: total_hotkey_stake_state[hotkey_ss58] = {} total_hotkey_stake_state[hotkey_ss58][self.block_number] = ( 0 # Shouldn't happen ) total_coldkey_stake_state = subtensor_state["TotalColdkeyStake"] - if not wallet.coldkeypub.ss58_address in total_coldkey_stake_state: + if wallet.coldkeypub.ss58_address not in total_coldkey_stake_state: total_coldkey_stake_state[wallet.coldkeypub.ss58_address] = {} total_coldkey_stake_state[wallet.coldkeypub.ss58_address][ self.block_number @@ -1368,7 +1363,7 @@ def get_delegate_by_hotkey( return info - def get_delegates(self, block: Optional[int] = None) -> List["DelegateInfo"]: + def get_delegates(self, block: Optional[int] = None) -> list["DelegateInfo"]: subtensor_state = self.chain_state["SubtensorModule"] delegates_info = [] for hotkey in subtensor_state["Delegates"]: @@ -1380,7 +1375,7 @@ def get_delegates(self, block: Optional[int] = None) -> List["DelegateInfo"]: def get_delegated( self, coldkey_ss58: str, block: Optional[int] = None - ) -> List[Tuple["DelegateInfo", "Balance"]]: + ) -> list[tuple["DelegateInfo", "Balance"]]: """Returns the list of delegates that a given coldkey is staked to.""" delegates = self.get_delegates(block=block) @@ -1391,7 +1386,7 @@ def get_delegated( return result - def get_all_subnets_info(self, block: Optional[int] = None) -> List[SubnetInfo]: + def get_all_subnets_info(self, block: Optional[int] = None) -> list[SubnetInfo]: subtensor_state = self.chain_state["SubtensorModule"] result = [] for subnet in subtensor_state["NetworksAdded"]: @@ -1444,7 +1439,7 @@ def _do_serve_prometheus( call_params: "PrometheusServeCallParams", wait_for_inclusion: bool = False, wait_for_finalization: bool = True, - ) -> Tuple[bool, Optional[str]]: + ) -> tuple[bool, Optional[str]]: return True, None def _do_set_weights( @@ -1452,11 +1447,11 @@ def _do_set_weights( wallet: "wallet", netuid: int, uids: int, - vals: List[int], + vals: list[int], version_key: int, wait_for_inclusion: bool = False, wait_for_finalization: bool = True, - ) -> Tuple[bool, Optional[str]]: + ) -> tuple[bool, Optional[str]]: return True, None def _do_serve_axon( @@ -1465,5 +1460,5 @@ def _do_serve_axon( call_params: "AxonServeCallParams", wait_for_inclusion: bool = False, wait_for_finalization: bool = True, - ) -> Tuple[bool, Optional[str]]: + ) -> tuple[bool, Optional[str]]: return True, None diff --git a/bittensor/mock/wallet_mock.py b/bittensor/mock/wallet_mock.py index 35179f8c94..0aa6254713 100644 --- a/bittensor/mock/wallet_mock.py +++ b/bittensor/mock/wallet_mock.py @@ -19,10 +19,12 @@ # DEALINGS IN THE SOFTWARE. import os -import bittensor from typing import Optional + from Crypto.Hash import keccak +import bittensor + from .keyfile_mock import MockKeyfile @@ -46,7 +48,7 @@ def __init__(self, **kwargs): @property def hotkey_file(self) -> "bittensor.keyfile": if self._is_mock: - if self._mocked_hotkey_keyfile == None: + if self._mocked_hotkey_keyfile is None: self._mocked_hotkey_keyfile = MockKeyfile(path="MockedHotkey") return self._mocked_hotkey_keyfile else: @@ -57,7 +59,7 @@ def hotkey_file(self) -> "bittensor.keyfile": @property def coldkey_file(self) -> "bittensor.keyfile": if self._is_mock: - if self._mocked_coldkey_keyfile == None: + if self._mocked_coldkey_keyfile is None: self._mocked_coldkey_keyfile = MockKeyfile(path="MockedColdkey") return self._mocked_coldkey_keyfile else: @@ -68,7 +70,7 @@ def coldkey_file(self) -> "bittensor.keyfile": @property def coldkeypub_file(self) -> "bittensor.keyfile": if self._is_mock: - if self._mocked_coldkey_keyfile == None: + if self._mocked_coldkey_keyfile is None: self._mocked_coldkey_keyfile = MockKeyfile(path="MockedColdkeyPub") return self._mocked_coldkey_keyfile else: diff --git a/bittensor/stream.py b/bittensor/stream.py index e0dc17c42c..39671b99b6 100644 --- a/bittensor/stream.py +++ b/bittensor/stream.py @@ -1,11 +1,13 @@ -from aiohttp import ClientResponse -import bittensor +from abc import ABC, abstractmethod +from collections.abc import Awaitable +from typing import Callable +from aiohttp import ClientResponse +from pydantic import BaseModel, ConfigDict from starlette.responses import StreamingResponse as _StreamingResponse -from starlette.types import Send, Receive, Scope -from typing import Callable, Awaitable -from pydantic import ConfigDict, BaseModel -from abc import ABC, abstractmethod +from starlette.types import Receive, Scope, Send + +import bittensor class BTStreamingResponseModel(BaseModel): diff --git a/bittensor/subnets.py b/bittensor/subnets.py index 836a20dcb7..b1e1e4bb6a 100644 --- a/bittensor/subnets.py +++ b/bittensor/subnets.py @@ -17,9 +17,10 @@ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. -import bittensor as bt from abc import ABC, abstractmethod -from typing import Any, List, Union, Optional +from typing import Any, Optional, Union + +import bittensor as bt class SubnetsAPI(ABC): @@ -38,7 +39,7 @@ def prepare_synapse(self, *args, **kwargs) -> Any: ... @abstractmethod - def process_responses(self, responses: List[Union["bt.Synapse", Any]]) -> Any: + def process_responses(self, responses: list[Union["bt.Synapse", Any]]) -> Any: """ Process the responses from the network. """ @@ -46,7 +47,7 @@ def process_responses(self, responses: List[Union["bt.Synapse", Any]]) -> Any: async def query_api( self, - axons: Union[bt.axon, List[bt.axon]], + axons: Union[bt.axon, list[bt.axon]], deserialize: Optional[bool] = False, timeout: Optional[int] = 12, **kwargs: Optional[Any], diff --git a/bittensor/subtensor.py b/bittensor/subtensor.py index 1b422ad276..9e58437c81 100644 --- a/bittensor/subtensor.py +++ b/bittensor/subtensor.py @@ -24,9 +24,8 @@ import argparse import copy import functools -import socket import time -from typing import List, Dict, Union, Optional, Tuple, TypedDict, Any +from typing import Any, Optional, TypedDict, Union import numpy as np import scalecodec @@ -36,24 +35,25 @@ from scalecodec.exceptions import RemainingScaleBytesNotEmptyException from scalecodec.type_registry import load_type_registry_preset from scalecodec.types import GenericCall, ScaleType -from substrateinterface.base import QueryMapResult, SubstrateInterface, ExtrinsicReceipt +from substrateinterface.base import ExtrinsicReceipt, QueryMapResult, SubstrateInterface from substrateinterface.exceptions import SubstrateRequestException import bittensor from bittensor.btlogging import logging as _logger from bittensor.utils import torch, weight_utils + from .chain_data import ( - NeuronInfo, + AxonInfo, DelegateInfo, DelegateInfoLite, - PrometheusInfo, - SubnetInfo, - SubnetHyperparameters, - StakeInfo, + IPInfo, + NeuronInfo, NeuronInfoLite, - AxonInfo, + PrometheusInfo, ProposalVoteData, - IPInfo, + StakeInfo, + SubnetHyperparameters, + SubnetInfo, custom_rpc_type_registry, ) from .errors import IdentityError, NominationError, StakeError, TakeError @@ -62,11 +62,11 @@ reveal_weights_extrinsic, ) from .extrinsics.delegation import ( + decrease_take_extrinsic, delegate_extrinsic, + increase_take_extrinsic, nominate_extrinsic, undelegate_extrinsic, - increase_take_extrinsic, - decrease_take_extrinsic, ) from .extrinsics.network import ( register_subnetwork_extrinsic, @@ -74,22 +74,22 @@ ) from .extrinsics.prometheus import prometheus_extrinsic from .extrinsics.registration import ( - register_extrinsic, burned_register_extrinsic, + register_extrinsic, run_faucet_extrinsic, swap_hotkey_extrinsic, ) from .extrinsics.root import root_register_extrinsic, set_root_weights_extrinsic from .extrinsics.senate import ( - register_senate_extrinsic, leave_senate_extrinsic, + register_senate_extrinsic, vote_senate_extrinsic, ) from .extrinsics.serving import ( - serve_extrinsic, - serve_axon_extrinsic, - publish_metadata, get_metadata, + publish_metadata, + serve_axon_extrinsic, + serve_extrinsic, ) from .extrinsics.set_weights import set_weights_extrinsic from .extrinsics.staking import add_stake_extrinsic, add_stake_multiple_extrinsic @@ -98,16 +98,15 @@ from .types import AxonServeCallParams, PrometheusServeCallParams from .utils import ( U16_NORMALIZED_FLOAT, - ss58_to_vec_u8, U64_NORMALIZED_FLOAT, networking, + ss58_to_vec_u8, ) from .utils.balance import Balance -from .utils.registration import POWSolution -from .utils.registration import legacy_torch_api_compat +from .utils.registration import POWSolution, legacy_torch_api_compat from .utils.subtensor import get_subtensor_errors -KEY_NONCE: Dict[str, int] = {} +KEY_NONCE: dict[str, int] = {} ####### # Monkey patch in caching the convert_type_string method @@ -115,7 +114,7 @@ if hasattr(RuntimeConfiguration, "convert_type_string"): original_convert_type_string = RuntimeConfiguration.convert_type_string - @functools.lru_cache(maxsize=None) + @functools.cache def convert_type_string(_, name): return original_convert_type_string(name) @@ -278,7 +277,7 @@ def __init__( _logger.warning(f"AttributeError: {e}") except TypeError as e: _logger.warning(f"TypeError: {e}") - except (socket.error, OSError) as e: + except OSError as e: _logger.warning(f"Socket error: {e}") if log_verbose: @@ -286,15 +285,15 @@ def __init__( f"Connected to {self.network} network and {self.chain_endpoint}." ) - self._subtensor_errors: Dict[str, Dict[str, str]] = {} + self._subtensor_errors: dict[str, dict[str, str]] = {} def __str__(self) -> str: if self.network == self.chain_endpoint: # Connecting to chain endpoint without network known. - return "subtensor({})".format(self.chain_endpoint) + return f"subtensor({self.chain_endpoint})" else: # Connecting to network with endpoint known. - return "subtensor({}, {})".format(self.network, self.chain_endpoint) + return f"subtensor({self.network}, {self.chain_endpoint})" def __repr__(self) -> str: return self.__str__() @@ -785,7 +784,7 @@ def set_weights( wait_for_finalization: bool = False, prompt: bool = False, max_retries: int = 5, - ) -> Tuple[bool, str]: + ) -> tuple[bool, str]: """ 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 @@ -841,13 +840,13 @@ def set_weights( def _do_set_weights( self, wallet: "bittensor.wallet", - uids: List[int], - vals: List[int], + uids: list[int], + vals: list[int], netuid: int, version_key: int = bittensor.__version_as_int__, wait_for_inclusion: bool = False, wait_for_finalization: bool = False, - ) -> Tuple[bool, Optional[str]]: # (success, error_message) + ) -> tuple[bool, Optional[str]]: # (success, error_message) """ Internal method to send a transaction to the Bittensor blockchain, setting weights for specified neurons. This method constructs and submits the transaction, handling @@ -911,7 +910,7 @@ def commit_weights( self, wallet: "bittensor.wallet", netuid: int, - salt: List[int], + salt: list[int], uids: Union[NDArray[np.int64], list], weights: Union[NDArray[np.int64], list], version_key: int = bittensor.__version_as_int__, @@ -919,7 +918,7 @@ def commit_weights( wait_for_finalization: bool = False, prompt: bool = False, max_retries: int = 5, - ) -> Tuple[bool, str]: + ) -> tuple[bool, str]: """ Commits a hash of the neuron's weights to the Bittensor blockchain using the provided wallet. This action serves as a commitment or snapshot of the neuron's current weight distribution. @@ -948,9 +947,7 @@ def commit_weights( message = "No attempt made. Perhaps it is too soon to commit weights!" _logger.info( - "Committing weights with params: netuid={}, uids={}, weights={}, version_key={}".format( - netuid, uids, weights, version_key - ) + f"Committing weights with params: netuid={netuid}, uids={uids}, weights={weights}, version_key={version_key}" ) # Generate the hash of the weights @@ -963,7 +960,7 @@ def commit_weights( version_key=version_key, ) - _logger.info("Commit Hash: {}".format(commit_hash)) + _logger.info(f"Commit Hash: {commit_hash}") while retries < max_retries: try: @@ -992,7 +989,7 @@ def _do_commit_weights( commit_hash: str, wait_for_inclusion: bool = False, wait_for_finalization: bool = False, - ) -> Tuple[bool, Optional[str]]: + ) -> tuple[bool, Optional[str]]: """ 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. @@ -1057,7 +1054,7 @@ def reveal_weights( wait_for_finalization: bool = False, prompt: bool = False, max_retries: int = 5, - ) -> Tuple[bool, str]: + ) -> tuple[bool, str]: """ Reveals the weights for a specific subnet on the Bittensor blockchain using the provided wallet. This action serves as a revelation of the neuron's previously committed weight distribution. @@ -1112,13 +1109,13 @@ def _do_reveal_weights( self, wallet: "bittensor.wallet", netuid: int, - uids: List[int], - values: List[int], - salt: List[int], + uids: list[int], + values: list[int], + salt: list[int], version_key: int, wait_for_inclusion: bool = False, wait_for_finalization: bool = False, - ) -> Tuple[bool, Optional[str]]: + ) -> tuple[bool, Optional[str]]: """ 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. @@ -1187,7 +1184,7 @@ def register( max_allowed_attempts: int = 3, output_in_place: bool = True, cuda: bool = False, - dev_id: Union[List[int], int] = 0, + dev_id: Union[list[int], int] = 0, tpb: int = 256, num_processes: Optional[int] = None, update_interval: Optional[int] = None, @@ -1282,7 +1279,7 @@ def run_faucet( max_allowed_attempts: int = 3, output_in_place: bool = True, cuda: bool = False, - dev_id: Union[List[int], int] = 0, + dev_id: Union[list[int], int] = 0, tpb: int = 256, num_processes: Optional[int] = None, update_interval: Optional[int] = None, @@ -1377,7 +1374,7 @@ def _do_pow_register( pow_result: POWSolution, wait_for_inclusion: bool = False, wait_for_finalization: bool = True, - ) -> Tuple[bool, Optional[str]]: + ) -> tuple[bool, Optional[str]]: """Sends a (POW) register extrinsic to the chain. Args: @@ -1438,7 +1435,7 @@ def _do_burned_register( wallet: "bittensor.wallet", wait_for_inclusion: bool = False, wait_for_finalization: bool = True, - ) -> Tuple[bool, Optional[str]]: + ) -> tuple[bool, Optional[str]]: """ Performs a burned register extrinsic call to the Subtensor chain. @@ -1495,7 +1492,7 @@ def _do_swap_hotkey( new_wallet: "bittensor.wallet", wait_for_inclusion: bool = False, wait_for_finalization: bool = True, - ) -> Tuple[bool, Optional[str]]: + ) -> tuple[bool, Optional[str]]: """ Performs a hotkey swap extrinsic call to the Subtensor chain. @@ -1625,9 +1622,7 @@ def get_transfer_fee( ) except Exception as e: bittensor.__console__.print( - ":cross_mark: [red]Failed to get payment info[/red]:[bold white]\n {}[/bold white]".format( - e - ) + f":cross_mark: [red]Failed to get payment info[/red]:[bold white]\n {e}[/bold white]" ) payment_info = {"partialFee": int(2e7)} # assume 0.02 Tao @@ -1650,7 +1645,7 @@ def _do_transfer( transfer_balance: "Balance", wait_for_inclusion: bool = True, wait_for_finalization: bool = False, - ) -> Tuple[bool, Optional[str], Optional[str]]: + ) -> tuple[bool, Optional[str], Optional[str]]: """Sends a transfer extrinsic to the chain. Args: @@ -1884,7 +1879,7 @@ def _do_serve_axon( call_params: AxonServeCallParams, wait_for_inclusion: bool = False, wait_for_finalization: bool = True, - ) -> Tuple[bool, Optional[str]]: + ) -> tuple[bool, Optional[str]]: """ 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. @@ -1951,7 +1946,7 @@ def _do_serve_prometheus( call_params: PrometheusServeCallParams, wait_for_inclusion: bool = False, wait_for_finalization: bool = True, - ) -> Tuple[bool, Optional[str]]: + ) -> tuple[bool, Optional[str]]: """ Sends a serve prometheus extrinsic to the chain. Args: @@ -1993,11 +1988,11 @@ def make_substrate_call_with_retry(): def _do_associate_ips( self, wallet: "bittensor.wallet", - ip_info_list: List["IPInfo"], + ip_info_list: list["IPInfo"], netuid: int, wait_for_inclusion: bool = False, wait_for_finalization: bool = True, - ) -> Tuple[bool, Optional[str]]: + ) -> tuple[bool, Optional[str]]: """ Sends an associate IPs extrinsic to the chain. @@ -2086,8 +2081,8 @@ def add_stake( def add_stake_multiple( self, wallet: "bittensor.wallet", - hotkey_ss58s: List[str], - amounts: Optional[List[Union["Balance", float]]] = None, + hotkey_ss58s: list[str], + amounts: Optional[list[Union["Balance", float]]] = None, wait_for_inclusion: bool = True, wait_for_finalization: bool = False, prompt: bool = False, @@ -2175,8 +2170,8 @@ def make_substrate_call_with_retry(): def unstake_multiple( self, wallet: "bittensor.wallet", - hotkey_ss58s: List[str], - amounts: Optional[List[Union["Balance", float]]] = None, + hotkey_ss58s: list[str], + amounts: Optional[list[Union["Balance", float]]] = None, wait_for_inclusion: bool = True, wait_for_finalization: bool = False, prompt: bool = False, @@ -2448,7 +2443,7 @@ def get_vote_data( get_proposal_vote_data = get_vote_data - def get_senate_members(self, block: Optional[int] = None) -> Optional[List[str]]: + def get_senate_members(self, block: Optional[int] = None) -> Optional[list[str]]: """ Retrieves the list of current senate members from the Bittensor blockchain. Senate members are responsible for governance and decision-making within the network. @@ -2492,7 +2487,7 @@ def get_proposal_call_data( return proposal_data.serialize() if proposal_data is not None else None - def get_proposal_hashes(self, block: Optional[int] = None) -> Optional[List[str]]: + def get_proposal_hashes(self, block: Optional[int] = None) -> Optional[list[str]]: """ Retrieves the list of proposal hashes currently present on the Bittensor blockchain. Each hash uniquely identifies a proposal made within the network. @@ -2516,7 +2511,7 @@ def get_proposal_hashes(self, block: Optional[int] = None) -> Optional[List[str] def get_proposals( self, block: Optional[int] = None - ) -> Optional[Dict[str, Tuple["GenericCall", "ProposalVoteData"]]]: + ) -> Optional[dict[str, tuple["GenericCall", "ProposalVoteData"]]]: """ 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 @@ -2532,7 +2527,7 @@ def get_proposals( 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. """ - proposal_hashes: Optional[List[str]] = self.get_proposal_hashes(block=block) + proposal_hashes: Optional[list[str]] = self.get_proposal_hashes(block=block) if proposal_hashes is None: return None return { @@ -2583,7 +2578,7 @@ def _do_root_register( wallet: "bittensor.wallet", wait_for_inclusion: bool = False, wait_for_finalization: bool = True, - ) -> Tuple[bool, Optional[str]]: + ) -> tuple[bool, Optional[str]]: @retry(delay=1, tries=3, backoff=2, max_delay=4, logger=_logger) def make_substrate_call_with_retry(): # create extrinsic call @@ -2996,7 +2991,7 @@ def state_call( method: str, data: str, block: Optional[int] = None, - ) -> Dict[Any, Any]: + ) -> dict[Any, Any]: """ Makes a state call to the Bittensor blockchain, allowing for direct queries of the blockchain's state. This function is typically used for advanced queries that require specific method calls and data inputs. @@ -3014,7 +3009,7 @@ def state_call( """ @retry(delay=1, tries=3, backoff=2, max_delay=4, logger=_logger) - def make_substrate_call_with_retry() -> Dict[Any, Any]: + def make_substrate_call_with_retry() -> dict[Any, Any]: block_hash = None if block is None else self.substrate.get_block_hash(block) return self.substrate.rpc_request( @@ -3028,7 +3023,7 @@ def query_runtime_api( self, runtime_api: str, method: str, - params: Optional[Union[List[int], Dict[str, int]]], + params: Optional[Union[list[int], dict[str, int]]], block: Optional[int] = None, ) -> Optional[str]: """ @@ -3081,15 +3076,15 @@ def query_runtime_api( def _encode_params( self, - call_definition: List["ParamWithTypes"], - params: Union[List[Any], Dict[str, Any]], + call_definition: list["ParamWithTypes"], + params: Union[list[Any], dict[str, Any]], ) -> str: """Returns a hex encoded string of the params using their types.""" param_data = scalecodec.ScaleBytes(b"") for i, param in enumerate(call_definition["params"]): # type: ignore scale_obj = self.substrate.create_scale_object(param["type"]) - if type(params) is list: + if type(params) is list: # noqa: E721 param_data += scale_obj.encode(params[i]) else: if param["name"] not in params: @@ -3688,7 +3683,7 @@ def get_stake_for_coldkey_and_hotkey( def get_stake( self, hotkey_ss58: str, block: Optional[int] = None - ) -> List[Tuple[str, "Balance"]]: + ) -> list[tuple[str, "Balance"]]: """ Returns a list of stake tuples (coldkey, balance) for each delegating coldkey including the owner. @@ -3929,7 +3924,7 @@ def subnet_exists(self, netuid: int, block: Optional[int] = None) -> bool: _result = self.query_subtensor("NetworksAdded", block, [netuid]) return getattr(_result, "value", False) - def get_all_subnet_netuids(self, block: Optional[int] = None) -> List[int]: + def get_all_subnet_netuids(self, block: Optional[int] = None) -> list[int]: """ Retrieves the list of all subnet unique identifiers (netuids) currently present in the Bittensor network. @@ -4013,7 +4008,7 @@ def get_emission_value_by_subnet( def get_subnet_connection_requirements( self, netuid: int, block: Optional[int] = None - ) -> Dict[str, int]: + ) -> dict[str, int]: """ Retrieves the connection requirements for a specific subnet within the Bittensor network. This function provides details on the criteria that must be met for neurons to connect to the subnet. @@ -4035,7 +4030,7 @@ def get_subnet_connection_requirements( else {} ) - def get_subnets(self, block: Optional[int] = None) -> List[int]: + def get_subnets(self, block: Optional[int] = None) -> list[int]: """ Retrieves a list of all subnets currently active within the Bittensor network. This function provides an overview of the various subnets and their identifiers. @@ -4056,7 +4051,7 @@ def get_subnets(self, block: Optional[int] = None) -> List[int]: else [] ) - def get_all_subnets_info(self, block: Optional[int] = None) -> List[SubnetInfo]: + def get_all_subnets_info(self, block: Optional[int] = None) -> list[SubnetInfo]: """ Retrieves detailed information about all subnets within the Bittensor network. This function provides comprehensive data on each subnet, including its characteristics and operational parameters. @@ -4123,7 +4118,7 @@ def make_substrate_call_with_retry(): def get_subnet_hyperparameters( self, netuid: int, block: Optional[int] = None - ) -> Optional[Union[List, SubnetHyperparameters]]: + ) -> Optional[Union[list, SubnetHyperparameters]]: """ Retrieves the hyperparameters for a specific subnet within the Bittensor network. These hyperparameters define the operational settings and rules governing the subnet's behavior. @@ -4223,7 +4218,7 @@ def get_delegate_take( def get_nominators_for_hotkey( self, hotkey_ss58: str, block: Optional[int] = None - ) -> Union[List[Tuple[str, Balance]], int]: + ) -> Union[list[tuple[str, Balance]], int]: """ Retrieves a list of nominators and their stakes for a neuron identified by its hotkey. Nominators are neurons that stake their tokens on a delegate to support its operations. @@ -4264,7 +4259,7 @@ def get_delegate_by_hotkey( """ @retry(delay=1, tries=3, backoff=2, max_delay=4, logger=_logger) - def make_substrate_call_with_retry(encoded_hotkey_: List[int]): + def make_substrate_call_with_retry(encoded_hotkey_: list[int]): block_hash = None if block is None else self.substrate.get_block_hash(block) return self.substrate.rpc_request( @@ -4282,7 +4277,7 @@ def make_substrate_call_with_retry(encoded_hotkey_: List[int]): return DelegateInfo.from_vec_u8(result) - def get_delegates_lite(self, block: Optional[int] = None) -> List[DelegateInfoLite]: + def get_delegates_lite(self, block: Optional[int] = None) -> list[DelegateInfoLite]: """ Retrieves a lighter list of all delegate neurons within the Bittensor network. This function provides an overview of the neurons that are actively involved in the network's delegation system. @@ -4316,7 +4311,7 @@ def make_substrate_call_with_retry(): return [DelegateInfoLite(**d) for d in result] - def get_delegates(self, block: Optional[int] = None) -> List[DelegateInfo]: + def get_delegates(self, block: Optional[int] = None) -> list[DelegateInfo]: """ Retrieves a list of all delegate neurons within the Bittensor network. This function provides an overview of the neurons that are actively involved in the network's delegation system. @@ -4352,7 +4347,7 @@ def make_substrate_call_with_retry(): def get_delegated( self, coldkey_ss58: str, block: Optional[int] = None - ) -> List[Tuple[DelegateInfo, Balance]]: + ) -> list[tuple[DelegateInfo, Balance]]: """ Retrieves a list of delegates and their associated stakes for a given coldkey. This function identifies the delegates that a specific account has staked tokens on. @@ -4370,7 +4365,7 @@ def get_delegated( """ @retry(delay=1, tries=3, backoff=2, max_delay=4, logger=_logger) - def make_substrate_call_with_retry(encoded_coldkey_: List[int]): + def make_substrate_call_with_retry(encoded_coldkey_: list[int]): block_hash = None if block is None else self.substrate.get_block_hash(block) return self.substrate.rpc_request( @@ -4394,7 +4389,7 @@ def make_substrate_call_with_retry(encoded_coldkey_: List[int]): def get_stake_info_for_coldkey( self, coldkey_ss58: str, block: Optional[int] = None - ) -> Optional[List[StakeInfo]]: + ) -> Optional[list[StakeInfo]]: """ Retrieves stake information associated with a specific coldkey. This function provides details about the stakes held by an account, including the staked amounts and associated delegates. @@ -4429,8 +4424,8 @@ def get_stake_info_for_coldkey( return StakeInfo.list_from_vec_u8(bytes_result) # type: ignore def get_stake_info_for_coldkeys( - self, coldkey_ss58_list: List[str], block: Optional[int] = None - ) -> Optional[Dict[str, List[StakeInfo]]]: + self, coldkey_ss58_list: list[str], block: Optional[int] = None + ) -> Optional[dict[str, list[StakeInfo]]]: """ Retrieves stake information for a list of coldkeys. This function aggregates stake data for multiple accounts, providing a collective view of their stakes and delegations. @@ -4584,7 +4579,7 @@ def get_uid_for_hotkey_on_subnet( def get_all_uids_for_hotkey( self, hotkey_ss58: str, block: Optional[int] = None - ) -> List[int]: + ) -> list[int]: """ Retrieves all unique identifiers (UIDs) associated with a given hotkey across different subnets within the Bittensor network. This function helps in identifying all the neuron instances that are @@ -4607,7 +4602,7 @@ def get_all_uids_for_hotkey( def get_netuids_for_hotkey( self, hotkey_ss58: str, block: Optional[int] = None - ) -> List[int]: + ) -> list[int]: """ Retrieves a list of subnet UIDs (netuids) for which a given hotkey is a member. This function identifies the specific subnets within the Bittensor network where the neuron associated with @@ -4654,7 +4649,7 @@ def get_neuron_for_pubkey_and_subnet( def get_all_neurons_for_pubkey( self, hotkey_ss58: str, block: Optional[int] = None - ) -> List[NeuronInfo]: + ) -> list[NeuronInfo]: """ Retrieves information about all neuron instances associated with a given public key (hotkey ``SS58`` address) across different subnets of the Bittensor network. This function aggregates neuron data @@ -4759,7 +4754,7 @@ def make_substrate_call_with_retry(): return NeuronInfo.from_vec_u8(result) - def neurons(self, netuid: int, block: Optional[int] = None) -> List[NeuronInfo]: + def neurons(self, netuid: int, block: Optional[int] = None) -> list[NeuronInfo]: """ Retrieves a list of all neurons within a specified subnet of the Bittensor network. This function provides a snapshot of the subnet's neuron population, including each neuron's attributes and network @@ -4834,7 +4829,7 @@ def neuron_for_uid_lite( def neurons_lite( self, netuid: int, block: Optional[int] = None - ) -> List[NeuronInfoLite]: + ) -> list[NeuronInfoLite]: """ Retrieves a list of neurons in a 'lite' format from a specific subnet of the Bittensor network. This function provides a streamlined view of the neurons, focusing on key attributes such as stake @@ -4896,7 +4891,7 @@ def metagraph( return metagraph_ - def incentive(self, netuid: int, block: Optional[int] = None) -> List[int]: + def incentive(self, netuid: int, block: Optional[int] = None) -> list[int]: """ Retrieves the list of incentives for neurons within a specific subnet of the Bittensor network. This function provides insights into the reward distribution mechanisms and the incentives allocated @@ -4924,7 +4919,7 @@ def incentive(self, netuid: int, block: Optional[int] = None) -> List[int]: def weights( self, netuid: int, block: Optional[int] = None - ) -> List[Tuple[int, List[Tuple[int, int]]]]: + ) -> list[tuple[int, list[tuple[int, int]]]]: """ Retrieves the weight distribution set by neurons within a specific subnet of the Bittensor network. This function maps each neuron's UID to the weights it assigns to other neurons, reflecting the @@ -4952,7 +4947,7 @@ def weights( def bonds( self, netuid: int, block: Optional[int] = None - ) -> List[Tuple[int, List[Tuple[int, int]]]]: + ) -> list[tuple[int, list[tuple[int, int]]]]: """ Retrieves the bond distribution set by neurons within a specific subnet of the Bittensor network. Bonds represent the investments or commitments made by neurons in one another, indicating a level @@ -4983,7 +4978,7 @@ def bonds( def associated_validator_ip_info( self, netuid: int, block: Optional[int] = None - ) -> Optional[List["IPInfo"]]: + ) -> Optional[list["IPInfo"]]: """ Retrieves the list of all validator IP addresses associated with a specific subnet in the Bittensor network. This information is crucial for network communication and the identification of validator nodes. @@ -5366,7 +5361,7 @@ def make_substrate_call_with_retry(): return make_substrate_call_with_retry() - def get_balances(self, block: Optional[int] = None) -> Dict[str, Balance]: + def get_balances(self, block: Optional[int] = None) -> dict[str, Balance]: """ Retrieves the token balances of all accounts within the Bittensor network as of a specific blockchain block. This function provides a comprehensive view of the token distribution among different accounts. @@ -5443,7 +5438,7 @@ def get_block_hash(self, block_id: int) -> str: """ return self.substrate.get_block_hash(block_id=block_id) - def get_error_info_by_index(self, error_index: int) -> Tuple[str, str]: + def get_error_info_by_index(self, error_index: int) -> tuple[str, str]: """ Returns the error name and description from the Subtensor error list. diff --git a/bittensor/synapse.py b/bittensor/synapse.py index 53c53f0083..8d0f3c42e0 100644 --- a/bittensor/synapse.py +++ b/bittensor/synapse.py @@ -21,6 +21,7 @@ import json import sys import warnings +from typing import Any, ClassVar, Optional from pydantic import ( BaseModel, @@ -29,8 +30,8 @@ field_validator, model_validator, ) + import bittensor -from typing import Optional, Any, Dict, ClassVar, Tuple def get_size(obj, seen=None) -> int: @@ -481,7 +482,7 @@ def set_name_type(cls, values) -> dict: repr=False, ) - required_hash_fields: ClassVar[Tuple[str, ...]] = () + required_hash_fields: ClassVar[tuple[str, ...]] = () _extract_total_size = field_validator("total_size", mode="before")(cast_int) @@ -756,7 +757,7 @@ def parse_headers_to_inputs(cls, headers: dict) -> dict: """ # Initialize the input dictionary with empty sub-dictionaries for 'axon' and 'dendrite' - inputs_dict: Dict[str, Dict[str, str]] = {"axon": {}, "dendrite": {}} + inputs_dict: dict[str, dict[str, str]] = {"axon": {}, "dendrite": {}} # Iterate over each item in the headers for key, value in headers.items(): diff --git a/bittensor/tensor.py b/bittensor/tensor.py index ab46560d99..02f1b68fb4 100644 --- a/bittensor/tensor.py +++ b/bittensor/tensor.py @@ -16,13 +16,15 @@ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. -import numpy as np import base64 +from typing import Optional, Union + import msgpack import msgpack_numpy -from typing import Optional, Union, List +import numpy as np +from pydantic import BaseModel, ConfigDict, Field, field_validator + from bittensor.utils.registration import torch, use_torch -from pydantic import ConfigDict, BaseModel, Field, field_validator class DTypes(dict): @@ -105,7 +107,7 @@ def cast_dtype(raw: Union[None, np.dtype, "torch.dtype", str]) -> Optional[str]: ) -def cast_shape(raw: Union[None, List[int], str]) -> Optional[Union[str, list]]: +def cast_shape(raw: Union[None, list[int], str]) -> Optional[Union[str, list]]: """ Casts the raw value to a string representing the tensor shape. @@ -156,7 +158,7 @@ class Tensor(BaseModel): def tensor(self) -> Union[np.ndarray, "torch.Tensor"]: return self.deserialize() - def tolist(self) -> List[object]: + def tolist(self) -> list[object]: return self.deserialize().tolist() def numpy(self) -> "numpy.ndarray": @@ -235,7 +237,7 @@ def serialize(tensor_: Union["np.ndarray", "torch.Tensor"]) -> "Tensor": ) # Represents the shape of the tensor. - shape: List[int] = Field( + shape: list[int] = Field( title="shape", description="Tensor shape. This field defines the dimensions of the tensor as a list of integers, such as [10, 10] for a 2D tensor with shape (10, 10).", examples=[10, 10], diff --git a/bittensor/threadpool.py b/bittensor/threadpool.py index 3e49786ff6..633f35bbe3 100644 --- a/bittensor/threadpool.py +++ b/bittensor/threadpool.py @@ -5,21 +5,20 @@ __author__ = "Brian Quinlan (brian@sweetapp.com)" +import argparse +import itertools +import logging import os -import sys -import time import queue import random -import weakref -import logging -import argparse -import bittensor -import itertools +import sys import threading - -from typing import Callable +import time +import weakref from concurrent.futures import _base +from typing import Callable +import bittensor from bittensor.btlogging.defines import BITTENSOR_LOGGER_NAME # Workers are created as daemon threads. This is done to allow the interpreter @@ -42,7 +41,7 @@ _shutdown = False -class _WorkItem(object): +class _WorkItem: def __init__(self, future, fn, start_time, args, kwargs): self.future = future self.fn = fn @@ -168,16 +167,16 @@ def __init__( @classmethod def add_args(cls, parser: argparse.ArgumentParser, prefix: str = None): """Accept specific arguments from parser""" - prefix_str = "" if prefix == None else prefix + "." + prefix_str = "" if prefix is None else prefix + "." try: default_max_workers = ( os.getenv("BT_PRIORITY_MAX_WORKERS") - if os.getenv("BT_PRIORITY_MAX_WORKERS") != None + if os.getenv("BT_PRIORITY_MAX_WORKERS") is not None else 5 ) default_maxsize = ( os.getenv("BT_PRIORITY_MAXSIZE") - if os.getenv("BT_PRIORITY_MAXSIZE") != None + if os.getenv("BT_PRIORITY_MAXSIZE") is not None else 10 ) parser.add_argument( diff --git a/bittensor/utils/__init__.py b/bittensor/utils/__init__.py index 175094da87..3f8c1b4183 100644 --- a/bittensor/utils/__init__.py +++ b/bittensor/utils/__init__.py @@ -1,42 +1,47 @@ # The MIT License (MIT) # Copyright © 2022 Opentensor Foundation # Copyright © 2023 Opentensor Technologies Inc -import os - +# # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated # documentation files (the “Software”), to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, # and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - # The above copyright notice and this permission notice shall be included in all copies or substantial portions of # the Software. - # THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO # THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. -from typing import Callable, List, Dict, Literal, Tuple - -import bittensor import hashlib +from typing import Callable, Literal, Optional, Union + +import numpy as np import requests import scalecodec -import numpy as np -from .wallet_utils import * # noqa F401 -from .version import version_checking, check_version, VersionCheckError +import bittensor + from .registration import torch, use_torch +from .version import VersionCheckError, check_version, version_checking +from .wallet_utils import ( + create_identity_dict, + decode_hex_identity_dict, + get_ss58_format, + is_valid_bittensor_address_or_public_key, + is_valid_ed25519_pubkey, + is_valid_ss58_address, +) RAOPERTAO = 1e9 U16_MAX = 65535 U64_MAX = 18446744073709551615 -def ss58_to_vec_u8(ss58_address: str) -> List[int]: +def ss58_to_vec_u8(ss58_address: str) -> list[int]: ss58_bytes: bytes = bittensor.utils.ss58_address_to_bytes(ss58_address) - encoded_address: List[int] = [int(byte) for byte in ss58_bytes] + encoded_address: list[int] = [int(byte) for byte in ss58_bytes] return encoded_address @@ -48,7 +53,7 @@ def _unbiased_topk( largest=True, axis=0, return_type: str = "numpy", -) -> Union[Tuple[np.ndarray, np.ndarray], Tuple["torch.Tensor", "torch.LongTensor"]]: +) -> Union[tuple[np.ndarray, np.ndarray], tuple["torch.Tensor", "torch.LongTensor"]]: """Selects topk as in torch.topk but does not bias lower indices when values are equal. Args: values: (np.ndarray) if using numpy, (torch.Tensor) if using torch: @@ -102,7 +107,7 @@ def unbiased_topk( sorted: bool = True, largest: bool = True, axis: int = 0, -) -> Union[Tuple[np.ndarray, np.ndarray], Tuple["torch.Tensor", "torch.LongTensor"]]: +) -> Union[tuple[np.ndarray, np.ndarray], tuple["torch.Tensor", "torch.LongTensor"]]: """Selects topk as in torch.topk but does not bias lower indices when values are equal. Args: values: (np.ndarray) if using numpy, (torch.Tensor) if using torch: @@ -164,12 +169,12 @@ def strtobool(val: str) -> Union[bool, Literal["==SUPRESS=="]]: elif val in ("n", "no", "f", "false", "off", "0"): return False else: - raise ValueError("invalid truth value %r" % (val,)) + raise ValueError(f"invalid truth value {val!r}") def get_explorer_root_url_by_network_from_map( - network: str, network_map: Dict[str, Dict[str, str]] -) -> Optional[Dict[str, str]]: + network: str, network_map: dict[str, dict[str, str]] +) -> Optional[dict[str, str]]: r""" Returns the explorer root url for the given network name from the given network map. @@ -181,7 +186,7 @@ def get_explorer_root_url_by_network_from_map( The explorer url for the given network. Or None if the network is not in the network map. """ - explorer_urls: Optional[Dict[str, str]] = {} + explorer_urls: Optional[dict[str, str]] = {} for entity_nm, entity_network_map in network_map.items(): if network in entity_network_map: explorer_urls[entity_nm] = entity_network_map[network] @@ -190,8 +195,8 @@ def get_explorer_root_url_by_network_from_map( def get_explorer_url_for_network( - network: str, block_hash: str, network_map: Dict[str, str] -) -> Optional[List[str]]: + network: str, block_hash: str, network_map: dict[str, str] +) -> Optional[list[str]]: r""" Returns the explorer url for the given block hash and network. @@ -205,9 +210,9 @@ def get_explorer_url_for_network( Or None if the network is not known. """ - explorer_urls: Optional[Dict[str, str]] = {} + explorer_urls: Optional[dict[str, str]] = {} # Will be None if the network is not known. i.e. not in network_map - explorer_root_urls: Optional[Dict[str, str]] = ( + explorer_root_urls: Optional[dict[str, str]] = ( get_explorer_root_url_by_network_from_map(network, network_map) ) @@ -241,7 +246,7 @@ def U64_NORMALIZED_FLOAT(x: int) -> float: return float(x) / float(U64_MAX) -def u8_key_to_ss58(u8_key: List[int]) -> str: +def u8_key_to_ss58(u8_key: list[int]) -> str: r""" Converts a u8-encoded account key to an ss58 address. diff --git a/bittensor/utils/_register_cuda.py b/bittensor/utils/_register_cuda.py index 05619416e4..74147ca5e4 100644 --- a/bittensor/utils/_register_cuda.py +++ b/bittensor/utils/_register_cuda.py @@ -1,14 +1,12 @@ import binascii import hashlib +import io import math -from typing import Tuple +from contextlib import redirect_stdout import numpy as np from Crypto.Hash import keccak -from contextlib import redirect_stdout -import io - def solve_cuda( nonce_start: np.int64, @@ -18,7 +16,7 @@ def solve_cuda( difficulty: int, limit: int, dev_id: int = 0, -) -> Tuple[np.int64, bytes]: +) -> tuple[np.int64, bytes]: """ Solves the PoW problem using CUDA. Args: diff --git a/bittensor/utils/balance.py b/bittensor/utils/balance.py index 63ca6cd5ba..2917aa179c 100644 --- a/bittensor/utils/balance.py +++ b/bittensor/utils/balance.py @@ -226,12 +226,6 @@ def __rfloordiv__(self, other: Union[int, float, "Balance"]): except (ValueError, TypeError): raise NotImplementedError("Unsupported type") - def __int__(self) -> int: - return self.rao - - def __float__(self) -> float: - return self.tao - def __nonzero__(self) -> bool: return bool(self.rao) diff --git a/bittensor/utils/formatting.py b/bittensor/utils/formatting.py index 1e93ce8340..9e4a1541c8 100644 --- a/bittensor/utils/formatting.py +++ b/bittensor/utils/formatting.py @@ -19,4 +19,4 @@ def millify(n: int): ), ) - return "{:.2f}{}".format(n / 10 ** (3 * millidx), millnames[millidx]) + return f"{n / 10 ** (3 * millidx):.2f}{millnames[millidx]}" diff --git a/bittensor/utils/networking.py b/bittensor/utils/networking.py index 0437aff80f..45f98db9ac 100644 --- a/bittensor/utils/networking.py +++ b/bittensor/utils/networking.py @@ -19,9 +19,10 @@ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. +import json import os import urllib -import json + import netaddr import requests @@ -187,6 +188,6 @@ def get_formatted_ws_endpoint_url(endpoint_url: str) -> str: The formatted endpoint url. In the form of ws:// or wss:// """ if endpoint_url[0:6] != "wss://" and endpoint_url[0:5] != "ws://": - endpoint_url = "ws://{}".format(endpoint_url) + endpoint_url = f"ws://{endpoint_url}" return endpoint_url diff --git a/bittensor/utils/registration.py b/bittensor/utils/registration.py index 6c504b05f1..18846dbede 100644 --- a/bittensor/utils/registration.py +++ b/bittensor/utils/registration.py @@ -10,18 +10,18 @@ from dataclasses import dataclass from datetime import timedelta from queue import Empty, Full -from typing import Any, Callable, Dict, List, Optional, Tuple, Union +from typing import Any, Callable, Optional, Union import backoff import numpy - -import bittensor from Crypto.Hash import keccak from rich import console as rich_console from rich import status as rich_status -from .formatting import get_human_readable, millify +import bittensor + from ._register_cuda import solve_cuda +from .formatting import get_human_readable, millify def use_torch() -> bool: @@ -133,7 +133,7 @@ class POWSolution: difficulty: int seal: bytes - def is_stale(self, subtensor: "bittensor.subtensor") -> bool: + def is_stale(self, subtensor: "bittensor.Subtensor") -> bool: """Returns True if the POW is stale. This means the block the POW is solved for is within 3 blocks of the current block. """ @@ -231,7 +231,7 @@ def run(self): @staticmethod def create_shared_memory() -> ( - Tuple[multiprocessing.Array, multiprocessing.Value, multiprocessing.Array] + tuple[multiprocessing.Array, multiprocessing.Value, multiprocessing.Array] ): """Creates shared memory for the solver processes to use.""" curr_block = multiprocessing.Array("h", 32, lock=True) # byte array @@ -561,7 +561,7 @@ def _solve_for_difficulty_fast( while still updating the block information after a different number of nonces, to increase the transparency of the process while still keeping the speed. """ - if num_processes == None: + if num_processes is None: # get the number of allowed processes for this process num_processes = min(1, get_cpu_count()) @@ -684,7 +684,7 @@ def _solve_for_difficulty_fast( num_time = 0 for finished_queue in finished_queues: try: - proc_num = finished_queue.get(timeout=0.1) + finished_queue.get(timeout=0.1) num_time += 1 except Empty: @@ -734,8 +734,8 @@ def _solve_for_difficulty_fast( @backoff.on_exception(backoff.constant, Exception, interval=1, max_tries=3) def _get_block_with_retry( - subtensor: "bittensor.subtensor", netuid: int -) -> Tuple[int, int, bytes]: + subtensor: "bittensor.Subtensor", netuid: int +) -> tuple[int, int, bytes]: """ Gets the current block number, difficulty, and block hash from the substrate node. @@ -779,7 +779,7 @@ def __init__(self, force: bool = False): def __enter__(self): self._old_start_method = multiprocessing.get_start_method(allow_none=True) - if self._old_start_method == None: + if self._old_start_method is None: self._old_start_method = "spawn" # default to spawn multiprocessing.set_start_method("spawn", force=self._force) @@ -790,7 +790,7 @@ def __exit__(self, *args): def _check_for_newest_block_and_update( - subtensor: "bittensor.subtensor", + subtensor: "bittensor.Subtensor", netuid: int, old_block_number: int, hotkey_bytes: bytes, @@ -799,7 +799,7 @@ def _check_for_newest_block_and_update( curr_block_num: multiprocessing.Value, update_curr_block: Callable, check_block: "multiprocessing.Lock", - solvers: List[_Solver], + solvers: list[_Solver], curr_stats: RegistrationStatistics, ) -> int: """ @@ -865,13 +865,13 @@ def _check_for_newest_block_and_update( def _solve_for_difficulty_fast_cuda( - subtensor: "bittensor.subtensor", + subtensor: "bittensor.Subtensor", wallet: "bittensor.wallet", netuid: int, output_in_place: bool = True, update_interval: int = 50_000, tpb: int = 512, - dev_id: Union[List[int], int] = 0, + dev_id: Union[list[int], int] = 0, n_samples: int = 10, alpha_: float = 0.80, log_verbose: bool = False, @@ -1032,7 +1032,7 @@ def _solve_for_difficulty_fast_cuda( # Get times for each solver for finished_queue in finished_queues: try: - proc_num = finished_queue.get(timeout=0.1) + finished_queue.get(timeout=0.1) num_time += 1 except Empty: @@ -1082,7 +1082,7 @@ def _solve_for_difficulty_fast_cuda( def _terminate_workers_and_wait_for_exit( - workers: List[multiprocessing.Process], + workers: list[multiprocessing.Process], ) -> None: for worker in workers: worker.terminate() @@ -1095,12 +1095,12 @@ def create_pow( netuid: int, output_in_place: bool = True, cuda: bool = False, - dev_id: Union[List[int], int] = 0, + dev_id: Union[list[int], int] = 0, tpb: int = 256, num_processes: int = None, update_interval: int = None, log_verbose: bool = False, -) -> Optional[Dict[str, Any]]: +) -> Optional[dict[str, Any]]: """ Creates a proof of work for the given subtensor and wallet. Args: diff --git a/bittensor/utils/subtensor.py b/bittensor/utils/subtensor.py index 484184e77f..44bef0e005 100644 --- a/bittensor/utils/subtensor.py +++ b/bittensor/utils/subtensor.py @@ -22,7 +22,7 @@ import json import logging import os -from typing import Dict, Optional, Union, Any +from typing import Any, Optional, Union from substrateinterface.base import SubstrateInterface @@ -41,7 +41,7 @@ # https://github.com/polkascan/py-scale-codec/blob/master/scalecodec/type_registry/core.json#L1024 # A class object is created dynamically at runtime. # Circleci linter complains about string represented classes like 'PalletMetadataV14'. -def _get_errors_from_pallet(pallet) -> Optional[Dict[str, Dict[str, str]]]: +def _get_errors_from_pallet(pallet) -> Optional[dict[str, dict[str, str]]]: """Extracts and returns error information from the given pallet metadata. Args: @@ -68,7 +68,7 @@ def _get_errors_from_pallet(pallet) -> Optional[Dict[str, Dict[str, str]]]: } -def _save_errors_to_cache(uniq_version: str, errors: Dict[str, Dict[str, str]]): +def _save_errors_to_cache(uniq_version: str, errors: dict[str, dict[str, str]]): """Saves error details and unique version identifier to a JSON file. Args: @@ -79,11 +79,11 @@ def _save_errors_to_cache(uniq_version: str, errors: Dict[str, Dict[str, str]]): try: with open(_ERRORS_FILE_PATH, "w") as json_file: json.dump(data, json_file, indent=4) - except IOError as e: + except OSError as e: _logger.warning(f"Error saving to file: {e}") -def _get_errors_from_cache() -> Optional[Dict[str, Dict[str, Dict[str, str]]]]: +def _get_errors_from_cache() -> Optional[dict[str, dict[str, dict[str, str]]]]: """Retrieves and returns the cached error information from a JSON file, if it exists. Returns: @@ -93,9 +93,9 @@ def _get_errors_from_cache() -> Optional[Dict[str, Dict[str, Dict[str, str]]]]: return None try: - with open(_ERRORS_FILE_PATH, "r") as json_file: + with open(_ERRORS_FILE_PATH) as json_file: data = json.load(json_file) - except IOError as e: + except OSError as e: _logger.warning(f"Error reading from file: {e}") return None @@ -104,7 +104,7 @@ def _get_errors_from_cache() -> Optional[Dict[str, Dict[str, Dict[str, str]]]]: def get_subtensor_errors( substrate: SubstrateInterface, -) -> Union[Dict[str, Dict[str, str]], Dict[Any, Any]]: +) -> Union[dict[str, dict[str, str]], dict[Any, Any]]: """Fetches or retrieves cached Subtensor error definitions using metadata. Args: diff --git a/bittensor/utils/test_utils.py b/bittensor/utils/test_utils.py index fdaa1bda95..6113554c0b 100644 --- a/bittensor/utils/test_utils.py +++ b/bittensor/utils/test_utils.py @@ -1,11 +1,10 @@ import socket from random import randint -from typing import Set max_tries = 10 -def get_random_unused_port(allocated_ports: Set = set()): +def get_random_unused_port(allocated_ports: set = set()): def port_in_use(port: int) -> bool: with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: return s.connect_ex(("localhost", port)) == 0 diff --git a/bittensor/utils/version.py b/bittensor/utils/version.py index 2a5aa3cd57..6892778d0b 100644 --- a/bittensor/utils/version.py +++ b/bittensor/utils/version.py @@ -1,10 +1,11 @@ -from typing import Optional -from pathlib import Path import time +from pathlib import Path +from typing import Optional + +import requests from packaging.version import Version import bittensor -import requests VERSION_CHECK_THRESHOLD = 86400 @@ -76,10 +77,8 @@ def check_version(timeout: int = 15): if Version(latest_version) > Version(bittensor.__version__): print( - "\u001b[33mBittensor Version: Current {}/Latest {}\nPlease update to the latest version at your earliest convenience. " - "Run the following command to upgrade:\n\n\u001b[0mpython -m pip install --upgrade bittensor".format( - bittensor.__version__, latest_version - ) + f"\u001b[33mBittensor Version: Current {bittensor.__version__}/Latest {latest_version}\nPlease update to the latest version at your earliest convenience. " + "Run the following command to upgrade:\n\n\u001b[0mpython -m pip install --upgrade bittensor" ) except Exception as e: raise VersionCheckError("Version check failed") from e diff --git a/bittensor/utils/wallet_utils.py b/bittensor/utils/wallet_utils.py index 39218c33f0..01544898ac 100644 --- a/bittensor/utils/wallet_utils.py +++ b/bittensor/utils/wallet_utils.py @@ -17,11 +17,12 @@ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. +from typing import Optional, Union + +from substrateinterface import Keypair as Keypair from substrateinterface.utils import ss58 -from typing import Union, Optional from .. import __ss58_format__ -from substrateinterface import Keypair as Keypair def get_ss58_format(ss58_address: str) -> int: diff --git a/bittensor/utils/weight_utils.py b/bittensor/utils/weight_utils.py index 42f0a88380..8c55b61ac4 100644 --- a/bittensor/utils/weight_utils.py +++ b/bittensor/utils/weight_utils.py @@ -20,15 +20,15 @@ # DEALINGS IN THE SOFTWARE. import hashlib -from typing import Tuple, List, Union +from typing import Union import numpy as np from numpy.typing import NDArray -from scalecodec import ScaleBytes, U16, Vec +from scalecodec import U16, ScaleBytes, Vec from substrateinterface import Keypair import bittensor -from bittensor.utils.registration import torch, use_torch, legacy_torch_api_compat +from bittensor.utils.registration import legacy_torch_api_compat, torch, use_torch U32_MAX = 4294967295 U16_MAX = 65535 @@ -85,7 +85,7 @@ def normalize_max_weight( def convert_weight_uids_and_vals_to_tensor( - n: int, uids: List[int], weights: List[int] + n: int, uids: list[int], weights: list[int] ) -> Union[NDArray[np.float32], "torch.FloatTensor"]: r"""Converts weights and uids from chain representation into a np.array (inverse operation from convert_weights_and_uids_for_emit) Args: @@ -115,7 +115,7 @@ def convert_weight_uids_and_vals_to_tensor( def convert_root_weight_uids_and_vals_to_tensor( - n: int, uids: List[int], weights: List[int], subnets: List[int] + n: int, uids: list[int], weights: list[int], subnets: list[int] ) -> Union[NDArray[np.float32], "torch.FloatTensor"]: r"""Converts root weights and uids from chain representation into a np.array or torch FloatTensor (inverse operation from convert_weights_and_uids_for_emit) Args: @@ -152,7 +152,7 @@ def convert_root_weight_uids_and_vals_to_tensor( def convert_bond_uids_and_vals_to_tensor( - n: int, uids: List[int], bonds: List[int] + n: int, uids: list[int], bonds: list[int] ) -> Union[NDArray[np.int64], "torch.LongTensor"]: r"""Converts bond and uids from chain representation into a np.array. Args: @@ -179,7 +179,7 @@ def convert_bond_uids_and_vals_to_tensor( def convert_weights_and_uids_for_emit( uids: Union[NDArray[np.int64], "torch.LongTensor"], weights: Union[NDArray[np.float32], "torch.FloatTensor"], -) -> Tuple[List[int], List[int]]: +) -> tuple[list[int], list[int]]: r"""Converts weights into integer u32 representation that sum to MAX_INT_WEIGHT. Args: uids (:obj:`np.int64,`): @@ -196,16 +196,12 @@ def convert_weights_and_uids_for_emit( weights = weights.tolist() uids = uids.tolist() if min(weights) < 0: - raise ValueError( - "Passed weight is negative cannot exist on chain {}".format(weights) - ) + raise ValueError(f"Passed weight is negative cannot exist on chain {weights}") if min(uids) < 0: - raise ValueError("Passed uid is negative cannot exist on chain {}".format(uids)) + raise ValueError(f"Passed uid is negative cannot exist on chain {uids}") if len(uids) != len(weights): raise ValueError( - "Passed weights and uids must have the same length, got {} and {}".format( - len(uids), len(weights) - ) + f"Passed weights and uids must have the same length, got {len(uids)} and {len(weights)}" ) if sum(weights) == 0: return [], [] # Nothing to set on chain. @@ -234,12 +230,12 @@ def process_weights_for_netuid( uids: Union[NDArray[np.int64], "torch.Tensor"], weights: Union[NDArray[np.float32], "torch.Tensor"], netuid: int, - subtensor: "bittensor.subtensor", + subtensor: "bittensor.Subtensor", metagraph: "bittensor.metagraph" = None, exclude_quantile: int = 0, ) -> Union[ - Tuple["torch.Tensor", "torch.FloatTensor"], - Tuple[NDArray[np.int64], NDArray[np.float32]], + tuple["torch.Tensor", "torch.FloatTensor"], + tuple[NDArray[np.int64], NDArray[np.float32]], ]: bittensor.logging.debug("process_weights_for_netuid()") bittensor.logging.debug("weights", weights) @@ -280,7 +276,7 @@ def process_weights_for_netuid( if nzw_size == 0 or metagraph.n < min_allowed_weights: bittensor.logging.warning("No non-zero weights returning all ones.") final_weights = ( - torch.ones((metagraph.n)).to(metagraph.n) / metagraph.n + torch.ones(metagraph.n).to(metagraph.n) / metagraph.n if use_torch() else np.ones((metagraph.n), dtype=np.int64) / metagraph.n ) @@ -302,7 +298,7 @@ def process_weights_for_netuid( ) # ( const ): Should this be np.zeros( ( metagraph.n ) ) to reset everyone to build up weight? weights = ( - torch.ones((metagraph.n)).to(metagraph.n) * 1e-5 + torch.ones(metagraph.n).to(metagraph.n) * 1e-5 if use_torch() else np.ones((metagraph.n), dtype=np.int64) * 1e-5 ) # creating minimum even non-zero weights @@ -352,10 +348,10 @@ def process_weights_for_netuid( def generate_weight_hash( address: str, netuid: int, - uids: List[int], - values: List[int], + uids: list[int], + values: list[int], version_key: int, - salt: List[int], + salt: list[int], ) -> str: """ Generate a valid commit hash from the provided weights. diff --git a/bittensor/wallet.py b/bittensor/wallet.py index be6aa08c93..f46b3633cc 100644 --- a/bittensor/wallet.py +++ b/bittensor/wallet.py @@ -17,13 +17,15 @@ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. -import os -import copy import argparse -import bittensor -from termcolor import colored +import copy +import os +from typing import Optional, Union, overload + from substrateinterface import Keypair -from typing import Optional, Union, Tuple, Dict, overload +from termcolor import colored + +import bittensor from bittensor.utils import is_valid_bittensor_address_or_public_key @@ -44,11 +46,11 @@ def display_mnemonic_msg(keypair: Keypair, key_type: str): "red", ) ) - print("The mnemonic to the new {} is:\n\n{}\n".format(key_type, mnemonic_green)) + print(f"The mnemonic to the new {key_type} is:\n\n{mnemonic_green}\n") print( "You can use the mnemonic to recreate the key in case it gets lost. The command to use to regenerate the key using this mnemonic is:" ) - print("btcli w regen_{} --mnemonic {}".format(key_type, mnemonic)) + print(f"btcli w regen_{key_type} --mnemonic {mnemonic}") print("") @@ -138,7 +140,7 @@ def add_args(cls, parser: argparse.ArgumentParser, prefix: str = None): parser (argparse.ArgumentParser): Argument parser object. prefix (str): Argument prefix. """ - prefix_str = "" if prefix == None else prefix + "." + prefix_str = "" if prefix is None else prefix + "." try: default_name = os.getenv("BT_WALLET_NAME") or "default" default_hotkey = os.getenv("BT_WALLET_NAME") or "default" @@ -169,7 +171,7 @@ def add_args(cls, parser: argparse.ArgumentParser, prefix: str = None): default=default_path, help="The path to your bittensor wallets", ) - except argparse.ArgumentError as e: + except argparse.ArgumentError: pass def __init__( @@ -217,7 +219,7 @@ def __str__(self): Returns: str: The string representation. """ - return "wallet({}, {}, {})".format(self.name, self.hotkey_str, self.path) + return f"wallet({self.name}, {self.hotkey_str}, {self.path})" def __repr__(self): """ @@ -431,7 +433,7 @@ def hotkey(self) -> "bittensor.Keypair": KeyFileError: Raised if the file is corrupt of non-existent. CryptoKeyError: Raised if the user enters an incorrec password for an encrypted keyfile. """ - if self._hotkey == None: + if self._hotkey is None: self._hotkey = self.hotkey_file.keypair return self._hotkey @@ -445,7 +447,7 @@ def coldkey(self) -> "bittensor.Keypair": KeyFileError: Raised if the file is corrupt of non-existent. CryptoKeyError: Raised if the user enters an incorrec password for an encrypted keyfile. """ - if self._coldkey == None: + if self._coldkey is None: self._coldkey = self.coldkey_file.keypair return self._coldkey @@ -459,7 +461,7 @@ def coldkeypub(self) -> "bittensor.Keypair": KeyFileError: Raised if the file is corrupt of non-existent. CryptoKeyError: Raised if the user enters an incorrect password for an encrypted keyfile. """ - if self._coldkeypub == None: + if self._coldkeypub is None: self._coldkeypub = self.coldkeypub_file.keypair return self._coldkeypub @@ -689,7 +691,7 @@ def regenerate_coldkey( @overload def regenerate_coldkey( self, - json: Optional[Tuple[Union[str, Dict], str]] = None, + json: Optional[tuple[Union[str, dict], str]] = None, use_password: bool = True, overwrite: bool = False, suppress: bool = False, @@ -796,7 +798,7 @@ def regenerate_hotkey( @overload def regenerate_hotkey( self, - json: Optional[Tuple[Union[str, Dict], str]] = None, + json: Optional[tuple[Union[str, dict], str]] = None, use_password: bool = True, overwrite: bool = False, suppress: bool = False, diff --git a/contrib/CONTRIBUTING.md b/contrib/CONTRIBUTING.md index f9f4ed5f34..9f785e7c89 100644 --- a/contrib/CONTRIBUTING.md +++ b/contrib/CONTRIBUTING.md @@ -76,7 +76,7 @@ You can contribute to Bittensor in one of two main ways (as well as many others) Here is a high-level summary: - Code consistency is crucial; adhere to established programming language conventions. -- Use `ruff format .` to format your Python code; it ensures readability and consistency. +- Use `ruff check --fix . && ruff format .` to format your Python code; it ensures readability and consistency. - Write concise Git commit messages; summarize changes in ~50 characters. - Follow these six commit rules: - Atomic Commits: Focus on one task or fix per commit. diff --git a/contrib/DEBUGGING.md b/contrib/DEBUGGING.md index 093e3432bf..914b944416 100644 --- a/contrib/DEBUGGING.md +++ b/contrib/DEBUGGING.md @@ -104,7 +104,7 @@ import bittensor wallet = bittensor.wallet() # Bittensor's chain interface. -subtensor = bittensor.subtensor() +subtensor = bittensor.Subtensor() # Bittensor's chain state object. metagraph = bittensor.metagraph(netuid=1) diff --git a/ruff.toml b/ruff.toml new file mode 100644 index 0000000000..867322b2d8 --- /dev/null +++ b/ruff.toml @@ -0,0 +1,22 @@ +# To be replaced by pyproject.toml when it is introduced in the project +#[tool.ruff] +target-version = "py39" # to be replaced by project:requires-python after switch to pyproject.toml + +#[tool.ruff.lint] +[lint] +select = [ + # "D", # TODO to be enabled after fixing all issues + "E", "F", "I", "UP", + "TCH005", +] +ignore = [ + "D100", "D105", "D107", "D200", "D202", "D203", "D205", "D212", "D400", "D401", "D415", + "E501", +] + +#[tool.ruff.lint.per-file-ignores] +[lint.per-file-ignores] +"__init__.py" = ["F401"] +"test/**" = ["D", "F403", "F405"] +"bittensor/__init__.py" = ["E402", "I001", ] # FIXME to be changed and tested afterwards +"bittensor/commands/__init__.py" = ["E402"] # FIXME to be changed and tested afterwards diff --git a/setup.py b/setup.py index 49c419724a..283a25a712 100644 --- a/setup.py +++ b/setup.py @@ -15,18 +15,17 @@ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. -from setuptools import setup, find_packages -from os import path -from io import open import codecs -import re import os import pathlib +import re +from os import path + +from setuptools import find_packages, setup def read_requirements(path): requirements = [] - git_requirements = [] with pathlib.Path(path).open() as requirements_txt: for line in requirements_txt: diff --git a/tests/e2e_tests/conftest.py b/tests/e2e_tests/conftest.py index 2300eafc77..bf345f66c5 100644 --- a/tests/e2e_tests/conftest.py +++ b/tests/e2e_tests/conftest.py @@ -1,13 +1,14 @@ +import logging import os +import re +import shlex import signal -from substrateinterface import SubstrateInterface -import pytest import subprocess -import logging -import shlex -import re import time +import pytest +from substrateinterface import SubstrateInterface + logging.basicConfig(level=logging.INFO) diff --git a/tests/e2e_tests/multistep/test_last_tx_block.py b/tests/e2e_tests/multistep/test_last_tx_block.py index 0d1796f5d8..e7f5cb334a 100644 --- a/tests/e2e_tests/multistep/test_last_tx_block.py +++ b/tests/e2e_tests/multistep/test_last_tx_block.py @@ -1,7 +1,8 @@ -from bittensor.commands.root import RootRegisterCommand from bittensor.commands.delegates import NominateCommand from bittensor.commands.network import RegisterSubnetworkCommand from bittensor.commands.register import RegisterCommand +from bittensor.commands.root import RootRegisterCommand + from ..utils import setup_wallet diff --git a/tests/e2e_tests/subcommands/delegation/test_set_delegate_take.py b/tests/e2e_tests/subcommands/delegation/test_set_delegate_take.py index 0453576332..0631fd53f8 100644 --- a/tests/e2e_tests/subcommands/delegation/test_set_delegate_take.py +++ b/tests/e2e_tests/subcommands/delegation/test_set_delegate_take.py @@ -1,8 +1,7 @@ -from bittensor.commands.delegates import SetTakeCommand, NominateCommand +from bittensor.commands.delegates import NominateCommand, SetTakeCommand from bittensor.commands.network import RegisterSubnetworkCommand from bittensor.commands.register import RegisterCommand from bittensor.commands.root import RootRegisterCommand - from tests.e2e_tests.utils import setup_wallet diff --git a/tests/e2e_tests/subcommands/wallet/test_transfer.py b/tests/e2e_tests/subcommands/wallet/test_transfer.py index de8052e027..8d08807b3d 100644 --- a/tests/e2e_tests/subcommands/wallet/test_transfer.py +++ b/tests/e2e_tests/subcommands/wallet/test_transfer.py @@ -1,6 +1,6 @@ from bittensor.commands.transfer import TransferCommand + from ...utils import setup_wallet -import bittensor # Example test using the local_chain fixture diff --git a/tests/e2e_tests/subcommands/weights/test_commit_weights.py b/tests/e2e_tests/subcommands/weights/test_commit_weights.py index faed9d3925..4b1f231d29 100644 --- a/tests/e2e_tests/subcommands/weights/test_commit_weights.py +++ b/tests/e2e_tests/subcommands/weights/test_commit_weights.py @@ -6,11 +6,11 @@ import bittensor import bittensor.utils.weight_utils as weight_utils from bittensor.commands import ( + CommitWeightCommand, RegisterCommand, - StakeCommand, RegisterSubnetworkCommand, - CommitWeightCommand, RevealWeightCommand, + StakeCommand, ) from tests.e2e_tests.utils import setup_wallet @@ -53,7 +53,7 @@ def test_commit_and_reveal_weights(local_chain): ], ) - subtensor = bittensor.subtensor(network="ws://localhost:9945") + subtensor = bittensor.Subtensor(network="ws://localhost:9945") # Enable Commit Reveal result = subtensor.set_hyperparameter( diff --git a/tests/e2e_tests/utils.py b/tests/e2e_tests/utils.py index 3ad789dd6d..ecab98e1ca 100644 --- a/tests/e2e_tests/utils.py +++ b/tests/e2e_tests/utils.py @@ -1,5 +1,5 @@ from substrateinterface import Keypair -from typing import List + import bittensor @@ -11,7 +11,7 @@ def setup_wallet(uri: str): wallet.set_coldkeypub(keypair=keypair, encrypt=False, overwrite=True) wallet.set_hotkey(keypair=keypair, encrypt=False, overwrite=True) - def exec_command(command, extra_args: List[str]): + def exec_command(command, extra_args: list[str]): parser = bittensor.cli.__create_parser__() args = extra_args + [ "--no_prompt", diff --git a/tests/helpers/__init__.py b/tests/helpers/__init__.py index fc9e8ad9d2..c5239c366f 100644 --- a/tests/helpers/__init__.py +++ b/tests/helpers/__init__.py @@ -16,14 +16,15 @@ # DEALINGS IN THE SOFTWARE. import os + from .helpers import ( + CLOSE_IN_VALUE, + MockConsole, + __mock_wallet_factory__, _get_mock_coldkey, _get_mock_hotkey, _get_mock_keypair, _get_mock_wallet, - CLOSE_IN_VALUE, - MockConsole, - __mock_wallet_factory__, ) diff --git a/tests/helpers/helpers.py b/tests/helpers/helpers.py index 482f59ce2d..440a5ab9a1 100644 --- a/tests/helpers/helpers.py +++ b/tests/helpers/helpers.py @@ -16,16 +16,19 @@ # DEALINGS IN THE SOFTWARE. from typing import Union -from bittensor import Balance, NeuronInfo, AxonInfo, PrometheusInfo, __ss58_format__ + +from rich.console import Console +from rich.text import Text + +from bittensor import AxonInfo, Balance, NeuronInfo, PrometheusInfo from bittensor.mock.wallet_mock import MockWallet as _MockWallet from bittensor.mock.wallet_mock import get_mock_coldkey as _get_mock_coldkey from bittensor.mock.wallet_mock import get_mock_hotkey as _get_mock_hotkey -from bittensor.mock.wallet_mock import get_mock_keypair as _get_mock_keypair +from bittensor.mock.wallet_mock import ( + get_mock_keypair as _get_mock_keypair, # noqa: F401 +) from bittensor.mock.wallet_mock import get_mock_wallet as _get_mock_wallet -from rich.console import Console -from rich.text import Text - def __mock_wallet_factory__(*args, **kwargs) -> _MockWallet: """Returns a mock wallet object.""" diff --git a/tests/integration_tests/test_cli.py b/tests/integration_tests/test_cli.py index aa019c4178..811bab16e3 100644 --- a/tests/integration_tests/test_cli.py +++ b/tests/integration_tests/test_cli.py @@ -18,14 +18,11 @@ # DEALINGS IN THE SOFTWARE. -import contextlib -from copy import deepcopy import os import random -import shutil -from types import SimpleNamespace -from typing import Dict import unittest +from copy import deepcopy +from types import SimpleNamespace from unittest.mock import MagicMock, patch import pytest @@ -38,13 +35,14 @@ from bittensor.mock import MockSubtensor from bittensor.wallet import wallet as Wallet from tests.helpers import ( - is_running_in_circleci, MockConsole, _get_mock_keypair, + is_running_in_circleci, +) +from tests.helpers import ( _get_mock_wallet as generate_wallet, ) - _subtensor_mock: MockSubtensor = MockSubtensor() @@ -252,11 +250,7 @@ def test_overview_not_in_first_subnet(self, _): print("Registering mock wallets to subnets...") for netuid, wallet in mock_registrations: - print( - "Registering wallet {} to subnet {}".format( - wallet.hotkey_str, netuid - ) - ) + print(f"Registering wallet {wallet.hotkey_str} to subnet {netuid}") _ = _subtensor_mock.force_register_neuron( netuid=netuid, coldkey=wallet.coldkey.ss58_address, @@ -458,7 +452,7 @@ def test_unstake_with_specific_hotkeys(self, _): config.all_hotkeys = False # Notice no max_stake specified - mock_stakes: Dict[str, Balance] = { + mock_stakes: dict[str, Balance] = { # All have more than 5.0 stake "hk0": Balance.from_float(10.0), "hk1": Balance.from_float(11.1), @@ -534,7 +528,7 @@ def test_unstake_with_all_hotkeys(self, _): config.all_hotkeys = True # Notice no max_stake specified - mock_stakes: Dict[str, Balance] = { + mock_stakes: dict[str, Balance] = { # All have more than 5.0 stake "hk0": Balance.from_float(10.0), "hk1": Balance.from_float(11.1), @@ -613,7 +607,7 @@ def test_unstake_with_exclude_hotkeys_from_all(self, _): config.hotkeys = ["hk1"] # Exclude hk1 config.all_hotkeys = True - mock_stakes: Dict[str, Balance] = { + mock_stakes: dict[str, Balance] = { # All have more than 5.0 stake "hk0": Balance.from_float(10.0), "hk1": Balance.from_float(11.1), @@ -699,7 +693,7 @@ def test_unstake_with_multiple_hotkeys_max_stake(self, _): config.hotkeys = ["hk0", "hk1", "hk2"] config.all_hotkeys = False - mock_stakes: Dict[str, Balance] = { + mock_stakes: dict[str, Balance] = { # All have more than 5.0 stake "hk0": Balance.from_float(10.0), "hk1": Balance.from_float(4.9), @@ -723,7 +717,7 @@ def test_unstake_with_multiple_hotkeys_max_stake(self, _): print("Registering mock wallets...") for wallet in mock_wallets: - print("Registering mock wallet {}".format(wallet.hotkey_str)) + print(f"Registering mock wallet {wallet.hotkey_str}") _ = _subtensor_mock.force_register_neuron( netuid=1, hotkey=wallet.hotkey.ss58_address, @@ -788,7 +782,7 @@ def test_unstake_with_thresholds(self, _): config.all_hotkeys = False # Notice no max_stake specified - mock_stakes: Dict[str, Balance] = { + mock_stakes: dict[str, Balance] = { "hk0": Balance.from_float(10.0), "hk1": Balance.from_float(11.1), "hk2": Balance.from_float(12.2), @@ -859,7 +853,7 @@ def test_unstake_all(self, _): config.hotkeys = ["hk0"] config.all_hotkeys = False - mock_stakes: Dict[str, Balance] = {"hk0": Balance.from_float(10.0)} + mock_stakes: dict[str, Balance] = {"hk0": Balance.from_float(10.0)} mock_coldkey_kp = _get_mock_keypair(0, self.id()) @@ -946,7 +940,7 @@ def test_stake_with_specific_hotkeys(self, _): print("Registering mock wallets...") for wallet in mock_wallets: - print("Registering mock wallet {}".format(wallet.hotkey_str)) + print(f"Registering mock wallet {wallet.hotkey_str}") _ = _subtensor_mock.force_register_neuron( netuid=1, hotkey=wallet.hotkey.ss58_address, @@ -1020,7 +1014,7 @@ def test_stake_with_all_hotkeys(self, _): print("Registering mock wallets...") for wallet in mock_wallets: - print("Registering mock wallet {}".format(wallet.hotkey_str)) + print(f"Registering mock wallet {wallet.hotkey_str}") _ = _subtensor_mock.force_register_neuron( netuid=1, hotkey=wallet.hotkey.ss58_address, @@ -1118,7 +1112,7 @@ def test_stake_with_exclude_hotkeys_from_all(self, _): print("Registering mock wallets...") for wallet in mock_wallets: - print("Registering mock wallet {}".format(wallet.hotkey_str)) + print(f"Registering mock wallet {wallet.hotkey_str}") _ = _subtensor_mock.force_register_neuron( netuid=1, hotkey=wallet.hotkey.ss58_address, @@ -1201,7 +1195,7 @@ def test_stake_with_multiple_hotkeys_max_stake(self, _): mock_balance = Balance.from_float(config.max_stake * 3) - mock_stakes: Dict[str, Balance] = { + mock_stakes: dict[str, Balance] = { "hk0": Balance.from_float(0.0), "hk1": Balance.from_float(config.max_stake * 2), "hk2": Balance.from_float(0.0), @@ -1224,7 +1218,7 @@ def test_stake_with_multiple_hotkeys_max_stake(self, _): print("Registering mock wallets...") for wallet in mock_wallets: - print("Registering mock wallet {}".format(wallet.hotkey_str)) + print(f"Registering mock wallet {wallet.hotkey_str}") if wallet.hotkey_str == "hk1": # Set the stake for hk1 _ = _subtensor_mock.force_register_neuron( @@ -1331,7 +1325,7 @@ def test_stake_with_multiple_hotkeys_max_stake_not_enough_balance(self, _): print("Registering mock wallets...") for wallet in mock_wallets: - print("Registering mock wallet {}".format(wallet.hotkey_str)) + print(f"Registering mock wallet {wallet.hotkey_str}") _ = _subtensor_mock.force_register_neuron( netuid=1, hotkey=wallet.hotkey.ss58_address, @@ -1424,7 +1418,7 @@ def test_stake_with_single_hotkey_max_stake(self, _): print("Registering mock wallets...") for wallet in mock_wallets: - print("Registering mock wallet {}".format(wallet.hotkey_str)) + print(f"Registering mock wallet {wallet.hotkey_str}") _ = _subtensor_mock.force_register_neuron( netuid=1, hotkey=wallet.hotkey.ss58_address, @@ -1584,7 +1578,7 @@ def test_stake_with_single_hotkey_max_stake_enough_stake(self, _): mock_balance = Balance.from_float(config.max_stake * 3) - mock_stakes: Dict[str, Balance] = { # has enough stake, more than max_stake + mock_stakes: dict[str, Balance] = { # has enough stake, more than max_stake "hk0": Balance.from_float(config.max_stake * 2) } @@ -1732,7 +1726,7 @@ def test_delegate_stake(self, _): config.amount = 5.0 config.wallet.name = "w1" - mock_balances: Dict[str, Balance] = { + mock_balances: dict[str, Balance] = { # All have more than 5.0 stake "w0": { "hk0": Balance.from_float(10.0), @@ -1817,7 +1811,7 @@ def test_undelegate_stake(self, _): config.amount = 5.0 config.wallet.name = "w1" - mock_balances: Dict[str, Balance] = { + mock_balances: dict[str, Balance] = { # All have more than 5.0 stake "w0": { "hk0": Balance.from_float(10.0), @@ -1921,7 +1915,7 @@ def test_transfer(self, _): config.amount = 3.2 config.wallet.name = "w1" - mock_balances: Dict[str, Balance] = { + mock_balances: dict[str, Balance] = { "w0": Balance.from_float(10.0), "w1": Balance.from_float(config.amount + 0.001), } @@ -1989,7 +1983,7 @@ def test_transfer_not_enough_balance(self, _): config.amount = 3.2 config.wallet.name = "w1" - mock_balances: Dict[str, Balance] = { + mock_balances: dict[str, Balance] = { "w0": Balance.from_float(10.0), "w1": Balance.from_float(config.amount - 0.1), # not enough balance } @@ -2080,7 +2074,7 @@ def test_register(self, _): mock_create_wallet.assert_called_once() # Verify that the wallet was registered - subtensor = bittensor.subtensor(config) + subtensor = bittensor.Subtensor(config) registered = subtensor.is_hotkey_registered_on_subnet( hotkey_ss58=mock_wallet.hotkey.ss58_address, netuid=1 ) @@ -2126,7 +2120,7 @@ def test_stake(self, _): config.model = "core_server" config.hotkey = "hk0" - subtensor = bittensor.subtensor(config) + subtensor = bittensor.Subtensor(config) mock_wallet = generate_wallet(hotkey=_get_mock_keypair(100, self.id())) @@ -2515,11 +2509,13 @@ def test_set_identity_command( mock_wallet.coldkey.ss58_address = "fake_coldkey_ss58_address" mock_wallet.coldkey = MagicMock() - with patch("bittensor.subtensor", return_value=mock_subtensor), patch( - "bittensor.wallet", return_value=mock_wallet - ), patch("bittensor.__console__", MagicMock()), patch( - "rich.prompt.Prompt.ask", side_effect=["y", "y"] - ), patch("sys.exit") as mock_exit: + with ( + patch("bittensor.subtensor", return_value=mock_subtensor), + patch("bittensor.wallet", return_value=mock_wallet), + patch("bittensor.__console__", MagicMock()), + patch("rich.prompt.Prompt.ask", side_effect=["y", "y"]), + patch("sys.exit") as mock_exit, + ): # Act if expected_exception: with pytest.raises(expected_exception) as exc_info: diff --git a/tests/integration_tests/test_cli_no_network.py b/tests/integration_tests/test_cli_no_network.py index 1ef6657f61..f86c15c109 100644 --- a/tests/integration_tests/test_cli_no_network.py +++ b/tests/integration_tests/test_cli_no_network.py @@ -17,18 +17,17 @@ # DEALINGS IN THE SOFTWARE. +import re import unittest -from unittest.mock import MagicMock, patch -from typing import Any, Optional -import pytest from copy import deepcopy -import re +from typing import Any +from unittest.mock import MagicMock, patch -from tests.helpers import _get_mock_coldkey, __mock_wallet_factory__, MockConsole +import pytest import bittensor from bittensor import Balance -from rich.table import Table +from tests.helpers import __mock_wallet_factory__, _get_mock_coldkey class MockException(Exception): @@ -301,7 +300,7 @@ def test_list_no_wallet(self, _, __): cli.run() def test_btcli_help(self, _, __): - with pytest.raises(SystemExit) as pytest_wrapped_e: + with pytest.raises(SystemExit): with patch( "argparse.ArgumentParser._print_message", return_value=None ) as mock_print_message: diff --git a/tests/integration_tests/test_metagraph_integration.py b/tests/integration_tests/test_metagraph_integration.py index 5dbb9ddfc1..c6a29d031e 100644 --- a/tests/integration_tests/test_metagraph_integration.py +++ b/tests/integration_tests/test_metagraph_integration.py @@ -16,11 +16,13 @@ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. -import bittensor -import torch import os -from bittensor.mock import MockSubtensor + +import torch + +import bittensor from bittensor.metagraph import METAGRAPH_STATE_DICT_NDARRAY_KEYS, get_save_dir +from bittensor.mock import MockSubtensor _subtensor_mock: MockSubtensor = MockSubtensor() diff --git a/tests/integration_tests/test_subtensor_integration.py b/tests/integration_tests/test_subtensor_integration.py index e3661210bc..b073b64297 100644 --- a/tests/integration_tests/test_subtensor_integration.py +++ b/tests/integration_tests/test_subtensor_integration.py @@ -30,8 +30,8 @@ from bittensor.utils import weight_utils from bittensor.utils.balance import Balance from tests.helpers import ( - _get_mock_coldkey, MockConsole, + _get_mock_coldkey, _get_mock_keypair, _get_mock_wallet, ) @@ -91,7 +91,7 @@ def test_network_overrides(self): with patch("substrateinterface.SubstrateInterface.reload_type_registry"): print(bittensor.subtensor, type(bittensor.subtensor)) # Choose network arg over config - sub1 = bittensor.subtensor(config=config1, network="local") + sub1 = bittensor.Subtensor(config=config1, network="local") self.assertEqual( sub1.chain_endpoint, bittensor.__local_entrypoint__, @@ -99,21 +99,21 @@ def test_network_overrides(self): ) # Choose network config over chain_endpoint config - sub2 = bittensor.subtensor(config=config0) + sub2 = bittensor.Subtensor(config=config0) self.assertNotEqual( sub2.chain_endpoint, bittensor.__finney_entrypoint__, # Here we expect the endpoint corresponding to the network "finney" msg="config.network should override config.chain_endpoint", ) - sub3 = bittensor.subtensor(config=config1) + sub3 = bittensor.Subtensor(config=config1) # Should pick local instead of finney (default) assert sub3.network == "local" assert sub3.chain_endpoint == bittensor.__local_entrypoint__ def test_get_current_block(self): block = self.subtensor.get_current_block() - assert type(block) == int + assert type(block) == int # noqa: E721 def test_unstake(self): self.subtensor._do_unstake = MagicMock(return_value=True) @@ -313,13 +313,6 @@ def test_transfer_dest_as_bytes(self): def test_set_weights(self): chain_weights = [0] - class success: - def __init__(self): - self.is_success = True - - def process_events(self): - return True - self.subtensor.set_weights = MagicMock(return_value=True) self.subtensor._do_set_weights = MagicMock(return_value=(True, None)) @@ -329,7 +322,7 @@ def process_events(self): uids=[1], weights=chain_weights, ) - assert success == True + assert success is True def test_set_weights_inclusion(self): chain_weights = [0] @@ -343,7 +336,7 @@ def test_set_weights_inclusion(self): weights=chain_weights, wait_for_inclusion=True, ) - assert success == True + assert success is True def test_set_weights_failed(self): chain_weights = [0] @@ -359,7 +352,7 @@ def test_set_weights_failed(self): weights=chain_weights, wait_for_inclusion=True, ) - assert fail == False + assert fail is False def test_commit_weights(self): weights = np.array([0.1, 0.2, 0.3, 0.4], dtype=np.float32) @@ -368,7 +361,7 @@ def test_commit_weights(self): weight_uids, weight_vals = weight_utils.convert_weights_and_uids_for_emit( uids=uids, weights=weights ) - commit_hash = bittensor.utils.weight_utils.generate_weight_hash( + bittensor.utils.weight_utils.generate_weight_hash( address=self.wallet.hotkey.ss58_address, netuid=3, uids=weight_uids, @@ -397,7 +390,7 @@ def test_commit_weights_inclusion(self): uids=uids, weights=weights ) - commit_hash = bittensor.utils.weight_utils.generate_weight_hash( + bittensor.utils.weight_utils.generate_weight_hash( address=self.wallet.hotkey.ss58_address, netuid=1, uids=weight_uids, @@ -431,7 +424,7 @@ def test_commit_weights_failed(self): uids=uids, weights=weights ) - commit_hash = bittensor.utils.weight_utils.generate_weight_hash( + bittensor.utils.weight_utils.generate_weight_hash( address=self.wallet.hotkey.ss58_address, netuid=3, uids=weight_uids, @@ -608,13 +601,13 @@ def test_commit_and_reveal_weights_inclusion(self): def test_get_balance(self): fake_coldkey = _get_mock_coldkey(0) balance = self.subtensor.get_balance(address=fake_coldkey) - assert type(balance) == bittensor.utils.balance.Balance + assert type(balance) == bittensor.utils.balance.Balance # noqa: E721 def test_get_balances(self): balances = self.subtensor.get_balances() - assert type(balances) == dict + assert type(balances) == dict # noqa: E721 for i in balances: - assert type(balances[i]) == bittensor.utils.balance.Balance + assert type(balances[i]) == bittensor.utils.balance.Balance # noqa: E721 def test_get_uid_by_hotkey_on_subnet(self): mock_coldkey_kp = _get_mock_keypair(0, self.id()) @@ -679,13 +672,11 @@ def test_registration_multiprocessed_already_registered(self): mock_neuron.is_null = True # patch solution queue to return None - with patch( - "multiprocessing.queues.Queue.get", return_value=None - ) as mock_queue_get: + with patch("multiprocessing.queues.Queue.get", return_value=None): # patch time queue get to raise Empty exception with patch( "multiprocessing.queues.Queue.get_nowait", side_effect=QueueEmpty - ) as mock_queue_get_nowait: + ): wallet = _get_mock_wallet( hotkey=_get_mock_keypair(0, self.id()), coldkey=_get_mock_keypair(1, self.id()), @@ -831,7 +822,7 @@ class ExitEarly(Exception): ) def test_defaults_to_finney(self): - sub = bittensor.subtensor() + sub = bittensor.Subtensor() assert sub.network == "finney" assert sub.chain_endpoint == bittensor.__finney_entrypoint__ diff --git a/tests/unit_tests/extrinsics/test_delegation.py b/tests/unit_tests/extrinsics/test_delegation.py index 42dcf4e706..56bff0bbfa 100644 --- a/tests/unit_tests/extrinsics/test_delegation.py +++ b/tests/unit_tests/extrinsics/test_delegation.py @@ -1,19 +1,21 @@ -import pytest from unittest.mock import MagicMock, patch -from bittensor.subtensor import Subtensor -from bittensor.wallet import wallet as Wallet -from bittensor.utils.balance import Balance -from bittensor.extrinsics.delegation import ( - nominate_extrinsic, - delegate_extrinsic, - undelegate_extrinsic, -) + +import pytest + from bittensor.errors import ( NominationError, NotDelegateError, NotRegisteredError, StakeError, ) +from bittensor.extrinsics.delegation import ( + delegate_extrinsic, + nominate_extrinsic, + undelegate_extrinsic, +) +from bittensor.subtensor import Subtensor +from bittensor.utils.balance import Balance +from bittensor.wallet import wallet as Wallet @pytest.fixture @@ -59,11 +61,14 @@ def test_nominate_extrinsic( expected_result, ): # Arrange - with patch.object( - mock_subtensor, "is_hotkey_delegate", return_value=already_delegate - ), patch.object( - mock_subtensor, "_do_nominate", return_value=nomination_success - ) as mock_nominate: + with ( + patch.object( + mock_subtensor, "is_hotkey_delegate", return_value=already_delegate + ), + patch.object( + mock_subtensor, "_do_nominate", return_value=nomination_success + ) as mock_nominate, + ): if raises_exception: mock_subtensor._do_nominate.side_effect = raises_exception @@ -240,17 +245,20 @@ def test_delegate_extrinsic( wallet_balance = Balance.from_tao(500) wallet_insufficient_balance = Balance.from_tao(0.002) - with patch("rich.prompt.Confirm.ask", return_value=prompt_response), patch.object( - mock_subtensor, - "get_balance", - return_value=wallet_balance - if balance_sufficient - else wallet_insufficient_balance, - ), patch.object( - mock_subtensor, "is_hotkey_delegate", return_value=is_delegate - ), patch.object( - mock_subtensor, "_do_delegation", return_value=transaction_success - ) as mock_delegate: + with ( + patch("rich.prompt.Confirm.ask", return_value=prompt_response), + patch.object( + mock_subtensor, + "get_balance", + return_value=wallet_balance + if balance_sufficient + else wallet_insufficient_balance, + ), + patch.object(mock_subtensor, "is_hotkey_delegate", return_value=is_delegate), + patch.object( + mock_subtensor, "_do_delegation", return_value=transaction_success + ) as mock_delegate, + ): if raises_error: mock_delegate.side_effect = raises_error @@ -402,17 +410,19 @@ def test_undelegate_extrinsic( # Arrange wallet_balance = Balance.from_tao(500) - with patch("rich.prompt.Confirm.ask", return_value=prompt_response), patch.object( - mock_subtensor, "is_hotkey_delegate", return_value=is_delegate - ), patch.object( - mock_subtensor, "get_balance", return_value=wallet_balance - ), patch.object( - mock_subtensor, - "get_stake_for_coldkey_and_hotkey", - return_value=Balance.from_tao(current_stake), - ), patch.object( - mock_subtensor, "_do_undelegation", return_value=transaction_success - ) as mock_undelegate: + with ( + patch("rich.prompt.Confirm.ask", return_value=prompt_response), + patch.object(mock_subtensor, "is_hotkey_delegate", return_value=is_delegate), + patch.object(mock_subtensor, "get_balance", return_value=wallet_balance), + patch.object( + mock_subtensor, + "get_stake_for_coldkey_and_hotkey", + return_value=Balance.from_tao(current_stake), + ), + patch.object( + mock_subtensor, "_do_undelegation", return_value=transaction_success + ) as mock_undelegate, + ): if raises_error: mock_undelegate.side_effect = raises_error diff --git a/tests/unit_tests/extrinsics/test_network.py b/tests/unit_tests/extrinsics/test_network.py index 67df030ffe..db66edaa42 100644 --- a/tests/unit_tests/extrinsics/test_network.py +++ b/tests/unit_tests/extrinsics/test_network.py @@ -1,11 +1,13 @@ -import pytest from unittest.mock import MagicMock, patch -from bittensor.subtensor import Subtensor -from bittensor.wallet import wallet as Wallet + +import pytest + from bittensor.extrinsics.network import ( - set_hyperparameter_extrinsic, register_subnetwork_extrinsic, + set_hyperparameter_extrinsic, ) +from bittensor.subtensor import Subtensor +from bittensor.wallet import wallet as Wallet # Mock the bittensor and related modules to avoid real network calls and wallet operations @@ -130,16 +132,19 @@ def test_set_hyperparameter_extrinsic( expected_result, ): # Arrange - with patch.object( - mock_subtensor, - "get_subnet_owner", - return_value=mock_wallet.coldkeypub.ss58_address - if is_owner - else mock_other_owner_wallet.coldkeypub.ss58_address, - ), patch.object( - mock_subtensor.substrate, - "submit_extrinsic", - return_value=MagicMock(is_success=extrinsic_success), + with ( + patch.object( + mock_subtensor, + "get_subnet_owner", + return_value=mock_wallet.coldkeypub.ss58_address + if is_owner + else mock_other_owner_wallet.coldkeypub.ss58_address, + ), + patch.object( + mock_subtensor.substrate, + "submit_extrinsic", + return_value=MagicMock(is_success=extrinsic_success), + ), ): # Act result = set_hyperparameter_extrinsic( diff --git a/tests/unit_tests/extrinsics/test_prometheus.py b/tests/unit_tests/extrinsics/test_prometheus.py index 7d9c975fbc..b2b7fcae61 100644 --- a/tests/unit_tests/extrinsics/test_prometheus.py +++ b/tests/unit_tests/extrinsics/test_prometheus.py @@ -1,9 +1,11 @@ -import pytest from unittest.mock import MagicMock, patch + +import pytest + import bittensor +from bittensor.extrinsics.prometheus import prometheus_extrinsic from bittensor.subtensor import Subtensor from bittensor.wallet import wallet as Wallet -from bittensor.extrinsics.prometheus import prometheus_extrinsic # Mocking the bittensor and networking modules @@ -112,7 +114,7 @@ def test_prometheus_extrinsic_edge_cases( ) # Assert - assert result == True, f"Test ID: {test_id}" + assert result is True, f"Test ID: {test_id}" # Error cases diff --git a/tests/unit_tests/extrinsics/test_registration.py b/tests/unit_tests/extrinsics/test_registration.py index 5a4d32dff6..37db25a1e7 100644 --- a/tests/unit_tests/extrinsics/test_registration.py +++ b/tests/unit_tests/extrinsics/test_registration.py @@ -1,15 +1,17 @@ -import pytest from unittest.mock import MagicMock, patch -from bittensor.subtensor import Subtensor -from bittensor.wallet import wallet as Wallet -from bittensor.utils.registration import POWSolution + +import pytest + from bittensor.extrinsics.registration import ( - MaxSuccessException, MaxAttemptsException, - swap_hotkey_extrinsic, + MaxSuccessException, burned_register_extrinsic, register_extrinsic, + swap_hotkey_extrinsic, ) +from bittensor.subtensor import Subtensor +from bittensor.utils.registration import POWSolution +from bittensor.wallet import wallet as Wallet # Mocking external dependencies @@ -74,10 +76,13 @@ def test_run_faucet_extrinsic_happy_path( log_verbose, expected, ): - with patch( - "bittensor.utils.registration._solve_for_difficulty_fast", - return_value=mock_pow_solution, - ) as mock_create_pow, patch("rich.prompt.Confirm.ask", return_value=True): + with ( + patch( + "bittensor.utils.registration._solve_for_difficulty_fast", + return_value=mock_pow_solution, + ), + patch("rich.prompt.Confirm.ask", return_value=True), + ): from bittensor.extrinsics.registration import run_faucet_extrinsic # Arrange @@ -131,8 +136,9 @@ def test_run_faucet_extrinsic_happy_path( def test_run_faucet_extrinsic_edge_cases( mock_subtensor, mock_wallet, cuda, torch_cuda_available, prompt_response, expected ): - with patch("torch.cuda.is_available", return_value=torch_cuda_available), patch( - "rich.prompt.Confirm.ask", return_value=prompt_response + with ( + patch("torch.cuda.is_available", return_value=torch_cuda_available), + patch("rich.prompt.Confirm.ask", return_value=prompt_response), ): from bittensor.extrinsics.registration import run_faucet_extrinsic @@ -257,19 +263,23 @@ def test_burned_register_extrinsic( test_id, ): # Arrange - with patch.object( - mock_subtensor, "subnet_exists", return_value=subnet_exists - ), patch.object( - mock_subtensor, - "get_neuron_for_pubkey_and_subnet", - return_value=MagicMock(is_null=neuron_is_null), - ), patch.object( - mock_subtensor, - "_do_burned_register", - return_value=(recycle_success, "Mock error message"), - ), patch.object( - mock_subtensor, "is_hotkey_registered", return_value=is_registered - ), patch("rich.prompt.Confirm.ask", return_value=prompt_response) as mock_confirm: + with ( + patch.object(mock_subtensor, "subnet_exists", return_value=subnet_exists), + patch.object( + mock_subtensor, + "get_neuron_for_pubkey_and_subnet", + return_value=MagicMock(is_null=neuron_is_null), + ), + patch.object( + mock_subtensor, + "_do_burned_register", + return_value=(recycle_success, "Mock error message"), + ), + patch.object( + mock_subtensor, "is_hotkey_registered", return_value=is_registered + ), + patch("rich.prompt.Confirm.ask", return_value=prompt_response) as mock_confirm, + ): # Act result = burned_register_extrinsic( subtensor=mock_subtensor, wallet=mock_wallet, netuid=123, prompt=True @@ -305,14 +315,15 @@ def test_register_extrinsic_without_pow( test_id, ): # Arrange - with patch.object( - mock_subtensor, "subnet_exists", return_value=subnet_exists - ), patch.object( - mock_subtensor, - "get_neuron_for_pubkey_and_subnet", - return_value=MagicMock(is_null=neuron_is_null), - ), patch("rich.prompt.Confirm.ask", return_value=prompt_response), patch( - "torch.cuda.is_available", return_value=cuda_available + with ( + patch.object(mock_subtensor, "subnet_exists", return_value=subnet_exists), + patch.object( + mock_subtensor, + "get_neuron_for_pubkey_and_subnet", + return_value=MagicMock(is_null=neuron_is_null), + ), + patch("rich.prompt.Confirm.ask", return_value=prompt_response), + patch("torch.cuda.is_available", return_value=cuda_available), ): # Act result = register_extrinsic( @@ -360,17 +371,22 @@ def test_register_extrinsic_with_pow( test_id, ): # Arrange - with patch( - "bittensor.utils.registration._solve_for_difficulty_fast", - return_value=mock_pow_solution if pow_success else None, - ), patch( - "bittensor.utils.registration._solve_for_difficulty_fast_cuda", - return_value=mock_pow_solution if pow_success else None, - ), patch.object( - mock_subtensor, - "_do_pow_register", - return_value=(registration_success, "key is already registered"), - ), patch("torch.cuda.is_available", return_value=cuda): + with ( + patch( + "bittensor.utils.registration._solve_for_difficulty_fast", + return_value=mock_pow_solution if pow_success else None, + ), + patch( + "bittensor.utils.registration._solve_for_difficulty_fast_cuda", + return_value=mock_pow_solution if pow_success else None, + ), + patch.object( + mock_subtensor, + "_do_pow_register", + return_value=(registration_success, "key is already registered"), + ), + patch("torch.cuda.is_available", return_value=cuda), + ): # Act if pow_success: mock_pow_solution.is_stale.return_value = pow_stale diff --git a/tests/unit_tests/extrinsics/test_root.py b/tests/unit_tests/extrinsics/test_root.py index d3ae2c3973..0b8ba22053 100644 --- a/tests/unit_tests/extrinsics/test_root.py +++ b/tests/unit_tests/extrinsics/test_root.py @@ -1,10 +1,12 @@ -import pytest from unittest.mock import MagicMock, patch -from bittensor.subtensor import Subtensor + +import pytest + from bittensor.extrinsics.root import ( root_register_extrinsic, set_root_weights_extrinsic, ) +from bittensor.subtensor import Subtensor @pytest.fixture @@ -84,11 +86,14 @@ def test_root_register_extrinsic( # Arrange mock_subtensor.is_hotkey_registered.side_effect = hotkey_registered - with patch.object( - mock_subtensor, - "_do_root_register", - return_value=(registration_success, "Error registering"), - ) as mock_register, patch("rich.prompt.Confirm.ask", return_value=user_response): + with ( + patch.object( + mock_subtensor, + "_do_root_register", + return_value=(registration_success, "Error registering"), + ) as mock_register, + patch("rich.prompt.Confirm.ask", return_value=user_response), + ): # Act result = root_register_extrinsic( subtensor=mock_subtensor, @@ -185,13 +190,16 @@ def test_set_root_weights_extrinsic( expected_success, ): # Arrange - with patch.object( - mock_subtensor, "_do_set_weights", return_value=(expected_success, "Mock error") - ), patch.object( - mock_subtensor, "min_allowed_weights", return_value=0 - ), patch.object(mock_subtensor, "max_weight_limit", return_value=1), patch( - "rich.prompt.Confirm.ask", return_value=user_response - ) as mock_confirm: + with ( + patch.object( + mock_subtensor, + "_do_set_weights", + return_value=(expected_success, "Mock error"), + ), + patch.object(mock_subtensor, "min_allowed_weights", return_value=0), + patch.object(mock_subtensor, "max_weight_limit", return_value=1), + patch("rich.prompt.Confirm.ask", return_value=user_response) as mock_confirm, + ): # Act result = set_root_weights_extrinsic( subtensor=mock_subtensor, diff --git a/tests/unit_tests/extrinsics/test_senate.py b/tests/unit_tests/extrinsics/test_senate.py index 66849efc5c..5fc21dbdf0 100644 --- a/tests/unit_tests/extrinsics/test_senate.py +++ b/tests/unit_tests/extrinsics/test_senate.py @@ -1,5 +1,7 @@ -import pytest from unittest.mock import MagicMock, patch + +import pytest + from bittensor import subtensor, wallet from bittensor.extrinsics.senate import ( leave_senate_extrinsic, @@ -54,20 +56,21 @@ def test_register_senate_extrinsic( test_id, ): # Arrange - with patch( - "bittensor.extrinsics.senate.Confirm.ask", return_value=not prompt - ), patch("bittensor.extrinsics.senate.time.sleep"), patch.object( - mock_subtensor.substrate, "compose_call" - ), patch.object(mock_subtensor.substrate, "create_signed_extrinsic"), patch.object( - mock_subtensor.substrate, - "submit_extrinsic", - return_value=MagicMock( - is_success=response_success, - process_events=MagicMock(), - error_message="error", + with ( + patch("bittensor.extrinsics.senate.Confirm.ask", return_value=not prompt), + patch("bittensor.extrinsics.senate.time.sleep"), + patch.object(mock_subtensor.substrate, "compose_call"), + patch.object(mock_subtensor.substrate, "create_signed_extrinsic"), + patch.object( + mock_subtensor.substrate, + "submit_extrinsic", + return_value=MagicMock( + is_success=response_success, + process_events=MagicMock(), + error_message="error", + ), ), - ) as mock_submit_extrinsic, patch.object( - mock_wallet, "is_senate_member", return_value=is_registered + patch.object(mock_wallet, "is_senate_member", return_value=is_registered), ): # Act result = register_senate_extrinsic( @@ -147,25 +150,28 @@ def test_vote_senate_extrinsic( proposal_hash = "mock_hash" proposal_idx = 123 - with patch( - "bittensor.extrinsics.senate.Confirm.ask", return_value=not prompt - ), patch("bittensor.extrinsics.senate.time.sleep"), patch.object( - mock_subtensor.substrate, "compose_call" - ), patch.object(mock_subtensor.substrate, "create_signed_extrinsic"), patch.object( - mock_subtensor.substrate, - "submit_extrinsic", - return_value=MagicMock( - is_success=response_success, - process_events=MagicMock(), - error_message="error", + with ( + patch("bittensor.extrinsics.senate.Confirm.ask", return_value=not prompt), + patch("bittensor.extrinsics.senate.time.sleep"), + patch.object(mock_subtensor.substrate, "compose_call"), + patch.object(mock_subtensor.substrate, "create_signed_extrinsic"), + patch.object( + mock_subtensor.substrate, + "submit_extrinsic", + return_value=MagicMock( + is_success=response_success, + process_events=MagicMock(), + error_message="error", + ), + ), + patch.object( + mock_subtensor, + "get_vote_data", + return_value={ + "ayes": [mock_wallet.hotkey.ss58_address] if vote_in_ayes else [], + "nays": [mock_wallet.hotkey.ss58_address] if vote_in_nays else [], + }, ), - ), patch.object( - mock_subtensor, - "get_vote_data", - return_value={ - "ayes": [mock_wallet.hotkey.ss58_address] if vote_in_ayes else [], - "nays": [mock_wallet.hotkey.ss58_address] if vote_in_nays else [], - }, ): # Act result = vote_senate_extrinsic( @@ -211,19 +217,22 @@ def test_leave_senate_extrinsic( test_id, ): # Arrange - with patch( - "bittensor.extrinsics.senate.Confirm.ask", return_value=not prompt - ), patch("bittensor.extrinsics.senate.time.sleep"), patch.object( - mock_subtensor.substrate, "compose_call" - ), patch.object(mock_subtensor.substrate, "create_signed_extrinsic"), patch.object( - mock_subtensor.substrate, - "submit_extrinsic", - return_value=MagicMock( - is_success=response_success, - process_events=MagicMock(), - error_message="error", + with ( + patch("bittensor.extrinsics.senate.Confirm.ask", return_value=not prompt), + patch("bittensor.extrinsics.senate.time.sleep"), + patch.object(mock_subtensor.substrate, "compose_call"), + patch.object(mock_subtensor.substrate, "create_signed_extrinsic"), + patch.object( + mock_subtensor.substrate, + "submit_extrinsic", + return_value=MagicMock( + is_success=response_success, + process_events=MagicMock(), + error_message="error", + ), ), - ), patch.object(mock_wallet, "is_senate_member", return_value=is_registered): + patch.object(mock_wallet, "is_senate_member", return_value=is_registered), + ): # Act result = leave_senate_extrinsic( subtensor=mock_subtensor, diff --git a/tests/unit_tests/extrinsics/test_serving.py b/tests/unit_tests/extrinsics/test_serving.py index bf975e195a..ea8e66237a 100644 --- a/tests/unit_tests/extrinsics/test_serving.py +++ b/tests/unit_tests/extrinsics/test_serving.py @@ -1,14 +1,15 @@ +from unittest.mock import MagicMock, patch + import pytest -from unittest.mock import MagicMock, patch -from bittensor.subtensor import Subtensor -from bittensor.wallet import wallet as Wallet from bittensor.axon import axon as Axon from bittensor.extrinsics.serving import ( - serve_extrinsic, publish_metadata, serve_axon_extrinsic, + serve_extrinsic, ) +from bittensor.subtensor import Subtensor +from bittensor.wallet import wallet as Wallet @pytest.fixture @@ -280,12 +281,15 @@ def test_serve_axon_extrinsic( ): mock_axon.external_ip = external_ip # Arrange - with patch( - "bittensor.utils.networking.get_external_ip", - side_effect=Exception("Failed to fetch IP") - if not external_ip_success - else MagicMock(return_value="192.168.1.1"), - ), patch.object(mock_subtensor, "serve", return_value=serve_success): + with ( + patch( + "bittensor.utils.networking.get_external_ip", + side_effect=Exception("Failed to fetch IP") + if not external_ip_success + else MagicMock(return_value="192.168.1.1"), + ), + patch.object(mock_subtensor, "serve", return_value=serve_success), + ): # Act if not external_ip_success: with pytest.raises(RuntimeError): @@ -349,15 +353,17 @@ def test_publish_metadata( test_id, ): # Arrange - with patch.object(mock_subtensor.substrate, "compose_call"), patch.object( - mock_subtensor.substrate, "create_signed_extrinsic" - ), patch.object( - mock_subtensor.substrate, - "submit_extrinsic", - return_value=MagicMock( - is_success=response_success, - process_events=MagicMock(), - error_message="error", + with ( + patch.object(mock_subtensor.substrate, "compose_call"), + patch.object(mock_subtensor.substrate, "create_signed_extrinsic"), + patch.object( + mock_subtensor.substrate, + "submit_extrinsic", + return_value=MagicMock( + is_success=response_success, + process_events=MagicMock(), + error_message="error", + ), ), ): # Act diff --git a/tests/unit_tests/extrinsics/test_set_weights.py b/tests/unit_tests/extrinsics/test_set_weights.py index 68ce7acae9..d1c354530c 100644 --- a/tests/unit_tests/extrinsics/test_set_weights.py +++ b/tests/unit_tests/extrinsics/test_set_weights.py @@ -1,6 +1,8 @@ -import torch -import pytest from unittest.mock import MagicMock, patch + +import pytest +import torch + from bittensor import subtensor, wallet from bittensor.extrinsics.set_weights import set_weights_extrinsic @@ -68,14 +70,18 @@ def test_set_weights_extrinsic( ): uids_tensor = torch.tensor(uids, dtype=torch.int64) weights_tensor = torch.tensor(weights, dtype=torch.float32) - with patch( - "bittensor.utils.weight_utils.convert_weights_and_uids_for_emit", - return_value=(uids_tensor, weights_tensor), - ), patch("rich.prompt.Confirm.ask", return_value=user_accepts), patch.object( - mock_subtensor, - "_do_set_weights", - return_value=(expected_success, "Mock error message"), - ) as mock_do_set_weights: + with ( + patch( + "bittensor.utils.weight_utils.convert_weights_and_uids_for_emit", + return_value=(uids_tensor, weights_tensor), + ), + patch("rich.prompt.Confirm.ask", return_value=user_accepts), + patch.object( + mock_subtensor, + "_do_set_weights", + return_value=(expected_success, "Mock error message"), + ) as mock_do_set_weights, + ): result, message = set_weights_extrinsic( subtensor=mock_subtensor, wallet=mock_wallet, diff --git a/tests/unit_tests/extrinsics/test_staking.py b/tests/unit_tests/extrinsics/test_staking.py index 288e065f78..28fb6f3299 100644 --- a/tests/unit_tests/extrinsics/test_staking.py +++ b/tests/unit_tests/extrinsics/test_staking.py @@ -1,12 +1,14 @@ +from unittest.mock import MagicMock, patch + import pytest -from unittest.mock import patch, MagicMock + import bittensor -from bittensor.utils.balance import Balance +from bittensor.errors import NotDelegateError from bittensor.extrinsics.staking import ( add_stake_extrinsic, add_stake_multiple_extrinsic, ) -from bittensor.errors import NotDelegateError +from bittensor.utils.balance import Balance # Mocking external dependencies @@ -117,25 +119,29 @@ def test_add_stake_extrinsic( if staking_balance > bittensor.Balance.from_rao(1000): staking_balance = staking_balance - bittensor.Balance.from_rao(1000) - with patch.object( - mock_subtensor, "_do_stake", return_value=expected_success - ) as mock_add_stake, patch.object( - mock_subtensor, "get_balance", return_value=Balance.from_tao(100) - ), patch.object( - mock_subtensor, - "get_stake_for_coldkey_and_hotkey", - return_value=Balance.from_tao(50), - ), patch.object( - mock_subtensor, - "get_hotkey_owner", - return_value=mock_wallet.coldkeypub.ss58_address - if hotkey_owner - else mock_other_owner_wallet.coldkeypub.ss58_address, - ), patch.object( - mock_subtensor, "is_hotkey_delegate", return_value=hotkey_delegate - ), patch.object(mock_subtensor, "get_delegate_take", return_value=0.01), patch( - "rich.prompt.Confirm.ask", return_value=user_accepts - ) as mock_confirm: + with ( + patch.object( + mock_subtensor, "_do_stake", return_value=expected_success + ) as mock_add_stake, + patch.object(mock_subtensor, "get_balance", return_value=Balance.from_tao(100)), + patch.object( + mock_subtensor, + "get_stake_for_coldkey_and_hotkey", + return_value=Balance.from_tao(50), + ), + patch.object( + mock_subtensor, + "get_hotkey_owner", + return_value=mock_wallet.coldkeypub.ss58_address + if hotkey_owner + else mock_other_owner_wallet.coldkeypub.ss58_address, + ), + patch.object( + mock_subtensor, "is_hotkey_delegate", return_value=hotkey_delegate + ), + patch.object(mock_subtensor, "get_delegate_take", return_value=0.01), + patch("rich.prompt.Confirm.ask", return_value=user_accepts) as mock_confirm, + ): # Act if not hotkey_owner and not hotkey_delegate: with pytest.raises(exception): @@ -494,17 +500,22 @@ def stake_side_effect(hotkey_ss58, *args, **kwargs): index = hotkey_ss58s.index(hotkey_ss58) return stake_responses[index] - with patch.object( - mock_subtensor, "get_balance", return_value=Balance.from_tao(wallet_balance) - ), patch.object( - mock_subtensor, "is_hotkey_delegate", side_effect=hotkey_delegate_side_effect - ), patch.object( - mock_subtensor, "get_hotkey_owner", side_effect=owner_side_effect - ), patch.object( - mock_subtensor, "_do_stake", side_effect=stake_side_effect - ) as mock_do_stake, patch.object( - mock_subtensor, "tx_rate_limit", return_value=0 - ), patch("rich.prompt.Confirm.ask", return_value=prompt_response) as mock_confirm: + with ( + patch.object( + mock_subtensor, "get_balance", return_value=Balance.from_tao(wallet_balance) + ), + patch.object( + mock_subtensor, + "is_hotkey_delegate", + side_effect=hotkey_delegate_side_effect, + ), + patch.object(mock_subtensor, "get_hotkey_owner", side_effect=owner_side_effect), + patch.object( + mock_subtensor, "_do_stake", side_effect=stake_side_effect + ) as mock_do_stake, + patch.object(mock_subtensor, "tx_rate_limit", return_value=0), + patch("rich.prompt.Confirm.ask", return_value=prompt_response) as mock_confirm, + ): # Act if exception: with pytest.raises(exception) as exc_info: diff --git a/tests/unit_tests/extrinsics/test_unstaking.py b/tests/unit_tests/extrinsics/test_unstaking.py index 6ad0a977e7..4f4e2a906b 100644 --- a/tests/unit_tests/extrinsics/test_unstaking.py +++ b/tests/unit_tests/extrinsics/test_unstaking.py @@ -1,10 +1,10 @@ -import bittensor -import pytest +from unittest.mock import MagicMock, patch -from unittest.mock import patch, MagicMock +import pytest -from bittensor.utils.balance import Balance +import bittensor from bittensor.extrinsics.unstaking import unstake_extrinsic, unstake_multiple_extrinsic +from bittensor.utils.balance import Balance @pytest.fixture @@ -71,19 +71,21 @@ def test_unstake_extrinsic( mock_current_stake = Balance.from_tao(50) mock_current_balance = Balance.from_tao(100) - with patch.object( - mock_subtensor, "_do_unstake", return_value=(expected_success) - ), patch.object( - mock_subtensor, "get_balance", return_value=mock_current_balance - ), patch.object( - mock_subtensor, - "get_minimum_required_stake", - side_effect=mock_get_minimum_required_stake, - ), patch.object( - mock_subtensor, - "get_stake_for_coldkey_and_hotkey", - return_value=mock_current_stake, - ), patch("rich.prompt.Confirm.ask", return_value=user_accepts) as mock_confirm: + with ( + patch.object(mock_subtensor, "_do_unstake", return_value=(expected_success)), + patch.object(mock_subtensor, "get_balance", return_value=mock_current_balance), + patch.object( + mock_subtensor, + "get_minimum_required_stake", + side_effect=mock_get_minimum_required_stake, + ), + patch.object( + mock_subtensor, + "get_stake_for_coldkey_and_hotkey", + return_value=mock_current_stake, + ), + patch("rich.prompt.Confirm.ask", return_value=user_accepts) as mock_confirm, + ): result = unstake_extrinsic( subtensor=mock_subtensor, wallet=mock_wallet, @@ -281,19 +283,26 @@ def unstake_side_effect(hotkey_ss58, *args, **kwargs): index = hotkey_ss58s.index(hotkey_ss58) return unstake_responses[index] - with patch.object( - mock_subtensor, "_do_unstake", side_effect=unstake_side_effect - ) as mock_unstake, patch.object( - mock_subtensor, - "get_minimum_required_stake", - side_effect=mock_get_minimum_required_stake, - ), patch.object( - mock_subtensor, "get_balance", return_value=Balance.from_tao(wallet_balance) - ), patch.object(mock_subtensor, "tx_rate_limit", return_value=0), patch.object( - mock_subtensor, - "get_stake_for_coldkey_and_hotkey", - return_value=mock_current_stake, - ), patch("rich.prompt.Confirm.ask", return_value=prompt_response) as mock_confirm: + with ( + patch.object( + mock_subtensor, "_do_unstake", side_effect=unstake_side_effect + ) as mock_unstake, + patch.object( + mock_subtensor, + "get_minimum_required_stake", + side_effect=mock_get_minimum_required_stake, + ), + patch.object( + mock_subtensor, "get_balance", return_value=Balance.from_tao(wallet_balance) + ), + patch.object(mock_subtensor, "tx_rate_limit", return_value=0), + patch.object( + mock_subtensor, + "get_stake_for_coldkey_and_hotkey", + return_value=mock_current_stake, + ), + patch("rich.prompt.Confirm.ask", return_value=prompt_response) as mock_confirm, + ): # Act if exception: with pytest.raises(exception) as exc_info: diff --git a/tests/unit_tests/test_axon.py b/tests/unit_tests/test_axon.py index 36d0ba2d00..75f55035d0 100644 --- a/tests/unit_tests/test_axon.py +++ b/tests/unit_tests/test_axon.py @@ -27,12 +27,12 @@ # Third Party import netaddr import pytest -from starlette.requests import Request from fastapi.testclient import TestClient +from starlette.requests import Request # Bittensor import bittensor -from bittensor import Synapse, RunException +from bittensor import RunException, Synapse from bittensor.axon import AxonMiddleware from bittensor.axon import axon as Axon @@ -42,33 +42,33 @@ def test_attach(): server = bittensor.axon() # Define the Synapse type - class Synapse(bittensor.Synapse): + class DummySynapse(bittensor.Synapse): pass # Define the functions with the correct signatures - def forward_fn(synapse: Synapse) -> Any: + def forward_fn(synapse: DummySynapse) -> Any: pass - def blacklist_fn(synapse: Synapse) -> bool: - return True + def blacklist_fn(synapse: DummySynapse) -> tuple[bool, str]: + return True, "" - def priority_fn(synapse: Synapse) -> float: + def priority_fn(synapse: DummySynapse) -> float: return 1.0 - def verify_fn(synapse: Synapse) -> None: + def verify_fn(synapse: DummySynapse) -> None: pass # Test attaching with correct signatures server.attach(forward_fn, blacklist_fn, priority_fn, verify_fn) # Define functions with incorrect signatures - def wrong_blacklist_fn(synapse: Synapse) -> int: + def wrong_blacklist_fn(synapse: DummySynapse) -> int: return 1 - def wrong_priority_fn(synapse: Synapse) -> int: + def wrong_priority_fn(synapse: DummySynapse) -> int: return 1 - def wrong_verify_fn(synapse: Synapse) -> bool: + def wrong_verify_fn(synapse: DummySynapse) -> bool: return True # Test attaching with incorrect signatures @@ -82,7 +82,7 @@ def wrong_verify_fn(synapse: Synapse) -> bool: server.attach(forward_fn, blacklist_fn, priority_fn, wrong_verify_fn) -def test_attach(): +def test_attach__inheritance(): # Create a mock AxonServer instance server = bittensor.axon() diff --git a/tests/unit_tests/test_chain_data.py b/tests/unit_tests/test_chain_data.py index a6474bbee9..1937d53760 100644 --- a/tests/unit_tests/test_chain_data.py +++ b/tests/unit_tests/test_chain_data.py @@ -1,6 +1,7 @@ import pytest -import bittensor import torch + +import bittensor from bittensor.chain_data import AxonInfo, ChainDataType, DelegateInfo, NeuronInfo SS58_FORMAT = bittensor.__ss58_format__ diff --git a/tests/unit_tests/test_dendrite.py b/tests/unit_tests/test_dendrite.py index c30ecc58fa..cc74c09d92 100644 --- a/tests/unit_tests/test_dendrite.py +++ b/tests/unit_tests/test_dendrite.py @@ -17,14 +17,14 @@ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. -from pydantic import ValidationError -import pytest import typing -import bittensor from unittest.mock import MagicMock, Mock -from tests.helpers import _get_mock_wallet +import pytest + +import bittensor from bittensor.synapse import TerminalInfo +from tests.helpers import _get_mock_wallet class SynapseDummy(bittensor.Synapse): @@ -79,12 +79,12 @@ def test_init(setup_dendrite): def test_str(dendrite_obj): - expected_string = "dendrite({})".format(dendrite_obj.keypair.ss58_address) + expected_string = f"dendrite({dendrite_obj.keypair.ss58_address})" assert str(dendrite_obj) == expected_string def test_repr(dendrite_obj): - expected_string = "dendrite({})".format(dendrite_obj.keypair.ss58_address) + expected_string = f"dendrite({dendrite_obj.keypair.ss58_address})" assert repr(dendrite_obj) == expected_string @@ -93,7 +93,7 @@ def test_close(dendrite_obj, setup_axon): # Query the axon to open a session dendrite_obj.query(axon, SynapseDummy(input=1)) # Session should be automatically closed after query - assert dendrite_obj._session == None + assert dendrite_obj._session is None @pytest.mark.asyncio @@ -101,14 +101,14 @@ async def test_aclose(dendrite_obj, setup_axon): axon = setup_axon # Use context manager to open an async session async with dendrite_obj: - resp = await dendrite_obj([axon], SynapseDummy(input=1), deserialize=False) + await dendrite_obj([axon], SynapseDummy(input=1), deserialize=False) # Close should automatically be called on the session after context manager scope - assert dendrite_obj._session == None + assert dendrite_obj._session is None class AsyncMock(Mock): def __call__(self, *args, **kwargs): - sup = super(AsyncMock, self) + sup = super() async def coro(): return sup.__call__(*args, **kwargs) @@ -306,7 +306,7 @@ async def test_dendrite__call__success_response( ) ) mock_aioresponse.post( - f"http://127.0.0.1:666/SynapseDummy", + "http://127.0.0.1:666/SynapseDummy", body=expected_synapse.json(), ) synapse = await dendrite_obj.call(axon_info, synapse=input_synapse) @@ -326,7 +326,7 @@ async def test_dendrite__call__handles_http_error_response( message = "Custom Error" mock_aioresponse.post( - f"http://127.0.0.1:666/SynapseDummy", + "http://127.0.0.1:666/SynapseDummy", status=status_code, payload={"message": message}, ) diff --git a/tests/unit_tests/test_keyfile.py b/tests/unit_tests/test_keyfile.py index d20af809f9..7d030e42e9 100644 --- a/tests/unit_tests/test_keyfile.py +++ b/tests/unit_tests/test_keyfile.py @@ -15,19 +15,20 @@ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. -import os import json -import time -import pytest +import os import shutil -import bittensor +import time import unittest.mock as mock + +import pytest +from bip39 import bip39_validate from scalecodec import ScaleBytes from substrateinterface import Keypair, KeypairType from substrateinterface.constants import DEV_PHRASE from substrateinterface.exceptions import ConfigurationError -from bip39 import bip39_validate +import bittensor from bittensor import get_coldkey_password_from_environment @@ -36,7 +37,7 @@ def test_generate_mnemonic(): Test the generation of a mnemonic and its validation. """ mnemonic = Keypair.generate_mnemonic() - assert bip39_validate(mnemonic) == True + assert bip39_validate(mnemonic) is True def test_invalid_mnemonic(): @@ -44,7 +45,7 @@ def test_invalid_mnemonic(): Test the validation of an invalid mnemonic. """ mnemonic = "This is an invalid mnemonic" - assert bip39_validate(mnemonic) == False + assert bip39_validate(mnemonic) is False def test_create_sr25519_keypair(): @@ -114,7 +115,7 @@ def test_sign_and_verify(): mnemonic = Keypair.generate_mnemonic() keypair = Keypair.create_from_mnemonic(mnemonic) signature = keypair.sign("Test1231223123123") - assert keypair.verify("Test1231223123123", signature) == True + assert keypair.verify("Test1231223123123", signature) is True def test_sign_and_verify_hex_data(): @@ -124,7 +125,7 @@ def test_sign_and_verify_hex_data(): mnemonic = Keypair.generate_mnemonic() keypair = Keypair.create_from_mnemonic(mnemonic) signature = keypair.sign("0x1234") - assert keypair.verify("0x1234", signature) == True + assert keypair.verify("0x1234", signature) is True def test_sign_and_verify_scale_bytes(): @@ -135,7 +136,7 @@ def test_sign_and_verify_scale_bytes(): keypair = Keypair.create_from_mnemonic(mnemonic) data = ScaleBytes("0x1234") signature = keypair.sign(data) - assert keypair.verify(data, signature) == True + assert keypair.verify(data, signature) is True def test_sign_missing_private_key(): @@ -180,7 +181,7 @@ def test_sign_and_verify_incorrect_signature(): mnemonic = Keypair.generate_mnemonic() keypair = Keypair.create_from_mnemonic(mnemonic) signature = "0x4c291bfb0bb9c1274e86d4b666d13b2ac99a0bacc04a4846fb8ea50bda114677f83c1f164af58fc184451e5140cc8160c4de626163b11451d3bbb208a1889f8a" - assert keypair.verify("Test1231223123123", signature) == False + assert keypair.verify("Test1231223123123", signature) is False def test_sign_and_verify_invalid_signature(): @@ -201,7 +202,7 @@ def test_sign_and_verify_invalid_message(): mnemonic = Keypair.generate_mnemonic() keypair = Keypair.create_from_mnemonic(mnemonic) signature = keypair.sign("Test1231223123123") - assert keypair.verify("OtherMessage", signature) == False + assert keypair.verify("OtherMessage", signature) is False def test_create_ed25519_keypair(): @@ -222,7 +223,7 @@ def test_sign_and_verify_ed25519(): mnemonic = Keypair.generate_mnemonic() keypair = Keypair.create_from_mnemonic(mnemonic, crypto_type=KeypairType.ED25519) signature = keypair.sign("Test1231223123123") - assert keypair.verify("Test1231223123123", signature) == True + assert keypair.verify("Test1231223123123", signature) is True def test_sign_and_verify_invalid_signature_ed25519(): @@ -232,7 +233,7 @@ def test_sign_and_verify_invalid_signature_ed25519(): mnemonic = Keypair.generate_mnemonic() keypair = Keypair.create_from_mnemonic(mnemonic, crypto_type=KeypairType.ED25519) signature = "0x4c291bfb0bb9c1274e86d4b666d13b2ac99a0bacc04a4846fb8ea50bda114677f83c1f164af58fc184451e5140cc8160c4de626163b11451d3bbb208a1889f8a" - assert keypair.verify("Test1231223123123", signature) == False + assert keypair.verify("Test1231223123123", signature) is False def test_unsupport_crypto_type(): @@ -465,13 +466,13 @@ def test_validate_password(): """ from bittensor.keyfile import validate_password - assert validate_password(None) == False - assert validate_password("passw0rd") == False - assert validate_password("123456789") == False + assert validate_password(None) is False + assert validate_password("passw0rd") is False + assert validate_password("123456789") is False with mock.patch("getpass.getpass", return_value="biTTensor"): - assert validate_password("biTTensor") == True + assert validate_password("biTTensor") is True with mock.patch("getpass.getpass", return_value="biTTenso"): - assert validate_password("biTTensor") == False + assert validate_password("biTTensor") is False def test_decrypt_keyfile_data_legacy(): @@ -546,7 +547,7 @@ def test_overwriting(keyfile_setup_teardown): ) bob = bittensor.Keypair.create_from_uri("/Bob") - with pytest.raises(bittensor.KeyFileError) as pytest_wrapped_e: + with pytest.raises(bittensor.KeyFileError): with mock.patch("builtins.input", return_value="n"): keyfile.set_keypair( bob, encrypt=True, overwrite=False, password="thisisafakepassword" @@ -590,8 +591,10 @@ def test_deserialize_keypair_from_keyfile_data(keyfile_setup_teardown): then deserializes the keyfile data to a keypair. It then asserts that the deserialized keypair matches the original keypair. """ - from bittensor.keyfile import serialized_keypair_to_keyfile_data - from bittensor.keyfile import deserialize_keypair_from_keyfile_data + from bittensor.keyfile import ( + deserialize_keypair_from_keyfile_data, + serialized_keypair_to_keyfile_data, + ) root_path = keyfile_setup_teardown keyfile = bittensor.keyfile(path=os.path.join(root_path, "keyfile")) diff --git a/tests/unit_tests/test_logging.py b/tests/unit_tests/test_logging.py index 1822fc86ef..d4d036fb2f 100644 --- a/tests/unit_tests/test_logging.py +++ b/tests/unit_tests/test_logging.py @@ -1,9 +1,11 @@ -import pytest -import multiprocessing import logging as stdlogging +import multiprocessing from unittest.mock import MagicMock, patch + +import pytest + from bittensor.btlogging import LoggingMachine -from bittensor.btlogging.defines import DEFAULT_LOG_FILE_NAME, BITTENSOR_LOGGER_NAME +from bittensor.btlogging.defines import BITTENSOR_LOGGER_NAME, DEFAULT_LOG_FILE_NAME from bittensor.btlogging.loggingmachine import LoggingConfig @@ -130,7 +132,7 @@ def test_enable_file_logging_with_new_config(tmp_path): """ log_dir = tmp_path / "logs" log_dir.mkdir() # Create the temporary directory - log_file_path = log_dir / DEFAULT_LOG_FILE_NAME + log_dir / DEFAULT_LOG_FILE_NAME # check no file handler is created config = LoggingConfig(debug=False, trace=False, record_log=True, logging_dir=None) diff --git a/tests/unit_tests/test_metagraph.py b/tests/unit_tests/test_metagraph.py index af0dbdba76..67abd75b4a 100644 --- a/tests/unit_tests/test_metagraph.py +++ b/tests/unit_tests/test_metagraph.py @@ -15,13 +15,13 @@ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. -from unittest.mock import Mock -import pytest +from unittest.mock import MagicMock, Mock + import numpy as np -import bittensor +import pytest +import bittensor from bittensor.metagraph import metagraph as Metagraph -from unittest.mock import MagicMock @pytest.fixture diff --git a/tests/unit_tests/test_overview.py b/tests/unit_tests/test_overview.py index 638ab4df4c..70d5e4cb84 100644 --- a/tests/unit_tests/test_overview.py +++ b/tests/unit_tests/test_overview.py @@ -92,17 +92,20 @@ def test_get_total_balance( mock_wallet.coldkeypub_file.exists_on_device.return_value = exists_on_device mock_wallet.coldkeypub_file.is_encrypted.return_value = is_encrypted - with patch( - "bittensor.wallet", return_value=mock_wallet - ) as mock_wallet_constructor, patch( - "bittensor.commands.overview.get_coldkey_wallets_for_path", - return_value=[mock_wallet] if config_all else [], - ), patch( - "bittensor.commands.overview.get_all_wallets_for_path", - return_value=[mock_wallet], - ), patch( - "bittensor.commands.overview.get_hotkey_wallets_for_wallet", - return_value=[mock_wallet], + with ( + patch("bittensor.wallet", return_value=mock_wallet), + patch( + "bittensor.commands.overview.get_coldkey_wallets_for_path", + return_value=[mock_wallet] if config_all else [], + ), + patch( + "bittensor.commands.overview.get_all_wallets_for_path", + return_value=[mock_wallet], + ), + patch( + "bittensor.commands.overview.get_hotkey_wallets_for_wallet", + return_value=[mock_wallet], + ), ): # Act result_hotkeys, result_balance = OverviewCommand._get_total_balance( diff --git a/tests/unit_tests/test_subtensor.py b/tests/unit_tests/test_subtensor.py index ee1dd06b58..77e44f1ee5 100644 --- a/tests/unit_tests/test_subtensor.py +++ b/tests/unit_tests/test_subtensor.py @@ -25,12 +25,12 @@ # Application import bittensor +from bittensor import subtensor_module from bittensor.subtensor import ( + Balance, Subtensor, _logger, - Balance, ) -from bittensor import subtensor_module def test_serve_axon_with_external_ip_set(): @@ -41,7 +41,7 @@ def test_serve_axon_with_external_ip_set(): mock_subtensor = MagicMock(spec=bittensor.subtensor, serve_axon=mock_serve_axon) - mock_add_insecure_port = mock.MagicMock(return_value=None) + mock.MagicMock(return_value=None) mock_wallet = MagicMock( spec=bittensor.wallet, coldkey=MagicMock(), @@ -1836,7 +1836,7 @@ def test_get_all_subnets_info_success(mocker, subtensor): ) # Call - result = subtensor.get_all_subnets_info(block) + subtensor.get_all_subnets_info(block) # Asserts subtensor.substrate.get_block_hash.assert_called_once_with(block) @@ -1915,7 +1915,7 @@ def test_get_subnet_info_success(mocker, subtensor): ) # Call - result = subtensor.get_subnet_info(netuid, block) + subtensor.get_subnet_info(netuid, block) # Asserts subtensor.substrate.get_block_hash.assert_called_once_with(block) @@ -1970,7 +1970,7 @@ def test_get_subnet_info_retry(mocker, subtensor): ) # Call - result = subtensor.get_subnet_info(netuid, block) + subtensor.get_subnet_info(netuid, block) # Asserts subtensor.substrate.get_block_hash.assert_called_with(block) @@ -1994,7 +1994,7 @@ def test_get_subnet_hyperparameters_success(mocker, subtensor): ) # Call - result = subtensor.get_subnet_hyperparameters(netuid, block) + subtensor.get_subnet_hyperparameters(netuid, block) # Asserts subtensor.query_runtime_api.assert_called_once_with( @@ -2041,7 +2041,7 @@ def test_get_subnet_hyperparameters_hex_without_prefix(mocker, subtensor): mocker.patch.object(subtensor_module.SubnetHyperparameters, "from_vec_u8") # Call - result = subtensor.get_subnet_hyperparameters(netuid, block) + subtensor.get_subnet_hyperparameters(netuid, block) # Asserts subtensor.query_runtime_api.assert_called_once_with( @@ -2170,7 +2170,6 @@ def test_get_delegate_take_no_data(mocker, subtensor): # Prep hotkey_ss58 = "hotkey_ss58" block = 123 - delegate_take_value = 32768 mocker.patch.object(subtensor, "query_subtensor", return_value=None) spy_u16_normalized_float = mocker.spy(subtensor_module, "U16_NORMALIZED_FLOAT") diff --git a/tests/unit_tests/test_synapse.py b/tests/unit_tests/test_synapse.py index b0ce4f1325..a66e0cd276 100644 --- a/tests/unit_tests/test_synapse.py +++ b/tests/unit_tests/test_synapse.py @@ -14,11 +14,13 @@ # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. -import json import base64 +import json +from typing import ClassVar, Optional + import pytest + import bittensor -from typing import Optional, ClassVar def test_parse_headers_to_inputs(): diff --git a/tests/unit_tests/test_tensor.py b/tests/unit_tests/test_tensor.py index 9939b397e7..b7a64ce1fe 100644 --- a/tests/unit_tests/test_tensor.py +++ b/tests/unit_tests/test_tensor.py @@ -14,12 +14,13 @@ # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. -import pytest -import numpy as np -import bittensor import numpy +import numpy as np +import pytest import torch +import bittensor + # This is a fixture that creates an example tensor for testing @pytest.fixture diff --git a/tests/unit_tests/test_wallet.py b/tests/unit_tests/test_wallet.py index 0d0466e344..875e80c2b8 100644 --- a/tests/unit_tests/test_wallet.py +++ b/tests/unit_tests/test_wallet.py @@ -16,15 +16,17 @@ # DEALINGS IN THE SOFTWARE. import json -import time -import pytest import random import re +import time +from unittest.mock import patch + +import pytest +from ansible_vault import Vault +from rich.prompt import Confirm + import bittensor from bittensor.errors import KeyFileError -from rich.prompt import Confirm -from ansible_vault import Vault -from unittest.mock import patch def legacy_encrypt_keyfile_data(keyfile_data: bytes, password: str = None) -> bytes: @@ -69,7 +71,7 @@ def _legacy_encrypt_keyfile_data(*args, **kwargs): path="/tmp/tests_wallets/do_not_use", ) legacy_password = ( - default_legacy_password if legacy_password == None else legacy_password + default_legacy_password if legacy_password is None else legacy_password ) # create a legacy ansible wallet @@ -168,8 +170,9 @@ def test_check_and_update_encryption_not_updated(wallet_update_setup): legacy_wallet = create_legacy_wallet( default_legacy_password=default_legacy_password ) - with patch("getpass.getpass", return_value="wrong_password"), patch.object( - Confirm, "ask", return_value=False + with ( + patch("getpass.getpass", return_value="wrong_password"), + patch.object(Confirm, "ask", return_value=False), ): assert not legacy_wallet.coldkey_file.check_and_update_encryption() @@ -198,8 +201,8 @@ def check_new_coldkey_file(keyfile): ) new_path = legacy_wallet.coldkey_file.path - assert old_coldkey_file_data != None - assert new_keyfile_data != None + assert old_coldkey_file_data is not None + assert new_keyfile_data is not None assert not old_coldkey_file_data == new_keyfile_data assert bittensor.keyfile_data_is_encrypted_ansible(old_coldkey_file_data) assert bittensor.keyfile_data_is_encrypted_nacl(new_keyfile_data) @@ -216,7 +219,7 @@ def check_new_hotkey_file(keyfile): assert new_path == old_hotkey_path assert not bittensor.keyfile_data_is_encrypted(new_keyfile_data) - if legacy_wallet == None: + if legacy_wallet is None: legacy_password = f"PASSword-{random.randint(0, 10000)}" legacy_wallet = create_legacy_wallet(legacy_password=legacy_password) @@ -235,8 +238,9 @@ def check_new_hotkey_file(keyfile): old_hotkey_path = legacy_wallet.hotkey_file.path # update legacy_wallet from ansible to nacl - with patch("getpass.getpass", return_value=legacy_password), patch.object( - Confirm, "ask", return_value=True + with ( + patch("getpass.getpass", return_value=legacy_password), + patch.object(Confirm, "ask", return_value=True), ): legacy_wallet.coldkey_file.check_and_update_encryption() @@ -461,9 +465,10 @@ def test_regen_coldkey_mnemonic(mock_wallet, mnemonic, expected_exception): """Test the `regenerate_coldkey` method of the wallet class, which regenerates the cold key pair from a mnemonic. We test different input formats of mnemonics and check if the function works as expected. """ - with patch.object(mock_wallet, "set_coldkey") as mock_set_coldkey, patch.object( - mock_wallet, "set_coldkeypub" - ) as mock_set_coldkeypub: + with ( + patch.object(mock_wallet, "set_coldkey") as mock_set_coldkey, + patch.object(mock_wallet, "set_coldkeypub") as mock_set_coldkeypub, + ): if expected_exception: with pytest.raises(expected_exception): mock_wallet.regenerate_coldkey( @@ -490,8 +495,9 @@ def test_regen_coldkey_overwrite_functionality( ss58_addr = "5D5cwd8DX6ij7nouVcoxDuWtJfiR1BnzCkiBVTt7DU8ft5Ta" seed_str = "0x659c024d5be809000d0d93fe378cfde020846150b01c49a201fc2a02041f7636" - with patch.object(mock_wallet, "set_coldkey") as mock_set_coldkey, patch( - "builtins.input", return_value=user_input + with ( + patch.object(mock_wallet, "set_coldkey") as mock_set_coldkey, + patch("builtins.input", return_value=user_input), ): if expected_exception: with pytest.raises(KeyFileError): diff --git a/tests/unit_tests/utils/test_balance.py b/tests/unit_tests/utils/test_balance.py index b99bc111f2..bb9bb72950 100644 --- a/tests/unit_tests/utils/test_balance.py +++ b/tests/unit_tests/utils/test_balance.py @@ -1,7 +1,8 @@ +from typing import Union + import pytest from hypothesis import given from hypothesis import strategies as st -from typing import Union from bittensor import Balance from tests.helpers import CLOSE_IN_VALUE @@ -439,7 +440,7 @@ def test_balance_not_eq_none(balance: Union[int, float]): Test the inequality (!=) of a Balance object and None. """ balance_ = Balance(balance) - assert not balance_ == None + assert balance_ is not None @given(balance=valid_tao_numbers_strategy) @@ -448,7 +449,7 @@ def test_balance_neq_none(balance: Union[int, float]): Test the inequality (!=) of a Balance object and None. """ balance_ = Balance(balance) - assert balance_ != None + assert balance_ is not None def test_balance_init_from_invalid_value(): diff --git a/tests/unit_tests/utils/test_networking.py b/tests/unit_tests/utils/test_networking.py index 6bc89d3f27..a74f8ac110 100644 --- a/tests/unit_tests/utils/test_networking.py +++ b/tests/unit_tests/utils/test_networking.py @@ -1,10 +1,12 @@ import os +import unittest.mock as mock import urllib +from unittest.mock import MagicMock + import pytest import requests -import unittest.mock as mock + from bittensor import utils -from unittest.mock import MagicMock # Test conversion functions for IPv4 diff --git a/tests/unit_tests/utils/test_subtensor.py b/tests/unit_tests/utils/test_subtensor.py index 1c1220bcea..ce9f346fa4 100644 --- a/tests/unit_tests/utils/test_subtensor.py +++ b/tests/unit_tests/utils/test_subtensor.py @@ -69,7 +69,7 @@ def test_save_errors_to_cache(tmp_path): st_utils._ERRORS_FILE_PATH = test_file st_utils._save_errors_to_cache("0x123", errors) - with open(test_file, "r") as file: + with open(test_file) as file: data = json.load(file) assert data["subtensor_build_id"] == "0x123" assert data["errors"] == errors diff --git a/tests/unit_tests/utils/test_utils.py b/tests/unit_tests/utils/test_utils.py index b03ab6e99c..87e8648da4 100644 --- a/tests/unit_tests/utils/test_utils.py +++ b/tests/unit_tests/utils/test_utils.py @@ -18,9 +18,10 @@ # DEALINGS IN THE SOFTWARE. import numpy as np -import bittensor.utils.weight_utils as weight_utils import pytest +import bittensor.utils.weight_utils as weight_utils + def test_convert_weight_and_uids(): uids = np.arange(10) @@ -29,18 +30,18 @@ def test_convert_weight_and_uids(): # min weight < 0 weights[5] = -1 - with pytest.raises(ValueError) as pytest_wrapped_e: + with pytest.raises(ValueError): weight_utils.convert_weights_and_uids_for_emit(uids, weights) # min uid < 0 weights[5] = 0 uids[3] = -1 - with pytest.raises(ValueError) as pytest_wrapped_e: + with pytest.raises(ValueError): weight_utils.convert_weights_and_uids_for_emit(uids, weights) # len(uids) != len(weights) uids[3] = 3 - with pytest.raises(ValueError) as pytest_wrapped_e: + with pytest.raises(ValueError): weight_utils.convert_weights_and_uids_for_emit(uids, weights[1:]) # sum(weights) == 0 diff --git a/tests/unit_tests/utils/test_version.py b/tests/unit_tests/utils/test_version.py index f9760933f3..48688cfc61 100644 --- a/tests/unit_tests/utils/test_version.py +++ b/tests/unit_tests/utils/test_version.py @@ -17,20 +17,21 @@ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. +from datetime import datetime, timedelta, timezone from pathlib import Path +from unittest.mock import MagicMock + import pytest from freezegun import freeze_time -from datetime import datetime, timedelta, timezone +from pytest_mock import MockerFixture from bittensor.utils.version import ( VERSION_CHECK_THRESHOLD, VersionCheckError, - get_and_save_latest_version, check_version, + get_and_save_latest_version, version_checking, ) -from unittest.mock import MagicMock -from pytest_mock import MockerFixture @pytest.fixture diff --git a/tests/unit_tests/utils/test_weight_utils.py b/tests/unit_tests/utils/test_weight_utils.py index edf334db50..74a1ea0021 100644 --- a/tests/unit_tests/utils/test_weight_utils.py +++ b/tests/unit_tests/utils/test_weight_utils.py @@ -18,9 +18,9 @@ # DEALINGS IN THE SOFTWARE. import numpy as np -import bittensor.utils.weight_utils as weight_utils import pytest +import bittensor.utils.weight_utils as weight_utils from bittensor.utils import torch @@ -31,18 +31,18 @@ def test_convert_weight_and_uids(): # min weight < 0 weights[5] = -1 - with pytest.raises(ValueError) as pytest_wrapped_e: + with pytest.raises(ValueError): weight_utils.convert_weights_and_uids_for_emit(uids, weights) # min uid < 0 weights[5] = 0 uids[3] = -1 - with pytest.raises(ValueError) as pytest_wrapped_e: + with pytest.raises(ValueError): weight_utils.convert_weights_and_uids_for_emit(uids, weights) # len(uids) != len(weights) uids[3] = 3 - with pytest.raises(ValueError) as pytest_wrapped_e: + with pytest.raises(ValueError): weight_utils.convert_weights_and_uids_for_emit(uids, weights[1:]) # sum(weights) == 0 @@ -63,16 +63,16 @@ def test_convert_weight_and_uids_torch(force_legacy_torch_compat_api): # min weight < 0 weights[5] = -1 - with pytest.raises(ValueError) as pytest_wrapped_e: + with pytest.raises(ValueError): weight_utils.convert_weights_and_uids_for_emit(uids, weights) # min uid < 0 weights[5] = 0 uids[3] = -1 - with pytest.raises(ValueError) as pytest_wrapped_e: + with pytest.raises(ValueError): weight_utils.convert_weights_and_uids_for_emit(uids, weights) # len(uids) != len(weights) uids[3] = 3 - with pytest.raises(ValueError) as pytest_wrapped_e: + with pytest.raises(ValueError): weight_utils.convert_weights_and_uids_for_emit(uids, weights[1:]) # sum(weights) == 0 @@ -336,7 +336,7 @@ def test_convert_root_weight_uids_and_vals_to_tensor_happy_paths( ), # All zero weights ], ) -def test_convert_root_weight_uids_and_vals_to_tensor_edge_cases( +def test_convert_root_weight_uids_and_vals_to_tensor_edge_cases__torch( test_id, n, uids, weights, subnets, expected, force_legacy_torch_compat_api ): # Act