Skip to content

Commit 9cf7abd

Browse files
authored
Merge pull request #381 from opentensor/fix/thewhaleking/name-shadowing
Code Cleanup
2 parents d63e404 + 0c5bcf5 commit 9cf7abd

File tree

13 files changed

+192
-347
lines changed

13 files changed

+192
-347
lines changed

bittensor_cli/src/bittensor/chain_data.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -745,7 +745,9 @@ def tao_to_alpha(self, tao: Balance) -> Balance:
745745
def alpha_to_tao(self, alpha: Balance) -> Balance:
746746
return Balance.from_tao(alpha.tao * self.price.tao)
747747

748-
def tao_to_alpha_with_slippage(self, tao: Balance) -> tuple[Balance, Balance]:
748+
def tao_to_alpha_with_slippage(
749+
self, tao: Balance
750+
) -> tuple[Balance, Balance, float]:
749751
"""
750752
Returns an estimate of how much Alpha would a staker receive if they stake their tao using the current pool state.
751753
Args:

bittensor_cli/src/bittensor/subtensor_interface.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -217,7 +217,7 @@ async def get_stake_for_coldkey(
217217

218218
if result is None:
219219
return []
220-
stakes = StakeInfo.list_from_any(result)
220+
stakes: list[StakeInfo] = StakeInfo.list_from_any(result)
221221
return [stake for stake in stakes if stake.stake > 0]
222222

223223
async def get_stake_for_coldkey_and_hotkey(
@@ -362,14 +362,12 @@ async def get_total_stake_for_coldkey(
362362
self,
363363
*ss58_addresses,
364364
block_hash: Optional[str] = None,
365-
reuse_block: bool = False,
366365
) -> dict[str, tuple[Balance, Balance]]:
367366
"""
368367
Returns the total stake held on a coldkey.
369368
370369
:param ss58_addresses: The SS58 address(es) of the coldkey(s)
371370
:param block_hash: The hash of the block number to retrieve the stake from.
372-
:param reuse_block: Whether to reuse the last-used block hash when retrieving info.
373371
374372
:return: {address: Balance objects}
375373
"""

bittensor_cli/src/bittensor/utils.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
import sqlite3
66
import platform
77
import webbrowser
8-
import sys
98
from pathlib import Path
109
from typing import TYPE_CHECKING, Any, Collection, Optional, Union, Callable
1110
from urllib.parse import urlparse
@@ -73,8 +72,8 @@ def coldkeypub(self):
7372
return self._coldkeypub
7473

7574

76-
def print_console(message: str, colour: str, title: str, console: Console):
77-
console.print(
75+
def print_console(message: str, colour: str, title: str, console_: Console):
76+
console_.print(
7877
f"[bold {colour}][{title}]:[/bold {colour}] [{colour}]{message}[/{colour}]\n"
7978
)
8079

Lines changed: 0 additions & 154 deletions
Original file line numberDiff line numberDiff line change
@@ -1,154 +0,0 @@
1-
from typing import Optional, TYPE_CHECKING
2-
3-
import rich.prompt
4-
from rich.table import Table
5-
6-
from bittensor_cli.src.bittensor.chain_data import DelegateInfoLite
7-
from bittensor_cli.src.bittensor.utils import console
8-
9-
if TYPE_CHECKING:
10-
from bittensor_cli.src.bittensor.subtensor_interface import SubtensorInterface
11-
12-
13-
async def select_delegate(subtensor: "SubtensorInterface", netuid: int):
14-
# Get a list of delegates and sort them by total stake in descending order
15-
delegates: list[DelegateInfoLite] = (
16-
await subtensor.get_delegates_by_netuid_light(netuid)
17-
).sort(key=lambda x: x.total_stake, reverse=True)
18-
19-
# Get registered delegates details.
20-
registered_delegate_info = await subtensor.get_delegate_identities()
21-
22-
# Create a table to display delegate information
23-
table = Table(
24-
show_header=True,
25-
header_style="bold",
26-
border_style="rgb(7,54,66)",
27-
style="rgb(0,43,54)",
28-
)
29-
30-
# Add columns to the table with specific styles
31-
table.add_column("Index", style="rgb(253,246,227)", no_wrap=True)
32-
table.add_column("Delegate Name", no_wrap=True)
33-
table.add_column("Hotkey SS58", style="rgb(211,54,130)", no_wrap=True)
34-
table.add_column("Owner SS58", style="rgb(133,153,0)", no_wrap=True)
35-
table.add_column("Take", style="rgb(181,137,0)", no_wrap=True)
36-
table.add_column(
37-
"Total Stake", style="rgb(38,139,210)", no_wrap=True, justify="right"
38-
)
39-
table.add_column(
40-
"Owner Stake", style="rgb(220,50,47)", no_wrap=True, justify="right"
41-
)
42-
# table.add_column("Return per 1000", style="rgb(108,113,196)", no_wrap=True, justify="right")
43-
# table.add_column("Total Daily Return", style="rgb(42,161,152)", no_wrap=True, justify="right")
44-
45-
# List to store visible delegates
46-
visible_delegates = []
47-
48-
def get_user_input() -> str:
49-
return rich.prompt.Prompt.ask(
50-
'Press Enter to scroll, enter a number (1-N) to select, or type "h" for help: ',
51-
choices=["", "h"] + [str(x) for x in range(1, len(delegates) - 1)],
52-
show_choices=True,
53-
)
54-
55-
# TODO: Add pagination to handle large number of delegates more efficiently
56-
# Iterate through delegates and display their information
57-
58-
def loop_selections() -> Optional[int]:
59-
idx = 0
60-
selected_idx = None
61-
while idx < len(delegates):
62-
if idx < len(delegates):
63-
delegate = delegates[idx]
64-
65-
# Add delegate to visible list
66-
visible_delegates.append(delegate)
67-
68-
# Add a row to the table with delegate information
69-
table.add_row(
70-
str(idx),
71-
registered_delegate_info[delegate.hotkey_ss58].name
72-
if delegate.hotkey_ss58 in registered_delegate_info
73-
else "",
74-
delegate.hotkey_ss58[:5]
75-
+ "..."
76-
+ delegate.hotkey_ss58[-5:], # Show truncated hotkey
77-
delegate.owner_ss58[:5]
78-
+ "..."
79-
+ delegate.owner_ss58[-5:], # Show truncated owner address
80-
f"{delegate.take:.6f}",
81-
f"τ{delegate.total_stake.tao:,.4f}",
82-
f"τ{delegate.owner_stake.tao:,.4f}",
83-
# f"τ{delegate.return_per_1000.tao:,.4f}",
84-
# f"τ{delegate.total_daily_return.tao:,.4f}",
85-
)
86-
87-
# Clear console and print updated table
88-
console.clear()
89-
console.print(table)
90-
91-
# Prompt user for input
92-
user_input: str = get_user_input()
93-
94-
# Add a help option to display information about each column
95-
if user_input == "h":
96-
console.print("\nColumn Information:")
97-
console.print(
98-
"[rgb(253,246,227)]Index:[/rgb(253,246,227)] Position in the list of delegates"
99-
)
100-
console.print(
101-
"[rgb(211,54,130)]Hotkey SS58:[/rgb(211,54,130)] Truncated public key of the delegate's hotkey"
102-
)
103-
console.print(
104-
"[rgb(133,153,0)]Owner SS58:[/rgb(133,153,0)] Truncated public key of the delegate's owner"
105-
)
106-
console.print(
107-
"[rgb(181,137,0)]Take:[/rgb(181,137,0)] Percentage of rewards the delegate takes"
108-
)
109-
console.print(
110-
"[rgb(38,139,210)]Total Stake:[/rgb(38,139,210)] Total amount staked to this delegate"
111-
)
112-
console.print(
113-
"[rgb(220,50,47)]Owner Stake:[/rgb(220,50,47)] Amount staked by the delegate owner"
114-
)
115-
console.print(
116-
"[rgb(108,113,196)]Return per 1000:[/rgb(108,113,196)] Estimated return for 1000 Tao staked"
117-
)
118-
console.print(
119-
"[rgb(42,161,152)]Total Daily Return:[/rgb(42,161,152)] Estimated total daily return for all stake"
120-
)
121-
user_input = get_user_input()
122-
123-
# If user presses Enter, continue to next delegate
124-
if user_input and user_input != "h":
125-
selected_idx = int(user_input)
126-
break
127-
128-
if idx < len(delegates):
129-
idx += 1
130-
131-
return selected_idx
132-
133-
# TODO( const ): uncomment for check
134-
# Add a confirmation step before returning the selected delegate
135-
# console.print(f"\nSelected delegate: [rgb(211,54,130)]{visible_delegates[selected_idx].hotkey_ss58}[/rgb(211,54,130)]")
136-
# console.print(f"Take: [rgb(181,137,0)]{visible_delegates[selected_idx].take:.6f}[/rgb(181,137,0)]")
137-
# console.print(f"Total Stake: [rgb(38,139,210)]{visible_delegates[selected_idx].total_stake}[/rgb(38,139,210)]")
138-
139-
# confirmation = Prompt.ask("Do you want to proceed with this delegate? (y/n)")
140-
# if confirmation.lower() != 'yes' and confirmation.lower() != 'y':
141-
# return select_delegate( subtensor, netuid )
142-
143-
# Return the selected delegate
144-
while True:
145-
selected_idx_ = loop_selections()
146-
if selected_idx_ is None:
147-
if not rich.prompt.Confirm.ask(
148-
"You've reached the end of the list. You must make a selection. Loop through again?"
149-
):
150-
raise IndexError
151-
else:
152-
continue
153-
else:
154-
return delegates[selected_idx_]

bittensor_cli/src/commands/stake/add.py

Lines changed: 19 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -46,9 +46,7 @@ async def stake_add(
4646
netuid: the netuid to stake to (None indicates all subnets)
4747
stake_all: whether to stake all available balance
4848
amount: specified amount of balance to stake
49-
delegate: whether to delegate stake, currently unused
5049
prompt: whether to prompt the user
51-
max_stake: maximum amount to stake (used in combination with stake_all), currently unused
5250
all_hotkeys: whether to stake all hotkeys
5351
include_hotkeys: list of hotkeys to include in staking process (if not specifying `--all`)
5452
exclude_hotkeys: list of hotkeys to exclude in staking (if specifying `--all`)
@@ -61,18 +59,16 @@ async def stake_add(
6159
"""
6260

