Skip to content

Commit f5483a8

Browse files
authored
Merge pull request #2619 from opentensor/feat/roman/improvement
Many small fixes
2 parents cfe3882 + 3c3f862 commit f5483a8

File tree

11 files changed

+75
-97
lines changed

11 files changed

+75
-97
lines changed

bittensor/core/async_subtensor.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@
8989
from bittensor_wallet import Wallet
9090
from bittensor.core.axon import Axon
9191
from bittensor.utils import Certificate
92-
from async_substrate_interface import QueryMapResult
92+
from async_substrate_interface import AsyncQueryMapResult
9393

9494

9595
class AsyncSubtensor(SubtensorMixin):
@@ -316,7 +316,7 @@ async def query_map(
316316
block_hash: Optional[str] = None,
317317
reuse_block: bool = False,
318318
params: Optional[list] = None,
319-
) -> "QueryMapResult":
319+
) -> "AsyncQueryMapResult":
320320
"""
321321
Queries map storage from any module on the Bittensor blockchain. This function retrieves data structures that
322322
represent key-value mappings, essential for accessing complex and structured data within the blockchain
@@ -354,7 +354,7 @@ async def query_map_subtensor(
354354
block_hash: Optional[str] = None,
355355
reuse_block: bool = False,
356356
params: Optional[list] = None,
357-
) -> "QueryMapResult":
357+
) -> "AsyncQueryMapResult":
358358
"""
359359
Queries map storage from the Subtensor module on the Bittensor blockchain. This function is designed to retrieve
360360
a map-like data structure, which can include various neuron-specific details or network-wide attributes.
@@ -1380,7 +1380,7 @@ async def get_all_metagraphs_info(
13801380
Returns:
13811381
MetagraphInfo dataclass
13821382
"""
1383-
block_hash = await self.determine_block_hash(block, block_hash.reuse_block)
1383+
block_hash = await self.determine_block_hash(block, block_hash, reuse_block)
13841384
if not block_hash and reuse_block:
13851385
block_hash = self.substrate.last_block_hash
13861386
query = await self.substrate.runtime_call(
@@ -2019,7 +2019,7 @@ async def get_vote_data(
20192019
network, particularly how proposals are received and acted upon by the governing body.
20202020
"""
20212021
block_hash = await self.determine_block_hash(block, block_hash, reuse_block)
2022-
vote_data = await self.substrate.query(
2022+
vote_data: dict[str, Any] = await self.substrate.query(
20232023
module="Triumvirate",
20242024
storage_function="Voting",
20252025
params=[proposal_hash],
@@ -2598,7 +2598,7 @@ async def subnet(
25982598
params=[netuid],
25992599
block_hash=block_hash,
26002600
)
2601-
subnet = DynamicInfo.from_vec_u8(bytes.fromhex(query.decode()[2:]))
2601+
subnet = DynamicInfo.from_vec_u8(hex_to_bytes(query.decode()))
26022602
return subnet
26032603

26042604
async def subnet_exists(

bittensor/core/chain_data/dynamic_info.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ class DynamicInfo:
4343
subnet_identity: Optional[SubnetIdentity]
4444

4545
@classmethod
46-
def from_vec_u8(cls, vec_u8: list[int]) -> Optional["DynamicInfo"]:
46+
def from_vec_u8(cls, vec_u8: Union[list[int], bytes]) -> Optional["DynamicInfo"]:
4747
if len(vec_u8) == 0:
4848
return None
4949
decoded = from_scale_encoding(vec_u8, ChainDataType.DynamicInfo)
@@ -154,8 +154,11 @@ def tao_to_alpha_with_slippage(
154154
) -> Union[tuple[Balance, Balance], float]:
155155
"""
156156
Returns an estimate of how much Alpha would a staker receive if they stake their tao using the current pool state.
157-
Args:
157+
158+
Arguments:
158159
tao: Amount of TAO to stake.
160+
percentage: percentage
161+
159162
Returns:
160163
If percentage is False, a tuple of balances where the first part is the amount of Alpha received, and the
161164
second part (slippage) is the difference between the estimated amount and ideal
@@ -206,8 +209,11 @@ def alpha_to_tao_with_slippage(
206209
) -> Union[tuple[Balance, Balance], float]:
207210
"""
208211
Returns an estimate of how much TAO would a staker receive if they unstake their alpha using the current pool state.
212+
209213
Args:
210214
alpha: Amount of Alpha to stake.
215+
percentage: percentage
216+
211217
Returns:
212218
If percentage is False, a tuple of balances where the first part is the amount of TAO received, and the
213219
second part (slippage) is the difference between the estimated amount and ideal

bittensor/core/chain_data/stake_info.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
from dataclasses import dataclass
2-
from typing import Optional, Any
2+
from typing import Any, Optional, Union
33

44
from scalecodec.utils.ss58 import ss58_encode
55

@@ -81,7 +81,7 @@ def list_of_tuple_from_vec_u8(
8181
}
8282

8383
@classmethod
84-
def list_from_vec_u8(cls, vec_u8: list[int]) -> list["StakeInfo"]:
84+
def list_from_vec_u8(cls, vec_u8: Union[list[int], bytes]) -> list["StakeInfo"]:
8585
"""Returns a list of StakeInfo objects from a ``vec_u8``."""
8686
decoded = from_scale_encoding(vec_u8, ChainDataType.StakeInfo, is_vec=True)
8787
if decoded is None:

bittensor/core/metagraph.py

Lines changed: 9 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import copy
2-
import importlib
32
import os
43
import pickle
54
import typing
@@ -764,7 +763,7 @@ def _set_metagraph_attributes(self, block: int):
764763
)
765764
self.axons = [n.axon_info for n in self.neurons]
766765

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

1025-
def load_from_path(self, dir_path: str) -> "AsyncMetagraph":
1024+
def load_from_path(self, dir_path: str) -> "MetagraphMixin":
10261025
"""
10271026
Loads the metagraph state from a specified directory path.
10281027
@@ -1152,7 +1151,7 @@ def __init__(
11521151
self.axons: list["AxonInfo"] = []
11531152
self.total_stake: list["Balance"] = []
11541153

1155-
def load_from_path(self, dir_path: str) -> "AsyncMetagraph":
1154+
def load_from_path(self, dir_path: str) -> "MetagraphMixin":
11561155
"""
11571156
Loads the state of the Metagraph from a specified directory path.
11581157
@@ -1356,10 +1355,7 @@ async def _initialize_subtensor(
13561355
subtensor = self.subtensor
13571356
if not subtensor:
13581357
# Lazy import due to circular import (subtensor -> metagraph, metagraph -> subtensor)
1359-
AsyncSubtensor = getattr(
1360-
importlib.import_module("bittensor.core.async_subtensor"),
1361-
"AsyncSubtensor",
1362-
)
1358+
from bittensor.core.async_subtensor import AsyncSubtensor
13631359

13641360
async with AsyncSubtensor(network=self.chain_endpoint) as subtensor:
13651361
self.subtensor = subtensor
@@ -1592,7 +1588,7 @@ def sync(
15921588
"""
15931589

15941590
# Initialize subtensor
1595-
subtensor = self._initialize_subtensor(subtensor)
1591+
subtensor = self._initialize_subtensor(subtensor=subtensor)
15961592

15971593
if (
15981594
subtensor.chain_endpoint != settings.ARCHIVE_ENTRYPOINT
@@ -1632,11 +1628,11 @@ def _initialize_subtensor(self, subtensor: "Subtensor") -> "Subtensor":
16321628
according to the current network settings.
16331629
16341630
Args:
1635-
subtensor (bittensor.core.async_subtensor.AsyncSubtensor): The subtensor instance provided for
1631+
subtensor (bittensor.core.subtensor.Subtensor): The subtensor instance provided for
16361632
initialization. If ``None``, a new subtensor instance is created using the current network configuration.
16371633
16381634
Returns:
1639-
subtensor (bittensor.core.async_subtensor.AsyncSubtensor): The initialized subtensor instance, ready to be
1635+
subtensor (bittensor.core.subtensor.Subtensor): The initialized subtensor instance, ready to be
16401636
used for syncing the metagraph.
16411637
16421638
Internal Usage:
@@ -1650,9 +1646,8 @@ def _initialize_subtensor(self, subtensor: "Subtensor") -> "Subtensor":
16501646
subtensor = self.subtensor
16511647
if not subtensor:
16521648
# Lazy import due to circular import (subtensor -> metagraph, metagraph -> subtensor)
1653-
Subtensor = getattr(
1654-
importlib.import_module("bittensor.core.subtensor"), "Subtensor"
1655-
)
1649+
from bittensor.core.subtensor import Subtensor
1650+
16561651
subtensor = Subtensor(network=self.chain_endpoint)
16571652

16581653
self.subtensor = subtensor

bittensor/core/subtensor.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1181,7 +1181,7 @@ def get_stake(
11811181
block=block,
11821182
params=[hotkey_ss58, coldkey_ss58, netuid],
11831183
)
1184-
hotkey_alpha_obj: ScaleType = self.query_module(
1184+
hotkey_alpha_obj: ScaleObj = self.query_module(
11851185
module="SubtensorModule",
11861186
name="TotalHotkeyAlpha",
11871187
block=block,
@@ -1541,7 +1541,7 @@ def get_vote_data(
15411541
This function is important for tracking and understanding the decision-making processes within the Bittensor
15421542
network, particularly how proposals are received and acted upon by the governing body.
15431543
"""
1544-
vote_data = self.substrate.query(
1544+
vote_data: dict[str, Any] = self.substrate.query(
15451545
module="Triumvirate",
15461546
storage_function="Voting",
15471547
params=[proposal_hash],
@@ -2180,6 +2180,7 @@ def add_stake(
21802180
Args:
21812181
wallet (bittensor_wallet.Wallet): The wallet to be used for staking.
21822182
hotkey_ss58 (Optional[str]): The ``SS58`` address of the hotkey associated with the neuron.
2183+
netuid (Optional[int]): The unique identifier of the subnet to which the neuron belongs.
21832184
amount (Balance): The amount of TAO to stake.
21842185
wait_for_inclusion (bool): Waits for the transaction to be included in a block.
21852186
wait_for_finalization (bool): Waits for the transaction to be finalized on the blockchain.
@@ -2217,6 +2218,7 @@ def add_stake_multiple(
22172218
Args:
22182219
wallet (bittensor_wallet.Wallet): The wallet used for staking.
22192220
hotkey_ss58s (list[str]): List of ``SS58`` addresses of hotkeys to stake to.
2221+
netuids (list[int]): List of network UIDs to stake to.
22202222
amounts (list[Balance]): Corresponding amounts of TAO to stake for each hotkey.
22212223
wait_for_inclusion (bool): Waits for the transaction to be included in a block.
22222224
wait_for_finalization (bool): Waits for the transaction to be finalized on the blockchain.
@@ -2637,6 +2639,7 @@ def _blocks_weight_limit() -> bool:
26372639

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

26482651
if self.commit_reveal_enabled(netuid=netuid) is True:
26492652
# go with `commit reveal v3` extrinsic
2650-
message = "No attempt made. Perhaps it is too soon to commit weights!"
2653+
26512654
while retries < max_retries and success is False and _blocks_weight_limit():
26522655
logging.info(
26532656
f"Committing weights for subnet #{netuid}. Attempt {retries + 1} of {max_retries}."
@@ -2666,7 +2669,7 @@ def _blocks_weight_limit() -> bool:
26662669
return success, message
26672670
else:
26682671
# go with classic `set weights extrinsic`
2669-
message = "No attempt made. Perhaps it is too soon to set weights!"
2672+
26702673
while retries < max_retries and success is False and _blocks_weight_limit():
26712674
try:
26722675
logging.info(

bittensor/core/types.py

Lines changed: 0 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -202,17 +202,6 @@ def determine_chain_endpoint_and_network(
202202
return "unknown", network
203203

204204

205-
class AxonServeCallParams_(TypedDict):
206-
"""Axon serve chain call parameters."""
207-
208-
version: int
209-
ip: int
210-
port: int
211-
ip_type: int
212-
netuid: int
213-
certificate: Optional[Certificate]
214-
215-
216205
class AxonServeCallParams:
217206
def __init__(
218207
self,

bittensor/utils/__init__.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -239,7 +239,6 @@ def format_error_message(error_message: Union[dict, Exception]) -> str:
239239
return f"Subtensor returned `{err_name}({err_type})` error. This means: `{err_description}`."
240240

241241

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

342-
def get_decoded(data: str) -> str:
341+
def get_decoded(data: str) -> Optional[str]:
343342
"""Decodes a hex-encoded string."""
344343
try:
345344
return bytes.fromhex(data[2:]).decode()

bittensor/utils/balance.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import warnings
2-
32
from typing import Union, TypedDict, Optional
43

54
from scalecodec import ScaleType

bittensor/utils/delegates_details.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
from dataclasses import dataclass
2-
from typing import Any, Optional
2+
from typing import Any, Optional, Union
33

44

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

1818
@classmethod
1919
def from_chain_data(cls, data: dict[str, Any]) -> "DelegatesDetails":
20-
def decode(key: str, default: Optional[str] = ""):
20+
def decode(key: str, default: Union[Optional[str], list] = ""):
2121
try:
2222
if isinstance(data.get(key), dict):
2323
value = next(data.get(key).values())

0 commit comments

Comments
 (0)