Skip to content

Commit 080e418

Browse files
authored
Merge pull request #2856 from opentensor/feat/roman/cleanup
Cleanup, refactoring, small fix, improvement
2 parents 62b2aa7 + c73c4ac commit 080e418

File tree

6 files changed

+51
-130
lines changed

6 files changed

+51
-130
lines changed

bittensor/core/async_subtensor.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -58,12 +58,12 @@
5858
publish_metadata,
5959
get_metadata,
6060
)
61-
from bittensor.core.extrinsics.asyncex.start_call import start_call_extrinsic
6261
from bittensor.core.extrinsics.asyncex.serving import serve_axon_extrinsic
6362
from bittensor.core.extrinsics.asyncex.staking import (
6463
add_stake_extrinsic,
6564
add_stake_multiple_extrinsic,
6665
)
66+
from bittensor.core.extrinsics.asyncex.start_call import start_call_extrinsic
6767
from bittensor.core.extrinsics.asyncex.take import (
6868
decrease_take_extrinsic,
6969
increase_take_extrinsic,
@@ -135,7 +135,6 @@ def __init__(
135135
self.chain_endpoint, self.network = AsyncSubtensor.setup_config(
136136
network, self._config
137137
)
138-
self._mock = _mock
139138

140139
self.log_verbose = log_verbose
141140
self._check_and_log_network_settings()
@@ -229,7 +228,7 @@ async def encode_params(
229228
call_definition: dict[str, list["ParamWithTypes"]],
230229
params: Union[list[Any], dict[str, Any]],
231230
) -> str:
232-
"""Returns a hex encoded string of the params using their types."""
231+
"""Returns a hex-encoded string of the params using their types."""
233232
param_data = scalecodec.ScaleBytes(b"")
234233

235234
for i, param in enumerate(call_definition["params"]):

bittensor/core/extrinsics/utils.py

Lines changed: 5 additions & 92 deletions
Original file line numberDiff line numberDiff line change
@@ -2,106 +2,19 @@
22

33
from typing import TYPE_CHECKING
44

5-
from async_substrate_interface.errors import SubstrateRequestException
6-
7-
from bittensor.utils import format_error_message
85
from bittensor.utils.balance import Balance
9-
from bittensor.utils.btlogging import logging
106

117
if TYPE_CHECKING:
128
from bittensor_wallet import Wallet
13-
from bittensor.core.async_subtensor import AsyncSubtensor
14-
from async_substrate_interface import (
15-
AsyncExtrinsicReceipt,
16-
ExtrinsicReceipt,
17-
)
18-
from bittensor.core.subtensor import Subtensor
199
from bittensor.core.chain_data import StakeInfo
20-
from scalecodec.types import GenericExtrinsic
21-
22-
23-
def submit_extrinsic(
24-
subtensor: "Subtensor",
25-
extrinsic: "GenericExtrinsic",
26-
wait_for_inclusion: bool,
27-
wait_for_finalization: bool,
28-
) -> "ExtrinsicReceipt":
29-
"""
30-
Submits an extrinsic to the substrate blockchain and handles potential exceptions.
31-
32-
This function attempts to submit an extrinsic to the substrate blockchain with specified options
33-
for waiting for inclusion in a block and/or finalization. If an exception occurs during submission,
34-
it logs the error and re-raises the exception.
35-
36-
Args:
37-
subtensor: The Subtensor instance used to interact with the blockchain.
38-
extrinsic (scalecodec.types.GenericExtrinsic): The extrinsic to be submitted to the blockchain.
39-
wait_for_inclusion (bool): Whether to wait for the extrinsic to be included in a block.
40-
wait_for_finalization (bool): Whether to wait for the extrinsic to be finalized on the blockchain.
41-
42-
Returns:
43-
response: The response from the substrate after submitting the extrinsic.
44-
45-
Raises:
46-
SubstrateRequestException: If the submission of the extrinsic fails, the error is logged and re-raised.
47-
"""
48-
try:
49-
return subtensor.substrate.submit_extrinsic(
50-
extrinsic,
51-
wait_for_inclusion=wait_for_inclusion,
52-
wait_for_finalization=wait_for_finalization,
53-
)
54-
except SubstrateRequestException as e:
55-
logging.error(format_error_message(e.args[0]))
56-
# Re-raise the exception for retrying of the extrinsic call. If we remove the retry logic,
57-
# the raise will need to be removed.
58-
raise
59-
60-
61-
async def async_submit_extrinsic(
62-
subtensor: "AsyncSubtensor",
63-
extrinsic: "GenericExtrinsic",
64-
wait_for_inclusion: bool,
65-
wait_for_finalization: bool,
66-
) -> "AsyncExtrinsicReceipt":
67-
"""
68-
Submits an extrinsic to the substrate blockchain and handles potential exceptions.
69-
70-
This function attempts to submit an extrinsic to the substrate blockchain with specified options
71-
for waiting for inclusion in a block and/or finalization. If an exception occurs during submission,
72-
it logs the error and re-raises the exception.
73-
74-
Args:
75-
subtensor: The AsyncSubtensor instance used to interact with the blockchain.
76-
extrinsic: The extrinsic to be submitted to the blockchain.
77-
wait_for_inclusion: Whether to wait for the extrinsic to be included in a block.
78-
wait_for_finalization: Whether to wait for the extrinsic to be finalized on the blockchain.
79-
80-
Returns:
81-
response: The response from the substrate after submitting the extrinsic.
82-
83-
Raises:
84-
SubstrateRequestException: If the submission of the extrinsic fails, the error is logged and re-raised.
85-
"""
86-
try:
87-
return await subtensor.substrate.submit_extrinsic(
88-
extrinsic,
89-
wait_for_inclusion=wait_for_inclusion,
90-
wait_for_finalization=wait_for_finalization,
91-
)
92-
except SubstrateRequestException as e:
93-
logging.error(format_error_message(e.args[0]))
94-
# Re-raise the exception for retrying of the extrinsic call. If we remove the retry logic,
95-
# the raise will need to be removed.
96-
raise
9710

9811

9912
def get_old_stakes(
10013
wallet: "Wallet",
10114
hotkey_ss58s: list[str],
10215
netuids: list[int],
10316
all_stakes: list["StakeInfo"],
104-
) -> list[Balance]:
17+
) -> list["Balance"]:
10518
"""
10619
Retrieve the previous staking balances for a wallet's hotkeys across given netuids.
10720
@@ -110,10 +23,10 @@ def get_old_stakes(
11023
is found for a particular hotkey and netuid combination, a default balance of zero is returned.
11124
11225
Args:
113-
wallet (Wallet): The wallet containing the coldkey to compare with stake data.
114-
hotkey_ss58s (list[str]): List of hotkey SS58 addresses for which stakes are retrieved.
115-
netuids (list[int]): List of network unique identifiers (netuids) corresponding to the hotkeys.
116-
all_stakes (list[StakeInfo]): A collection of all staking information to search through.
26+
wallet: The wallet containing the coldkey to compare with stake data.
27+
hotkey_ss58s: List of hotkey SS58 addresses for which stakes are retrieved.
28+
netuids: List of network unique identifiers (netuids) corresponding to the hotkeys.
29+
all_stakes: A collection of all staking information to search through.
11730
11831
Returns:
11932
list[Balance]: A list of Balances, each representing the stake for a given hotkey and netuid.

bittensor/core/subtensor.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -61,12 +61,12 @@
6161
get_metadata,
6262
serve_axon_extrinsic,
6363
)
64-
from bittensor.core.extrinsics.start_call import start_call_extrinsic
6564
from bittensor.core.extrinsics.set_weights import set_weights_extrinsic
6665
from bittensor.core.extrinsics.staking import (
6766
add_stake_extrinsic,
6867
add_stake_multiple_extrinsic,
6968
)
69+
from bittensor.core.extrinsics.start_call import start_call_extrinsic
7070
from bittensor.core.extrinsics.take import (
7171
decrease_take_extrinsic,
7272
increase_take_extrinsic,
@@ -110,7 +110,7 @@
110110

111111

112112
class Subtensor(SubtensorMixin):
113-
"""Thin layer for interacting with Substrate Interface. Mostly a collection of frequently-used calls."""
113+
"""Thin layer for interacting with Substrate Interface. Mostly a collection of frequently used calls."""
114114

115115
def __init__(
116116
self,
@@ -135,7 +135,6 @@ def __init__(
135135
config = self.config()
136136
self._config = copy.deepcopy(config)
137137
self.chain_endpoint, self.network = self.setup_config(network, self._config)
138-
self._mock = _mock
139138

140139
self.log_verbose = log_verbose
141140
self._check_and_log_network_settings()

bittensor/utils/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -248,7 +248,7 @@ def format_error_message(error_message: Union[dict, Exception]) -> str:
248248
err_type = error_message.get("type", err_type)
249249
err_name = error_message.get("name", err_name)
250250
err_docs = error_message.get("docs", [err_description])
251-
err_description = err_docs[0] if err_docs else err_description
251+
err_description = " ".join(err_docs)
252252

253253
elif error_message.get("code") and error_message.get("message"):
254254
err_type = error_message.get("code", err_name)

tests/unit_tests/extrinsics/test__init__.py

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,26 +4,31 @@
44

55

66
def test_format_error_message_with_right_error_message():
7-
"""Verify that error message from extrinsic response parses correctly."""
7+
"""Verify that an error message from extrinsic response parses correctly."""
88
# Prep
99
fake_error_message = {
1010
"type": "SomeType",
1111
"name": "SomeErrorName",
12-
"docs": ["Some error description."],
12+
"docs": [
13+
"Some error description.",
14+
"I'm second part.",
15+
"Hah, I'm the last one.",
16+
],
1317
}
1418

1519
# Call
1620
result = format_error_message(fake_error_message)
1721

1822
# Assertions
1923

20-
assert "SomeType" in result
21-
assert "SomeErrorName" in result
22-
assert "Some error description." in result
24+
assert (
25+
result
26+
== "Subtensor returned `SomeErrorName(SomeType)` error. This means: `Some error description. I'm second part. Hah, I'm the last one.`."
27+
)
2328

2429

2530
def test_format_error_message_with_empty_error_message():
26-
"""Verify that empty error message from extrinsic response parses correctly."""
31+
"""Verify that an empty error message from extrinsic response parses correctly."""
2732
# Prep
2833
fake_error_message = {}
2934

Lines changed: 30 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,31 @@
1-
from unittest.mock import MagicMock
2-
3-
import pytest
4-
from scalecodec.types import GenericExtrinsic
5-
1+
from bittensor.core.chain_data import StakeInfo
62
from bittensor.core.extrinsics import utils
7-
from bittensor.core.subtensor import Subtensor
8-
9-
10-
@pytest.fixture
11-
def mock_subtensor(mock_substrate):
12-
mock_subtensor = MagicMock(autospec=Subtensor)
13-
mock_subtensor.substrate = mock_substrate
14-
yield mock_subtensor
15-
16-
17-
@pytest.fixture
18-
def starting_block():
19-
yield {"header": {"number": 1, "hash": "0x0100"}}
20-
21-
22-
def test_submit_extrinsic_success(mock_subtensor):
23-
mock_subtensor.substrate.submit_extrinsic.return_value = True
24-
mock_extrinsic = MagicMock(autospec=GenericExtrinsic)
25-
result = utils.submit_extrinsic(mock_subtensor, mock_extrinsic, True, True)
26-
assert result is True
3+
from bittensor.utils.balance import Balance
4+
5+
6+
def test_old_stake(subtensor, mocker):
7+
wallet = mocker.Mock(
8+
hotkey=mocker.Mock(ss58_address="HK1"),
9+
coldkeypub=mocker.Mock(ss58_address="CK1"),
10+
)
11+
12+
expected_stake = Balance.from_tao(100)
13+
14+
hotkey_ss58s = ["HK1", "HK2"]
15+
netuids = [3, 4]
16+
all_stakes = [
17+
StakeInfo(
18+
hotkey_ss58="HK1",
19+
coldkey_ss58="CK1",
20+
netuid=3,
21+
stake=expected_stake,
22+
locked=Balance.from_tao(10),
23+
emission=Balance.from_tao(1),
24+
drain=0,
25+
is_registered=True,
26+
),
27+
]
28+
29+
result = utils.get_old_stakes(wallet, hotkey_ss58s, netuids, all_stakes)
30+
31+
assert result == [expected_stake, Balance.from_tao(0)]

0 commit comments

Comments
 (0)