6361
async def safe_stake_extrinsic(
64-
netuid: int,
65-
amount: Balance,
62+
netuid_: int,
63+
amount_: Balance,
6664
current_stake: Balance,
67-
hotkey_ss58: str,
65+
hotkey_ss58_: str,
6866
price_limit: Balance,
69-
wallet: Wallet,
70-
subtensor: "SubtensorInterface",
7167
status=None,
7268
) -> None:
7369
err_out = partial(print_error, status=status)
7470
failure_prelude = (
75-
f":cross_mark: [red]Failed[/red] to stake {amount} on Netuid {netuid}"
71+
f":cross_mark: [red]Failed[/red] to stake {amount_} on Netuid {netuid_}"
7672
)
7773
current_balance = await subtensor.get_balance(wallet.coldkeypub.ss58_address)
7874
next_nonce = await subtensor.substrate.get_account_next_index(
@@ -82,9 +78,9 @@ async def safe_stake_extrinsic(
8278
call_module="SubtensorModule",
8379
call_function="add_stake_limit",
8480
call_params={
85-
"hotkey": hotkey_ss58,
86-
"netuid": netuid,
87-
"amount_staked": amount.rao,
81+
"hotkey": hotkey_ss58_,
82+
"netuid": netuid_,
83+
"amount_staked": amount_.rao,
8884
"limit_price": price_limit,
8985
"allow_partial": allow_partial_stake,
9086
},
@@ -119,30 +115,30 @@ async def safe_stake_extrinsic(
119115
new_balance, new_stake = await asyncio.gather(
120116
subtensor.get_balance(wallet.coldkeypub.ss58_address, block_hash),
121117
subtensor.get_stake(
122-
hotkey_ss58=hotkey_ss58,
118+
hotkey_ss58=hotkey_ss58_,
123119
coldkey_ss58=wallet.coldkeypub.ss58_address,
124-
netuid=netuid,
120+
netuid=netuid_,
125121
block_hash=block_hash,
126122
),
127123
)
128124
console.print(
129-
f":white_heavy_check_mark: [dark_sea_green3]Finalized. Stake added to netuid: {netuid}[/dark_sea_green3]"
125+
f":white_heavy_check_mark: [dark_sea_green3]Finalized. Stake added to netuid: {netuid_}[/dark_sea_green3]"
130126
)
131127
console.print(
132128
f"Balance:\n [blue]{current_balance}[/blue] :arrow_right: [{COLOR_PALETTE['STAKE']['STAKE_AMOUNT']}]{new_balance}"
133129
)
134130

135131
amount_staked = current_balance - new_balance
136-
if allow_partial_stake and (amount_staked != amount):
132+
if allow_partial_stake and (amount_staked != amount_):
137133
console.print(
138134
"Partial stake transaction. Staked:\n"
139135
f" [{COLOR_PALETTE['STAKE']['STAKE_AMOUNT']}]{amount_staked}[/{COLOR_PALETTE['STAKE']['STAKE_AMOUNT']}] "
140136
f"instead of "
141-
f"[blue]{amount}[/blue]"
137+
f"[blue]{amount_}[/blue]"
142138
)
143139

144140
console.print(
145-
f"Subnet: [{COLOR_PALETTE['GENERAL']['SUBHEADING']}]{netuid}[/{COLOR_PALETTE['GENERAL']['SUBHEADING']}] "
141+
f"Subnet: [{COLOR_PALETTE['GENERAL']['SUBHEADING']}]{netuid_}[/{COLOR_PALETTE['GENERAL']['SUBHEADING']}] "
146142
f"Stake:\n"
147143
f" [blue]{current_stake}[/blue] "
148144
f":arrow_right: "
@@ -361,13 +357,11 @@ async def stake_extrinsic(
361357
else:
362358
stake_coroutines.append(
363359
safe_stake_extrinsic(
364-
netuid=ni,
365-
amount=am,
360+
netuid_=ni,
361+
amount_=am,
366362
current_stake=curr,
367-
hotkey_ss58=staking_address,
363+
hotkey_ss58_=staking_address,
368364
price_limit=price_with_tolerance,
369-
wallet=wallet,
370-
subtensor=subtensor,
371365
)
372366
)
373367
else:
@@ -590,7 +584,9 @@ def _print_table_and_slippage(table: Table, max_slippage: float, safe_staking: b
590584
console.print(base_description + (safe_staking_description if safe_staking else ""))
591585

592586

593-
def _calculate_slippage(subnet_info, amount: Balance) -> tuple[Balance, str, float]:
587+
def _calculate_slippage(
588+
subnet_info, amount: Balance
589+
) -> tuple[Balance, str, float, str]:
594590
"""Calculate slippage when adding stake.
595591
596592
Args:

0 commit comments

Comments
 (0)