Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions bittensor/core/async_subtensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@
from bittensor_wallet import Wallet
from bittensor.core.axon import Axon
from bittensor.utils import Certificate
from async_substrate_interface import QueryMapResult
from async_substrate_interface import AsyncQueryMapResult


class AsyncSubtensor(SubtensorMixin):
Expand Down Expand Up @@ -316,7 +316,7 @@ async def query_map(
block_hash: Optional[str] = None,
reuse_block: bool = False,
params: Optional[list] = None,
) -> "QueryMapResult":
) -> "AsyncQueryMapResult":
"""
Queries map storage from any module on the Bittensor blockchain. This function retrieves data structures that
represent key-value mappings, essential for accessing complex and structured data within the blockchain
Expand Down Expand Up @@ -354,7 +354,7 @@ async def query_map_subtensor(
block_hash: Optional[str] = None,
reuse_block: bool = False,
params: Optional[list] = None,
) -> "QueryMapResult":
) -> "AsyncQueryMapResult":
"""
Queries map storage from the Subtensor module on the Bittensor blockchain. This function is designed to retrieve
a map-like data structure, which can include various neuron-specific details or network-wide attributes.
Expand Down Expand Up @@ -1380,7 +1380,7 @@ async def get_all_metagraphs_info(
Returns:
MetagraphInfo dataclass
"""
block_hash = await self.determine_block_hash(block, block_hash.reuse_block)
block_hash = await self.determine_block_hash(block, block_hash, reuse_block)
if not block_hash and reuse_block:
block_hash = self.substrate.last_block_hash
query = await self.substrate.runtime_call(
Expand Down Expand Up @@ -2019,7 +2019,7 @@ async def get_vote_data(
network, particularly how proposals are received and acted upon by the governing body.
"""
block_hash = await self.determine_block_hash(block, block_hash, reuse_block)
vote_data = await self.substrate.query(
vote_data: dict[str, Any] = await self.substrate.query(
module="Triumvirate",
storage_function="Voting",
params=[proposal_hash],
Expand Down Expand Up @@ -2598,7 +2598,7 @@ async def subnet(
params=[netuid],
block_hash=block_hash,
)
subnet = DynamicInfo.from_vec_u8(bytes.fromhex(query.decode()[2:]))
subnet = DynamicInfo.from_vec_u8(hex_to_bytes(query.decode()))
return subnet

async def subnet_exists(
Expand Down
10 changes: 8 additions & 2 deletions bittensor/core/chain_data/dynamic_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ class DynamicInfo:
subnet_identity: Optional[SubnetIdentity]

@classmethod
def from_vec_u8(cls, vec_u8: list[int]) -> Optional["DynamicInfo"]:
def from_vec_u8(cls, vec_u8: Union[list[int], bytes]) -> Optional["DynamicInfo"]:
if len(vec_u8) == 0:
return None
decoded = from_scale_encoding(vec_u8, ChainDataType.DynamicInfo)
Expand Down Expand Up @@ -154,8 +154,11 @@ def tao_to_alpha_with_slippage(
) -> Union[tuple[Balance, Balance], float]:
"""
Returns an estimate of how much Alpha would a staker receive if they stake their tao using the current pool state.
Args:

Arguments:
tao: Amount of TAO to stake.
percentage: percentage

Returns:
If percentage is False, a tuple of balances where the first part is the amount of Alpha received, and the
second part (slippage) is the difference between the estimated amount and ideal
Expand Down Expand Up @@ -206,8 +209,11 @@ def alpha_to_tao_with_slippage(
) -> Union[tuple[Balance, Balance], float]:
"""
Returns an estimate of how much TAO would a staker receive if they unstake their alpha using the current pool state.

Args:
alpha: Amount of Alpha to stake.
percentage: percentage

Returns:
If percentage is False, a tuple of balances where the first part is the amount of TAO received, and the
second part (slippage) is the difference between the estimated amount and ideal
Expand Down
4 changes: 2 additions & 2 deletions bittensor/core/chain_data/stake_info.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from dataclasses import dataclass
from typing import Optional, Any
from typing import Any, Optional, Union

from scalecodec.utils.ss58 import ss58_encode

Expand Down Expand Up @@ -81,7 +81,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: Union[list[int], bytes]) -> 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:
Expand Down
23 changes: 9 additions & 14 deletions bittensor/core/metagraph.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import copy
import importlib
import os
import pickle
import typing
Expand Down Expand Up @@ -764,7 +763,7 @@ def _set_metagraph_attributes(self, block: int):
)
self.axons = [n.axon_info for n in self.neurons]

def save(self, root_dir: Optional[list[str]] = None) -> "AsyncMetagraph":
def save(self, root_dir: Optional[list[str]] = None) -> "MetagraphMixin":
"""
Saves the current state of the metagraph to a file on disk. This function is crucial for persisting the current
state of the network's metagraph, which can later be reloaded or analyzed. The save operation includes all
Expand Down Expand Up @@ -1022,7 +1021,7 @@ def __init__(
self.axons: list["AxonInfo"] = []
self.total_stake: list["Balance"] = []

def load_from_path(self, dir_path: str) -> "AsyncMetagraph":
def load_from_path(self, dir_path: str) -> "MetagraphMixin":
"""
Loads the metagraph state from a specified directory path.

Expand Down Expand Up @@ -1152,7 +1151,7 @@ def __init__(
self.axons: list["AxonInfo"] = []
self.total_stake: list["Balance"] = []

def load_from_path(self, dir_path: str) -> "AsyncMetagraph":
def load_from_path(self, dir_path: str) -> "MetagraphMixin":
"""
Loads the state of the Metagraph from a specified directory path.

Expand Down Expand Up @@ -1356,10 +1355,7 @@ async def _initialize_subtensor(
subtensor = self.subtensor
if not subtensor:
# Lazy import due to circular import (subtensor -> metagraph, metagraph -> subtensor)
AsyncSubtensor = getattr(
importlib.import_module("bittensor.core.async_subtensor"),
"AsyncSubtensor",
)
from bittensor.core.async_subtensor import AsyncSubtensor

async with AsyncSubtensor(network=self.chain_endpoint) as subtensor:
self.subtensor = subtensor
Expand Down Expand Up @@ -1592,7 +1588,7 @@ def sync(
"""

# Initialize subtensor
subtensor = self._initialize_subtensor(subtensor)
subtensor = self._initialize_subtensor(subtensor=subtensor)

if (
subtensor.chain_endpoint != settings.ARCHIVE_ENTRYPOINT
Expand Down Expand Up @@ -1632,11 +1628,11 @@ def _initialize_subtensor(self, subtensor: "Subtensor") -> "Subtensor":
according to the current network settings.

Args:
subtensor (bittensor.core.async_subtensor.AsyncSubtensor): The subtensor instance provided for
subtensor (bittensor.core.subtensor.Subtensor): The subtensor instance provided for
initialization. If ``None``, a new subtensor instance is created using the current network configuration.

Returns:
subtensor (bittensor.core.async_subtensor.AsyncSubtensor): The initialized subtensor instance, ready to be
subtensor (bittensor.core.subtensor.Subtensor): The initialized subtensor instance, ready to be
used for syncing the metagraph.

Internal Usage:
Expand All @@ -1650,9 +1646,8 @@ def _initialize_subtensor(self, subtensor: "Subtensor") -> "Subtensor":
subtensor = self.subtensor
if not subtensor:
# Lazy import due to circular import (subtensor -> metagraph, metagraph -> subtensor)
Subtensor = getattr(
importlib.import_module("bittensor.core.subtensor"), "Subtensor"
)
from bittensor.core.subtensor import Subtensor

subtensor = Subtensor(network=self.chain_endpoint)

self.subtensor = subtensor
Expand Down
11 changes: 7 additions & 4 deletions bittensor/core/subtensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -1181,7 +1181,7 @@ def get_stake(
block=block,
params=[hotkey_ss58, coldkey_ss58, netuid],
)
hotkey_alpha_obj: ScaleType = self.query_module(
hotkey_alpha_obj: ScaleObj = self.query_module(
module="SubtensorModule",
name="TotalHotkeyAlpha",
block=block,
Expand Down Expand Up @@ -1541,7 +1541,7 @@ def get_vote_data(
This function is important for tracking and understanding the decision-making processes within the Bittensor
network, particularly how proposals are received and acted upon by the governing body.
"""
vote_data = self.substrate.query(
vote_data: dict[str, Any] = self.substrate.query(
module="Triumvirate",
storage_function="Voting",
params=[proposal_hash],
Expand Down Expand Up @@ -2180,6 +2180,7 @@ def add_stake(
Args:
wallet (bittensor_wallet.Wallet): The wallet to be used for staking.
hotkey_ss58 (Optional[str]): The ``SS58`` address of the hotkey associated with the neuron.
netuid (Optional[int]): The unique identifier of the subnet to which the neuron belongs.
amount (Balance): The amount of TAO to stake.
wait_for_inclusion (bool): Waits for the transaction to be included in a block.
wait_for_finalization (bool): Waits for the transaction to be finalized on the blockchain.
Expand Down Expand Up @@ -2217,6 +2218,7 @@ def add_stake_multiple(
Args:
wallet (bittensor_wallet.Wallet): The wallet used for staking.
hotkey_ss58s (list[str]): List of ``SS58`` addresses of hotkeys to stake to.
netuids (list[int]): List of network UIDs to stake to.
amounts (list[Balance]): Corresponding amounts of TAO to stake for each hotkey.
wait_for_inclusion (bool): Waits for the transaction to be included in a block.
wait_for_finalization (bool): Waits for the transaction to be finalized on the blockchain.
Expand Down Expand Up @@ -2637,6 +2639,7 @@ def _blocks_weight_limit() -> bool:

retries = 0
success = False
message = "No attempt made. Perhaps it is too soon to commit weights!"
if (
uid := self.get_uid_for_hotkey_on_subnet(wallet.hotkey.ss58_address, netuid)
) is None:
Expand All @@ -2647,7 +2650,7 @@ def _blocks_weight_limit() -> bool:

if self.commit_reveal_enabled(netuid=netuid) is True:
# go with `commit reveal v3` extrinsic
message = "No attempt made. Perhaps it is too soon to commit weights!"

while retries < max_retries and success is False and _blocks_weight_limit():
logging.info(
f"Committing weights for subnet #{netuid}. Attempt {retries + 1} of {max_retries}."
Expand All @@ -2666,7 +2669,7 @@ def _blocks_weight_limit() -> bool:
return success, message
else:
# go with classic `set weights extrinsic`
message = "No attempt made. Perhaps it is too soon to set weights!"

while retries < max_retries and success is False and _blocks_weight_limit():
try:
logging.info(
Expand Down
11 changes: 0 additions & 11 deletions bittensor/core/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -202,17 +202,6 @@ def determine_chain_endpoint_and_network(
return "unknown", network


class AxonServeCallParams_(TypedDict):
"""Axon serve chain call parameters."""

version: int
ip: int
port: int
ip_type: int
netuid: int
certificate: Optional[Certificate]


class AxonServeCallParams:
def __init__(
self,
Expand Down
3 changes: 1 addition & 2 deletions bittensor/utils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,6 @@ def format_error_message(error_message: Union[dict, Exception]) -> str:
return f"Subtensor returned `{err_name}({err_type})` error. This means: `{err_description}`."


# Subnet 24 uses this function
def is_valid_ss58_address(address: str) -> bool:
"""
Checks if the given address is a valid ss58 address.
Expand Down Expand Up @@ -339,7 +338,7 @@ def decode_hex_identity_dict(info_dictionary) -> dict[str, Any]:
{'name': 'john', 'additional': [('data', 'data')]}
"""

def get_decoded(data: str) -> str:
def get_decoded(data: str) -> Optional[str]:
"""Decodes a hex-encoded string."""
try:
return bytes.fromhex(data[2:]).decode()
Expand Down
1 change: 0 additions & 1 deletion bittensor/utils/balance.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import warnings

from typing import Union, TypedDict, Optional

from scalecodec import ScaleType
Expand Down
4 changes: 2 additions & 2 deletions bittensor/utils/delegates_details.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from dataclasses import dataclass
from typing import Any, Optional
from typing import Any, Optional, Union


# TODO: consider move it to `bittensor.core.chain_data`
Expand All @@ -17,7 +17,7 @@ class DelegatesDetails:

@classmethod
def from_chain_data(cls, data: dict[str, Any]) -> "DelegatesDetails":
def decode(key: str, default: Optional[str] = ""):
def decode(key: str, default: Union[Optional[str], list] = ""):
try:
if isinstance(data.get(key), dict):
value = next(data.get(key).values())
Expand Down
Loading
Loading