Skip to content

Commit

Permalink
Merge pull request #2382 from opentensor/feat/roman/remove-prompt-fro…
Browse files Browse the repository at this point in the history
…m-sdk

Avoid using `prompt` in SDK
  • Loading branch information
ibraheem-opentensor authored Nov 5, 2024
2 parents 43a01a7 + e50b59b commit 3e1e179
Show file tree
Hide file tree
Showing 24 changed files with 332 additions and 645 deletions.
6 changes: 1 addition & 5 deletions bittensor/core/async_subtensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -694,7 +694,7 @@ async def filter_netuids_by_registered_hotkeys(
"""
Filters a given list of all netuids for certain specified netuids and hotkeys
Argumens:
Args:
all_netuids (Iterable[int]): A list of netuids to filter.
filter_for_netuids (Iterable[int]): A subset of all_netuids to filter from the main list
all_hotkeys (Iterable[Wallet]): Hotkeys to filter from the main list
Expand Down Expand Up @@ -1315,7 +1315,6 @@ async def transfer(
destination: str,
amount: float,
transfer_all: bool,
prompt: bool,
) -> bool:
"""
Transfer token of amount to destination.
Expand All @@ -1325,7 +1324,6 @@ async def transfer(
destination (str): Destination address for the transfer.
amount (float): Amount of tokens to transfer.
transfer_all (bool): Flag to transfer all tokens.
prompt (bool): Flag to prompt user for confirmation before transferring.
Returns:
`True` if the transferring was successful, otherwise `False`.
Expand All @@ -1336,7 +1334,6 @@ async def transfer(
destination,
Balance.from_tao(amount),
transfer_all,
prompt=prompt,
)

async def register(
Expand Down Expand Up @@ -1413,7 +1410,6 @@ async def pow_register(
subtensor=self,
wallet=wallet,
netuid=netuid,
prompt=True,
tpb=threads_per_block,
update_interval=update_interval,
num_processes=processors,
Expand Down
12 changes: 0 additions & 12 deletions bittensor/core/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,18 +97,6 @@ def __init__(
# this can fail if --no_version_checking has already been added.
pass

try:
parser.add_argument(
"--no_prompt",
dest="no_prompt",
action="store_true",
help="Set ``true`` to stop cli from prompting the user.",
default=False,
)
except Exception:
# this can fail if --no_version_checking has already been added.
pass

# Get args from argv if not passed in.
if args is None:
args = sys.argv[1:]
Expand Down
379 changes: 166 additions & 213 deletions bittensor/core/extrinsics/async_registration.py

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion bittensor/core/extrinsics/async_root.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ async def get_limits(subtensor: "AsyncSubtensor") -> tuple[int, float]:

async def root_register_extrinsic(
subtensor: "AsyncSubtensor",
wallet: Wallet,
wallet: "Wallet",
netuid: int,
wait_for_inclusion: bool = True,
wait_for_finalization: bool = True,
Expand Down
43 changes: 16 additions & 27 deletions bittensor/core/extrinsics/async_transfer.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@

from bittensor_wallet import Wallet
from bittensor_wallet.errors import KeyFileError
from rich.prompt import Confirm
from substrateinterface.exceptions import SubstrateRequestException

from bittensor.core.settings import NETWORK_EXPLORER_MAP
Expand All @@ -23,28 +22,26 @@ async def transfer_extrinsic(
subtensor: "AsyncSubtensor",
wallet: Wallet,
destination: str,
amount: Balance,
amount: "Balance",
transfer_all: bool = False,
wait_for_inclusion: bool = True,
wait_for_finalization: bool = False,
keep_alive: bool = True,
prompt: bool = False,
) -> bool:
"""Transfers funds from this wallet to the destination public key address.
:param subtensor: initialized AsyncSubtensor object used for transfer
:param wallet: Bittensor wallet object to make transfer from.
:param destination: Destination public key address (ss58_address or ed25519) of recipient.
:param amount: Amount to stake as Bittensor balance.
:param transfer_all: Whether to transfer all funds from this wallet to the destination address.
:param wait_for_inclusion: If set, waits for the extrinsic to enter a block before returning `True`,
or returns `False` if the extrinsic fails to enter the block within the timeout.
:param wait_for_finalization: If set, waits for the extrinsic to be finalized on the chain before returning
`True`, or returns `False` if the extrinsic fails to be finalized within the timeout.
:param keep_alive: If set, keeps the account alive by keeping the balance above the existential deposit.
:param prompt: If `True`, the call waits for confirmation from the user before proceeding.
:return: success: Flag is `True` if extrinsic was finalized or included in the block. If we did not wait for
finalization / inclusion, the response is `True`, regardless of its inclusion.
Args:
subtensor (bittensor.core.async_subtensor.AsyncSubtensor): initialized AsyncSubtensor object used for transfer
wallet (bittensor_wallet.Wallet): Bittensor wallet object to make transfer from.
destination (str): Destination public key address (ss58_address or ed25519) of recipient.
amount (bittensor.utils.balance.Balance): Amount to stake as Bittensor balance.
transfer_all (bool): Whether to transfer all funds from this wallet to the destination address.
wait_for_inclusion (bool): If set, waits for the extrinsic to enter a block before returning `True`, or returns `False` if the extrinsic fails to enter the block within the timeout.
wait_for_finalization (bool): If set, waits for the extrinsic to be finalized on the chain before returning `True`, or returns `False` if the extrinsic fails to be finalized within the timeout.
keep_alive (bool): If set, keeps the account alive by keeping the balance above the existential deposit.
Returns:
success (bool): Flag is `True` if extrinsic was finalized or included in the block. If we did not wait for finalization / inclusion, the response is `True`, regardless of its inclusion.
"""

async def get_transfer_fee() -> Balance:
Expand Down Expand Up @@ -76,7 +73,9 @@ async def get_transfer_fee() -> Balance:
async def do_transfer() -> tuple[bool, str, str]:
"""
Makes transfer from wallet to destination public key address.
:return: success, block hash, formatted error message
Returns:
success, block hash, formatted error message
"""
call = await subtensor.substrate.compose_call(
call_module="Balances",
Expand Down Expand Up @@ -155,16 +154,6 @@ async def do_transfer() -> tuple[bool, str, str]:
logging.error(f"\t\tFor fee:\t<blue>{fee}</blue>")
return False

# Ask before moving on.
if prompt:
if not Confirm.ask(
"Do you want to transfer:[bold white]\n"
f" amount: [bright_cyan]{amount}[/bright_cyan]\n"
f" from: [light_goldenrod2]{wallet.name}[/light_goldenrod2] : [bright_magenta]{wallet.coldkey.ss58_address}\n[/bright_magenta]"
f" to: [bright_magenta]{destination}[/bright_magenta]\n for fee: [bright_cyan]{fee}[/bright_cyan]"
):
return False

logging.info(":satellite: <magenta>Transferring...</magenta")
success, block_hash, err_msg = await do_transfer()

Expand Down
3 changes: 1 addition & 2 deletions bittensor/core/extrinsics/async_weights.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,6 @@ async def set_weights_extrinsic(
version_key (int): The version key of the validator.
wait_for_inclusion (bool): If set, waits for the extrinsic to enter a block before returning ``true``, or returns ``false`` if the extrinsic fails to enter the block within the timeout.
wait_for_finalization (bool): If set, waits for the extrinsic to be finalized on the chain before returning ``true``, or returns ``false`` if the extrinsic fails to be finalized within the timeout.
prompt (bool): If ``true``, the call waits for confirmation from the user before proceeding.
Returns:
success (bool): Flag is ``true`` if extrinsic was finalized or included in the block. If we did not wait for finalization / inclusion, the response is ``true``.
Expand Down Expand Up @@ -222,7 +221,7 @@ async def commit_weights_extrinsic(
) -> tuple[bool, str]:
"""
Commits a hash of the neuron's weights to the Bittensor blockchain using the provided wallet.
This function is a wrapper around the `do_commit_weights` method, handling user prompts and error messages.
This function is a wrapper around the `do_commit_weights` method.
Args:
subtensor (bittensor.core.subtensor.Subtensor): The subtensor instance used for blockchain interaction.
Expand Down
22 changes: 5 additions & 17 deletions bittensor/core/extrinsics/commit_weights.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
from typing import Optional, TYPE_CHECKING

from retry import retry
from rich.prompt import Confirm

from bittensor.core.extrinsics.utils import submit_extrinsic
from bittensor.utils import format_error_message
Expand All @@ -33,7 +32,7 @@
from bittensor.core.subtensor import Subtensor


# # Chain call for `commit_weights_extrinsic`
# Chain call for `commit_weights_extrinsic`
@ensure_connected
def do_commit_weights(
self: "Subtensor",
Expand Down Expand Up @@ -101,11 +100,10 @@ def commit_weights_extrinsic(
commit_hash: str,
wait_for_inclusion: bool = False,
wait_for_finalization: bool = False,
prompt: bool = False,
) -> tuple[bool, str]:
"""
Commits a hash of the neuron's weights to the Bittensor blockchain using the provided wallet.
This function is a wrapper around the `do_commit_weights` method, handling user prompts and error messages.
This function is a wrapper around the `do_commit_weights` method.
Args:
subtensor (bittensor.core.subtensor.Subtensor): The subtensor instance used for blockchain interaction.
Expand All @@ -114,16 +112,12 @@ def commit_weights_extrinsic(
commit_hash (str): The hash of the neuron's weights to be committed.
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.
prompt (bool): If ``True``, prompts for user confirmation before proceeding.
Returns:
tuple[bool, str]: ``True`` if the weight commitment is successful, False otherwise. And `msg`, a string
value describing the success or potential error.
tuple[bool, str]: ``True`` if the weight commitment is successful, False otherwise. And `msg`, a string value describing the success or potential error.
This function provides a user-friendly interface for committing weights to the Bittensor blockchain, ensuring proper error handling and user interaction when required.
"""
if prompt and not Confirm.ask(f"Would you like to commit weights?"):
return False, "User cancelled the operation."

success, error_message = do_commit_weights(
self=subtensor,
Expand Down Expand Up @@ -226,11 +220,10 @@ def reveal_weights_extrinsic(
version_key: int,
wait_for_inclusion: bool = False,
wait_for_finalization: bool = False,
prompt: bool = False,
) -> tuple[bool, str]:
"""
Reveals the weights for a specific subnet on the Bittensor blockchain using the provided wallet.
This function is a wrapper around the `_do_reveal_weights` method, handling user prompts and error messages.
This function is a wrapper around the `_do_reveal_weights` method.
Args:
subtensor (bittensor.core.subtensor.Subtensor): The subtensor instance used for blockchain interaction.
Expand All @@ -242,18 +235,13 @@ def reveal_weights_extrinsic(
version_key (int): Version key for compatibility with the network.
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.
prompt (bool): If ``True``, prompts for user confirmation before proceeding.
Returns:
tuple[bool, str]: ``True`` if the weight revelation is successful, False otherwise. And `msg`, a string
value describing the success or potential error.
tuple[bool, str]: ``True`` if the weight revelation is successful, False otherwise. And `msg`, a string value describing the success or potential error.
This function provides a user-friendly interface for revealing weights on the Bittensor blockchain, ensuring proper error handling and user interaction when required.
"""

if prompt and not Confirm.ask(f"Would you like to reveal weights?"):
return False, "User cancelled the operation."

success, error_message = do_reveal_weights(
self=subtensor,
wallet=wallet,
Expand Down
39 changes: 11 additions & 28 deletions bittensor/core/extrinsics/registration.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@

from bittensor_wallet.errors import KeyFileError
from retry import retry
from rich.prompt import Confirm

from bittensor.utils import format_error_message
from bittensor.utils.btlogging import logging
Expand All @@ -43,7 +42,7 @@ def _do_pow_register(
self: "Subtensor",
netuid: int,
wallet: "Wallet",
pow_result: POWSolution,
pow_result: "POWSolution",
wait_for_inclusion: bool = False,
wait_for_finalization: bool = True,
) -> tuple[bool, Optional[str]]:
Expand All @@ -53,14 +52,12 @@ def _do_pow_register(
netuid (int): The subnet to register on.
wallet (bittensor.wallet): The wallet to register.
pow_result (POWSolution): The PoW result to register.
wait_for_inclusion (bool): If ``True``, waits for the extrinsic to be included in a block.
Default to `False`.
wait_for_inclusion (bool): If ``True``, waits for the extrinsic to be included in a block. Default to `False`.
wait_for_finalization (bool): If ``True``, waits for the extrinsic to be finalized. Default to `True`.
Returns:
success (bool): ``True`` if the extrinsic was included in a block.
error (Optional[str]): ``None`` on success or not waiting for inclusion/finalization, otherwise the error
message.
error (Optional[str]): ``None`` on success or not waiting for inclusion/finalization, otherwise the error message.
"""

@retry(delay=1, tries=3, backoff=2, max_delay=4)
Expand Down Expand Up @@ -110,7 +107,6 @@ def register_extrinsic(
netuid: int,
wait_for_inclusion: bool = False,
wait_for_finalization: bool = True,
prompt: bool = False,
max_allowed_attempts: int = 3,
output_in_place: bool = True,
cuda: bool = False,
Expand All @@ -128,7 +124,6 @@ def register_extrinsic(
netuid (int): The ``netuid`` of the subnet to register on.
wait_for_inclusion (bool): If set, waits for the extrinsic to enter a block before returning ``true``, or returns ``false`` if the extrinsic fails to enter the block within the timeout.
wait_for_finalization (bool): If set, waits for the extrinsic to be finalized on the chain before returning ``true``, or returns ``false`` if the extrinsic fails to be finalized within the timeout.
prompt (bool): If ``true``, the call waits for confirmation from the user before proceeding.
max_allowed_attempts (int): Maximum number of attempts to register the wallet.
output_in_place (bool): If true, prints the progress of the proof of work to the console in-place. Meaning the progress is printed on the same lines. Defaults to `True`.
cuda (bool): If ``true``, the wallet should be registered using CUDA device(s).
Expand Down Expand Up @@ -160,15 +155,9 @@ def register_extrinsic(
)
return True

if prompt:
if not Confirm.ask(
"Continue Registration?\n hotkey: [bold white]{}[/bold white]\n coldkey: [bold white]{}[/bold white]\n network: [bold white]{}[/bold white]".format(
wallet.hotkey.ss58_address,
wallet.coldkeypub.ss58_address,
subtensor.network,
)
):
return False
logging.debug(
f"Registration hotkey: <blue>{wallet.hotkey.ss58_address}</blue>, <green>Public</green> coldkey: <blue>{wallet.coldkey.ss58_address}</blue> in the network: <blue>{subtensor.network}</blue>."
)

if not torch:
log_no_torch_error()
Expand All @@ -183,8 +172,6 @@ def register_extrinsic(
# Solve latest POW.
if cuda:
if not torch.cuda.is_available():
if prompt:
logging.info("CUDA is not available.")
return False
pow_result: Optional[POWSolution] = create_pow(
subtensor,
Expand Down Expand Up @@ -353,7 +340,6 @@ def burned_register_extrinsic(
netuid: int,
wait_for_inclusion: bool = False,
wait_for_finalization: bool = True,
prompt: bool = False,
) -> bool:
"""Registers the wallet to chain by recycling TAO.
Expand All @@ -363,7 +349,6 @@ def burned_register_extrinsic(
netuid (int): The ``netuid`` of the subnet to register on.
wait_for_inclusion (bool): If set, waits for the extrinsic to enter a block before returning ``true``, or returns ``false`` if the extrinsic fails to enter the block within the timeout.
wait_for_finalization (bool): If set, waits for the extrinsic to be finalized on the chain before returning ``true``, or returns ``false`` if the extrinsic fails to be finalized within the timeout.
prompt (bool): If ``true``, the call waits for confirmation from the user before proceeding.
Returns:
success (bool): Flag is ``true`` if extrinsic was finalized or uncluded in the block. If we did not wait for finalization / inclusion, the response is ``true``.
Expand All @@ -390,7 +375,6 @@ def burned_register_extrinsic(

old_balance = subtensor.get_balance(wallet.coldkeypub.ss58_address)

recycle_amount = subtensor.recycle(netuid=netuid)
if not neuron.is_null:
logging.info(":white_heavy_check_mark: <green>Already Registered</green>")
logging.info(f"\t\tuid: <blue>{neuron.uid}</blue>")
Expand All @@ -399,12 +383,11 @@ def burned_register_extrinsic(
logging.info(f"\t\tcoldkey: <blue>{neuron.coldkey}</blue>")
return True

if prompt:
# Prompt user for confirmation.
if not Confirm.ask(f"Recycle {recycle_amount} to register on subnet:{netuid}?"):
return False

logging.info(":satellite: <magenta>Recycling TAO for Registration...</magenta>")

recycle_amount = subtensor.recycle(netuid=netuid)
logging.info(f"Recycling {recycle_amount} to register on subnet:{netuid}")

success, err_msg = _do_burned_register(
self=subtensor,
netuid=netuid,
Expand All @@ -414,7 +397,7 @@ def burned_register_extrinsic(
)

if not success:
logging.error(f":cross_mark: <red>Failed:</red> {err_msg}")
logging.error(f":cross_mark: <red>Failed error:</red> {err_msg}")
time.sleep(0.5)
return False
# Successful registration, final check for neuron and pubkey
Expand Down
Loading

0 comments on commit 3e1e179

Please sign in to comment.