Skip to content

Commit 93b7b25

Browse files
author
Roman
committed
Merge branch 'staging-pre-merge-new-async' into tests/zyzniewski/e2e_templates_teardown
2 parents 3d632d1 + fa2b9a8 commit 93b7b25

File tree

5 files changed

+91
-89
lines changed

5 files changed

+91
-89
lines changed

bittensor/core/extrinsics/move_stake.py

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -289,13 +289,6 @@ def move_stake_extrinsic(
289289
"""
290290

291291
amount.set_unit(netuid=origin_netuid)
292-
# Verify ownership of origin hotkey
293-
origin_owner = subtensor.get_hotkey_owner(origin_hotkey)
294-
if origin_owner != wallet.coldkeypub.ss58_address:
295-
logging.error(
296-
f":cross_mark: [red]Failed[/red]: Origin hotkey: {origin_hotkey} does not belong to the coldkey owner: {wallet.coldkeypub.ss58_address}"
297-
)
298-
return False
299292

300293
# Check sufficient stake
301294
stake_in_origin, stake_in_destination = _get_stake_in_origin_and_dest(

bittensor/core/metagraph.py

Lines changed: 41 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
MetagraphInfoPool,
2020
MetagraphInfoParams,
2121
)
22-
22+
from bittensor.utils import determine_chain_endpoint_and_network
2323
from bittensor.utils.btlogging import logging
2424
from bittensor.utils.registration import torch, use_torch
2525
from bittensor.utils.weight_utils import (
@@ -42,6 +42,7 @@
4242

4343

4444
Tensor = Union["torch.nn.Parameter", NDArray]
45+
ROOT_TAO_STAKES_WEIGHT = 0.018
4546

4647

4748
METAGRAPH_STATE_DICT_NDARRAY_KEYS = [
@@ -142,26 +143,6 @@ def latest_block_path(dir_path: str) -> str:
142143
return latest_file_full_path
143144

144145

145-
def determine_chain_endpoint_and_network(network: str) -> tuple[str, str]:
146-
"""
147-
Determine the chain endpoint and network name from the passed arg
148-
149-
Args:
150-
network: The network name (e.g. 'finney', 'test') or
151-
chain endpoint (e.g. wss://entrypoint-finney.opentensor.ai:443)
152-
153-
Returns:
154-
(network name, chain endpoint)
155-
"""
156-
pathless_network = network[:-1] if network.endswith("/") else network
157-
if pathless_network in settings.NETWORK_MAP:
158-
return pathless_network, settings.NETWORK_MAP[pathless_network]
159-
elif pathless_network in settings.REVERSE_NETWORK_MAP:
160-
return settings.REVERSE_NETWORK_MAP[pathless_network], pathless_network
161-
else:
162-
return "unknown", network
163-
164-
165146
class MetagraphMixin(ABC):
166147
"""
167148
The metagraph class is a core component of the Bittensor network, representing the neural graph that forms the
@@ -258,6 +239,11 @@ class MetagraphMixin(ABC):
258239
_dtype_registry = {"int64": np.int64, "float32": np.float32, "bool": bool}
259240

260241
# metagraph_info fields
242+
name: str
243+
symbol: str
244+
network_registered_at: int
245+
num_uids: int
246+
max_uids: int
261247
identities: list[Optional["ChainIdentity"]]
262248
identity: Optional["SubnetIdentity"]
263249
pruning_score: list[float]
@@ -537,6 +523,15 @@ def __init__(
537523
538524
metagraph = Metagraph(netuid=123, network="finney", lite=True, sync=True)
539525
"""
526+
self.lite = lite
527+
self.subtensor = subtensor
528+
self.should_sync = sync
529+
self.netuid = netuid
530+
self.network, self.chain_endpoint = determine_chain_endpoint_and_network(
531+
network
532+
)
533+
self.neurons = []
534+
self.axons: list[AxonInfo] = []
540535

541536
def __str__(self) -> str:
542537
"""
@@ -937,6 +932,11 @@ def _apply_metagraph_info_mixin(self, metagraph_info: "MetagraphInfo"):
937932
metagraph_info (MetagraphInfo): An instance of the MetagraphInfo class containing the data to be applied to
938933
the current object.
939934
"""
935+
self.name = metagraph_info.name
936+
self.symbol = metagraph_info.symbol
937+
self.network_registered_at = metagraph_info.network_registered_at
938+
self.num_uids = metagraph_info.num_uids
939+
self.max_uids = metagraph_info.max_uids
940940
self.identities = metagraph_info.identities
941941
self.identity = metagraph_info.identity
942942
self.pruning_score = metagraph_info.pruning_score
@@ -1043,10 +1043,6 @@ def __init__(
10431043
"""
10441044
BaseClass.__init__(self)
10451045
MetagraphMixin.__init__(self, netuid, network, lite, sync, subtensor)
1046-
self.netuid = netuid
1047-
self.network, self.chain_endpoint = determine_chain_endpoint_and_network(
1048-
network
1049-
)
10501046
self._dtype_registry = {
10511047
"int64": torch.int64,
10521048
"float32": torch.float32,
@@ -1107,10 +1103,6 @@ def __init__(
11071103
self.uids = torch.nn.Parameter(
11081104
torch.tensor([], dtype=torch.int64), requires_grad=False
11091105
)
1110-
self.axons: list[AxonInfo] = []
1111-
self.neurons = []
1112-
self.subtensor = subtensor
1113-
self.should_sync = sync
11141106
self.alpha_stake = torch.nn.Parameter(
11151107
torch.tensor([], dtype=torch.float32), requires_grad=False
11161108
)
@@ -1239,9 +1231,6 @@ def __init__(
12391231
self.tao_stake: Tensor = np.array([], dtype=np.int64)
12401232
self.stake: Tensor = np.array([], dtype=np.int64)
12411233
self.total_stake: Tensor = np.array([], dtype=np.int64)
1242-
1243-
self.axons: list[AxonInfo] = []
1244-
self.neurons = []
12451234
self.subtensor = subtensor
12461235
self.should_sync = sync
12471236

@@ -1343,7 +1332,7 @@ async def __aexit__(self, exc_type, exc_val, exc_tb):
13431332
async def sync(
13441333
self,
13451334
block: Optional[int] = None,
1346-
lite: bool = True,
1335+
lite: Optional[bool] = None,
13471336
subtensor: Optional["AsyncSubtensor"] = None,
13481337
):
13491338
"""
@@ -1354,8 +1343,9 @@ async def sync(
13541343
Args:
13551344
block (Optional[int]): A specific block number to synchronize with. If None, the metagraph syncs with the
13561345
latest block. This allows for historical analysis or specific state examination of the network.
1357-
lite (bool): If True, a lite version of the metagraph is used for quicker synchronization. This is
1346+
lite (Optional[bool]): If True, a lite version of the metagraph is used for quicker synchronization. This is
13581347
beneficial when full detail is not necessary, allowing for reduced computational and time overhead.
1348+
Defaults to `True`.
13591349
subtensor (Optional[bittensor.core.subtensor.Subtensor]): An instance of the subtensor class from Bittensor,
13601350
providing an interface to the underlying blockchain data. If provided, this instance is used for data
13611351
retrieval during synchronization.
@@ -1390,6 +1380,9 @@ async def sync(
13901380
13911381
metagraph.sync(block=history_block, lite=False, subtensor=subtensor)
13921382
"""
1383+
if lite is None:
1384+
lite = self.lite
1385+
13931386
subtensor = await self._initialize_subtensor(subtensor)
13941387

13951388
if (
@@ -1608,8 +1601,14 @@ async def _get_all_stakes_from_chain(self):
16081601
)
16091602
return subnet_state
16101603

1611-
self.alpha_stake = subnet_state.alpha_stake
1612-
self.tao_stake = [b * 0.018 for b in subnet_state.tao_stake]
1604+
self.alpha_stake = self._create_tensor(
1605+
[b.tao for b in subnet_state.alpha_stake],
1606+
dtype=self._dtype_registry["float32"],
1607+
)
1608+
self.tao_stake = self._create_tensor(
1609+
[b.tao * ROOT_TAO_STAKES_WEIGHT for b in subnet_state.tao_stake],
1610+
dtype=self._dtype_registry["float32"],
1611+
)
16131612
self.total_stake = self.stake = self._create_tensor(
16141613
[stake.tao for stake in subnet_state.total_stake],
16151614
dtype=self._dtype_registry["float32"],
@@ -1641,7 +1640,7 @@ def __init__(
16411640
def sync(
16421641
self,
16431642
block: Optional[int] = None,
1644-
lite: bool = True,
1643+
lite: Optional[bool] = None,
16451644
subtensor: Optional["Subtensor"] = None,
16461645
):
16471646
"""
@@ -1652,8 +1651,9 @@ def sync(
16521651
Args:
16531652
block (Optional[int]): A specific block number to synchronize with. If None, the metagraph syncs with the
16541653
latest block. This allows for historical analysis or specific state examination of the network.
1655-
lite (bool): If True, a lite version of the metagraph is used for quicker synchronization. This is
1654+
lite (Optional[bool]): If True, a lite version of the metagraph is used for quicker synchronization. This is
16561655
beneficial when full detail is not necessary, allowing for reduced computational and time overhead.
1656+
Defaults to `True`.
16571657
subtensor (Optional[bittensor.core.subtensor.Subtensor]): An instance of the subtensor class from Bittensor,
16581658
providing an interface to the underlying blockchain data. If provided, this instance is used for data
16591659
retrieval during synchronization.
@@ -1688,6 +1688,8 @@ def sync(
16881688
16891689
metagraph.sync(block=history_block, lite=False, subtensor=subtensor)
16901690
"""
1691+
if lite is None:
1692+
lite = self.lite
16911693

16921694
# Initialize subtensor
16931695
subtensor = self._initialize_subtensor(subtensor=subtensor)
@@ -1908,7 +1910,7 @@ def _get_all_stakes_from_chain(self):
19081910
dtype=self._dtype_registry["float32"],
19091911
)
19101912
self.tao_stake = self._create_tensor(
1911-
[b.tao * 0.018 for b in subnet_state.tao_stake],
1913+
[b.tao * ROOT_TAO_STAKES_WEIGHT for b in subnet_state.tao_stake],
19121914
dtype=self._dtype_registry["float32"],
19131915
)
19141916
self.total_stake = self.stake = self._create_tensor(

bittensor/core/types.py

Lines changed: 3 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
from bittensor.core import settings
88
from bittensor.core.config import Config
99
from bittensor.core.chain_data import NeuronInfo, NeuronInfoLite
10+
from bittensor.utils import determine_chain_endpoint_and_network
1011

1112

1213
class SubtensorMixin(ABC):
@@ -95,8 +96,8 @@ def setup_config(network: Optional[str], config: "Config"):
9596
if check:
9697
network = config_network
9798

98-
evaluated_network, evaluated_endpoint = (
99-
SubtensorMixin.determine_chain_endpoint_and_network(network)
99+
evaluated_network, evaluated_endpoint = determine_chain_endpoint_and_network(
100+
network
100101
)
101102

102103
return networking.get_formatted_ws_endpoint_url(
@@ -166,41 +167,6 @@ def add_args(cls, parser: "argparse.ArgumentParser", prefix: Optional[str] = Non
166167
# re-parsing arguments.
167168
pass
168169

169-
@staticmethod
170-
def determine_chain_endpoint_and_network(
171-
network: str,
172-
) -> tuple[Optional[str], Optional[str]]:
173-
"""Determines the chain endpoint and network from the passed network or chain_endpoint.
174-
175-
Arguments:
176-
network (str): The network flag. The choices are: ``finney`` (main network), ``archive`` (archive network
177-
+300 blocks), ``local`` (local running network), ``test`` (test network).
178-
179-
Returns:
180-
tuple[Optional[str], Optional[str]]: The network and chain endpoint flag. If passed, overrides the
181-
``network`` argument.
182-
"""
183-
184-
if network is None:
185-
return None, None
186-
if network in settings.NETWORKS:
187-
return network, settings.NETWORK_MAP[network]
188-
189-
substrings_map = {
190-
"entrypoint-finney.opentensor.ai": ("finney", settings.FINNEY_ENTRYPOINT),
191-
"test.finney.opentensor.ai": ("test", settings.FINNEY_TEST_ENTRYPOINT),
192-
"archive.chain.opentensor.ai": ("archive", settings.ARCHIVE_ENTRYPOINT),
193-
"subvortex": ("subvortex", settings.SUBVORTEX_ENTRYPOINT),
194-
"127.0.0.1": ("local", settings.LOCAL_ENTRYPOINT),
195-
"localhost": ("local", settings.LOCAL_ENTRYPOINT),
196-
}
197-
198-
for substring, result in substrings_map.items():
199-
if substring in network:
200-
return result
201-
202-
return "unknown", network
203-
204170

205171
class AxonServeCallParams:
206172
def __init__(

bittensor/utils/__init__.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
from bittensor_wallet.errors import KeyFileError, PasswordError
1313
from scalecodec import ss58_decode, is_valid_ss58_address as _is_valid_ss58_address
1414

15+
from bittensor.core import settings
1516
from bittensor.core.settings import SS58_FORMAT
1617
from bittensor.utils.btlogging import logging
1718
from .registration import torch, use_torch
@@ -410,3 +411,38 @@ def unlock_key(wallet: "Wallet", unlock_type="coldkey") -> "UnlockStatus":
410411
except KeyFileError:
411412
err_msg = f"{unlock_type.capitalize()} keyfile is corrupt, non-writable, or non-readable, or non-existent."
412413
return UnlockStatus(False, err_msg)
414+
415+
416+
def determine_chain_endpoint_and_network(
417+
network: str,
418+
) -> tuple[Optional[str], Optional[str]]:
419+
"""Determines the chain endpoint and network from the passed network or chain_endpoint.
420+
421+
Arguments:
422+
network (str): The network flag. The choices are: ``finney`` (main network), ``archive`` (archive network
423+
+300 blocks), ``local`` (local running network), ``test`` (test network).
424+
425+
Returns:
426+
tuple[Optional[str], Optional[str]]: The network and chain endpoint flag. If passed, overrides the
427+
``network`` argument.
428+
"""
429+
430+
if network is None:
431+
return None, None
432+
if network in settings.NETWORKS:
433+
return network, settings.NETWORK_MAP[network]
434+
435+
substrings_map = {
436+
"entrypoint-finney.opentensor.ai": ("finney", settings.FINNEY_ENTRYPOINT),
437+
"test.finney.opentensor.ai": ("test", settings.FINNEY_TEST_ENTRYPOINT),
438+
"archive.chain.opentensor.ai": ("archive", settings.ARCHIVE_ENTRYPOINT),
439+
"subvortex": ("subvortex", settings.SUBVORTEX_ENTRYPOINT),
440+
"127.0.0.1": ("local", network),
441+
"localhost": ("local", network),
442+
}
443+
444+
for substring, result in substrings_map.items():
445+
if substring in network and validate_chain_endpoint(network):
446+
return result
447+
448+
return "unknown", network

tests/unit_tests/test_subtensor.py

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,12 @@
3434
from bittensor.core.settings import version_as_int
3535
from bittensor.core.subtensor import Subtensor
3636
from bittensor.core.types import AxonServeCallParams
37-
from bittensor.utils import Certificate, u16_normalized_float, u64_normalized_float
37+
from bittensor.utils import (
38+
Certificate,
39+
u16_normalized_float,
40+
u64_normalized_float,
41+
determine_chain_endpoint_and_network,
42+
)
3843
from bittensor.utils.balance import Balance
3944

4045
U16_MAX = 65535
@@ -269,8 +274,10 @@ def mock_add_argument(*args, **kwargs):
269274
"archive",
270275
settings.ARCHIVE_ENTRYPOINT,
271276
),
272-
("127.0.0.1", "local", settings.LOCAL_ENTRYPOINT),
273-
("localhost", "local", settings.LOCAL_ENTRYPOINT),
277+
("127.0.0.1", "local", "127.0.0.1"),
278+
("localhost", "local", "localhost"),
279+
("ws://127.0.0.1:9945", "local", "ws://127.0.0.1:9945"),
280+
("ws://localhost:9945", "local", "ws://localhost:9945"),
274281
# Edge cases
275282
(None, None, None),
276283
("unknown", "unknown", "unknown"),
@@ -280,9 +287,7 @@ def test_determine_chain_endpoint_and_network(
280287
network, expected_network, expected_endpoint
281288
):
282289
# Act
283-
result_network, result_endpoint = Subtensor.determine_chain_endpoint_and_network(
284-
network
285-
)
290+
result_network, result_endpoint = determine_chain_endpoint_and_network(network)
286291

287292
# Assert
288293
assert result_network == expected_network

0 commit comments

Comments
 (0)