-
Notifications
You must be signed in to change notification settings - Fork 74
Expand file tree
/
Copy pathcli.py
More file actions
executable file
·10134 lines (9214 loc) · 380 KB
/
cli.py
File metadata and controls
executable file
·10134 lines (9214 loc) · 380 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import asyncio
import copy
import curses
import datetime
import importlib
import json
import logging
import os.path
import re
import ssl
import sys
import traceback
import warnings
from dataclasses import fields
from pathlib import Path
from typing import Coroutine, Optional, Union
import numpy as np
import rich
import typer
from async_substrate_interface.errors import (
SubstrateRequestException,
ConnectionClosed,
InvalidHandshake,
)
from bittensor_wallet import Wallet
from bittensor_wallet.utils import (
is_valid_ss58_address as btwallet_is_valid_ss58_address,
)
from rich import box
from rich.prompt import FloatPrompt, Prompt, IntPrompt
from rich.table import Column, Table
from rich.tree import Tree
from typing_extensions import Annotated
from yaml import safe_dump, safe_load
from bittensor_cli.src import (
defaults,
HELP_PANELS,
WalletOptions as WO,
WalletValidationTypes as WV,
Constants,
COLORS,
HYPERPARAMS,
HYPERPARAMS_METADATA,
RootSudoOnly,
WalletOptions,
)
from bittensor_cli.src.bittensor import utils
from bittensor_cli.src.bittensor.balances import Balance
from bittensor_cli.src.bittensor.chain_data import SubnetHyperparameters
from bittensor_cli.src.bittensor.subtensor_interface import (
SubtensorInterface,
best_connection,
)
from bittensor_cli.src.bittensor.utils import (
console,
err_console,
verbose_console,
json_console,
is_valid_ss58_address,
print_error,
validate_chain_endpoint,
validate_netuid,
is_rao_network,
get_effective_network,
prompt_for_identity,
validate_uri,
prompt_for_subnet_identity,
validate_rate_tolerance,
get_hotkey_pub_ss58,
ensure_address_book_tables_exist,
ProxyAddressBook,
ProxyAnnouncements,
confirm_action,
print_protection_warnings,
)
from bittensor_cli.src.commands import sudo, wallets, view
from bittensor_cli.src.commands import weights as weights_cmds
from bittensor_cli.src.commands.liquidity import liquidity
from bittensor_cli.src.commands.crowd import (
contribute as crowd_contribute,
create as create_crowdloan,
dissolve as crowd_dissolve,
view as view_crowdloan,
update as crowd_update,
refund as crowd_refund,
contributors as crowd_contributors,
)
from bittensor_cli.src.commands.liquidity.utils import (
prompt_liquidity,
prompt_position_id,
)
from bittensor_cli.src.commands import proxy as proxy_commands
from bittensor_cli.src.commands.proxy import ProxyType
from bittensor_cli.src.commands.stake import (
auto_staking as auto_stake,
children_hotkeys,
list as list_stake,
move as move_stake,
add as add_stake,
remove as remove_stake,
claim as claim_stake,
wizard as stake_wizard,
)
from bittensor_cli.src.commands.subnets import (
price,
subnets,
mechanisms as subnet_mechanisms,
)
from bittensor_cli.src.commands.axon import axon
from bittensor_cli.version import __version__, __version_as_int__
try:
from git import Repo, GitError
except ImportError:
Repo = None
class GitError(Exception):
pass
logger = logging.getLogger("btcli")
_epilog = "Made with [bold red]:heart:[/bold red] by The Openτensor Foundaτion"
np.set_printoptions(precision=8, suppress=True, floatmode="fixed")
def arg__(arg_name: str) -> str:
"""
Helper function to 'arg' format a string for rich console
"""
return f"[{COLORS.G.ARG}]{arg_name}[/{COLORS.G.ARG}]"
def is_valid_ss58_address_param(address: Optional[str]) -> Optional[str]:
"""
Evaluates whether a non-None address is a valid SS58 address. Used as a callback for
Annotated typer params.
Args:
address: an SS58 address, or None
Returns:
the SS58 address (if valid) or None (if None)
Raises:
typer.BadParameter: if the address is not a valid SS58 address
"""
if address is None:
return None
elif not btwallet_is_valid_ss58_address(address):
raise typer.BadParameter(f"Invalid SS58 address: {address}")
return address
def validate_claim_type(value: Optional[str]) -> Optional[claim_stake.ClaimType]:
"""
Validates the claim type argument, allowing case-insensitive input.
"""
if value is None:
return None
try:
for member in claim_stake.ClaimType:
if member.value.lower() == value.lower():
return member
return claim_stake.ClaimType(value)
except ValueError:
raise typer.BadParameter(f"'{value}' is not one of 'Keep', 'Swap'.")
class Options:
"""
Re-usable typer args
"""
@classmethod
def edit_help(cls, option_name: str, help_text: str):
"""
Edits the `help` attribute of a copied given Typer option in this class, returning
the modified Typer option.
Args:
option_name: the name of the option (e.g. "wallet_name")
help_text: New help text to be used (e.g. "Wallet's name")
Returns:
Modified Typer Option with new help text.
"""
copied_attr = copy.copy(getattr(cls, option_name))
setattr(copied_attr, "help", help_text)
return copied_attr
wallet_name = typer.Option(
None,
"--wallet-name",
"--name",
"--wallet_name",
"--wallet.name",
help="Name of the wallet.",
)
wallet_path = typer.Option(
None,
"--wallet-path",
"-p",
"--wallet_path",
"--wallet.path",
help="Path where the wallets are located. For example: `/Users/btuser/.bittensor/wallets`.",
)
wallet_hotkey = typer.Option(
None,
"--hotkey",
"-H",
"--wallet_hotkey",
"--wallet-hotkey",
"--wallet.hotkey",
help="Hotkey of the wallet",
)
wallet_ss58_address = typer.Option(
None,
"--wallet-name",
"--name",
"--wallet_name",
"--wallet.name",
"--address",
"--ss58",
"--ss58-address",
help="SS58 address or wallet name to check. Leave empty to be prompted.",
)
wallet_hotkey_ss58 = typer.Option(
None,
"--hotkey",
"--hotkey-ss58",
"-H",
"--wallet_hotkey",
"--wallet_hotkey_ss58",
"--wallet-hotkey",
"--wallet-hotkey-ss58",
"--wallet.hotkey",
help="Hotkey name or SS58 address of the hotkey",
)
coldkey_ss58 = typer.Option(
None,
"--ss58",
"--coldkey-ss58",
"--coldkey_ss58",
"--key",
"-k",
help="Coldkey address of the wallet",
)
mnemonic = typer.Option(
None,
help='Mnemonic used to regenerate your key. For example: "horse cart dog ..."',
)
seed = typer.Option(
None, help="Seed hex string used to regenerate your key. For example: 0x1234..."
)
json = typer.Option(
None,
"--json",
"-j",
help="Path to a JSON file containing the encrypted key backup. For example, a JSON file from PolkadotJS.",
)
json_password = typer.Option(
None, "--json-password", help="Password to decrypt the JSON file."
)
use_password = typer.Option(
True,
help="Set this to `True` to protect the generated Bittensor key with a password.",
)
public_hex_key = typer.Option(None, help="The public key in hex format.")
ss58_address = typer.Option(
None, "--ss58", "--ss58-address", help="The SS58 address of the coldkey."
)
overwrite = typer.Option(
False,
"--overwrite/--no-overwrite",
help="Overwrite the existing wallet file with the new one.",
)
network = typer.Option(
None,
"--network",
"--subtensor.network",
"--chain",
"--subtensor.chain_endpoint",
help="The subtensor network to connect to. Default: finney.",
show_default=False,
)
netuids = typer.Option(
None,
"--netuids",
"--netuid",
"-n",
help="Set the netuid(s) to exclude. Separate multiple netuids with a comma, for example: `-n 0,1,2`.",
)
netuid = typer.Option(
None,
help="The netuid of the subnet in the network, (e.g. 1).",
prompt=True,
callback=validate_netuid,
)
netuid_not_req = typer.Option(
None,
help="The netuid of the subnet in the network, (e.g. 1).",
prompt=False,
)
mechanism_id = typer.Option(
None,
"--mechid",
"--mech-id",
"--mech_id",
"--mechanism_id",
"--mechanism-id",
help="Mechanism ID within the subnet (defaults to 0).",
)
all_netuids = typer.Option(
False,
help="Use all netuids",
prompt=False,
)
weights = typer.Option(
None,
"--weights",
"-w",
help="Weights for the specified UIDs, e.g. `-w 0.2,0.4,0.1 ...` Must correspond to the order of the UIDs.",
)
reuse_last = typer.Option(
False,
"--reuse-last",
help="Reuse the metagraph data you last retrieved."
"Use this option only if you have already retrieved the metagraph."
"data",
)
html_output = typer.Option(
False,
"--html",
help="Display the table as HTML in the browser.",
)
wait_for_inclusion = typer.Option(
True, help="If `True`, waits until the transaction is included in a block."
)
wait_for_finalization = typer.Option(
True,
help="If `True`, waits until the transaction is finalized on the blockchain.",
)
prompt = typer.Option(
True,
"--prompt/--no-prompt",
" /--yes",
" /--no_prompt",
" /-y",
help="Enable or disable interactive prompts.",
)
decline = typer.Option(
False,
"--no",
help="Automatically decline any confirmation prompts. The prompt message is still displayed unless --quiet is specified.",
)
verbose = typer.Option(
False,
"--verbose",
help="Enable verbose output.",
)
quiet = typer.Option(
False,
"--quiet",
help="Display only critical information on the console.",
)
live = typer.Option(
False,
"--live",
help="Display live view of the table",
)
uri = typer.Option(
None,
"--uri",
help="Create wallet from uri (e.g. 'Alice', 'Bob', 'Charlie', 'Dave', 'Eve')",
callback=validate_uri,
)
rate_tolerance = typer.Option(
None,
"--tolerance",
"--rate-tolerance",
help="Set the rate tolerance percentage for transactions (default: 0.05 for 5%).",
callback=validate_rate_tolerance,
)
safe_staking = typer.Option(
None,
"--safe-staking/--no-safe-staking",
"--safe/--unsafe",
show_default=False,
help="Enable or disable safe staking mode [dim](default: enabled)[/dim].",
)
allow_partial_stake = typer.Option(
None,
"--allow-partial-stake/--no-allow-partial-stake",
"--partial/--no-partial",
"--allow/--not-allow",
"--allow-partial/--not-partial",
show_default=False,
help="Enable or disable partial stake mode [dim](default: disabled)[/dim].",
)
dashboard_path = typer.Option(
None,
"--dashboard-path",
"--dashboard_path",
"--dash_path",
"--dash.path",
"--dashboard.path",
help="Path to save the dashboard HTML file. For example: `~/.bittensor/dashboard`.",
)
mev_protection = typer.Option(
True,
"--mev-protection/--no-mev-protection",
show_default=False,
help="Enable or disable MEV protection [dim](default: enabled)[/dim].",
)
json_output = typer.Option(
False,
"--json-output",
"--json-out",
help="Outputs the result of the command as JSON.",
)
period: int = typer.Option(
16,
"--period",
"--era",
help="Length (in blocks) for which the transaction should be valid.",
)
proxy_type: ProxyType = typer.Option(
ProxyType.Any.value,
"--proxy-type",
help="Type of proxy",
prompt=True,
)
proxy: Optional[str] = typer.Option(
None,
"--proxy",
help="Optional proxy to use for the transaction: either the SS58 or the name of the proxy if you "
f"have added it with {arg__('btcli config add-proxy')}.",
)
real_proxy: Optional[str] = typer.Option(
None,
"--real",
help="The real account making this call. If omitted, the proxy's ss58 is used.",
)
announce_only: bool = typer.Option(
False,
help=f"If set along with [{COLORS.G.ARG}]--proxy[/{COLORS.G.ARG}], will not actually make the extrinsic call, "
f"but rather just announce it to be made later.",
)
def list_prompt(init_var: list, list_type: type, help_text: str) -> list:
"""
Serves a similar purpose to rich.FloatPrompt or rich.Prompt, but for creating a list of those variables for
a given type
:param init_var: starting variable, this will generally be `None` if you intend to get something out of this
prompt, if it is not empty, it will return the same
:param list_type: the type for each item in the list you're creating
:param help_text: the helper text to display to the user in the prompt
:return: list of the specified type of the user inputs
"""
while not init_var:
prompt = Prompt.ask(help_text)
init_var = [list_type(x) for x in re.split(r"[ ,]+", prompt) if x]
return init_var
def parse_to_list(
raw_list: str, list_type: type, error_message: str, is_ss58: bool = False
) -> list:
try:
# Split the string by commas and convert each part to according to type
parsed_list = [
list_type(uid.strip()) for uid in raw_list.split(",") if uid.strip()
]
# Validate in-case of ss58s
if is_ss58:
for item in parsed_list:
if not is_valid_ss58_address(item):
raise typer.BadParameter(f"Invalid SS58 address: {item}")
return parsed_list
except ValueError:
raise typer.BadParameter(error_message)
def verbosity_console_handler(verbosity_level: int = 1) -> None:
"""
Sets verbosity level of console output
:param verbosity_level: int corresponding to verbosity level of console output (0 is quiet, 1 is normal, 2 is
verbose)
"""
if verbosity_level not in range(4):
raise ValueError(
f"Invalid verbosity level: {verbosity_level}. "
f"Must be one of: 0 (quiet + json output), 1 (normal), 2 (verbose), 3 (json output + verbose)"
)
if verbosity_level == 0:
console.quiet = True
err_console.quiet = True
verbose_console.quiet = True
json_console.quiet = False
elif verbosity_level == 1:
console.quiet = False
err_console.quiet = False
verbose_console.quiet = True
json_console.quiet = True
elif verbosity_level == 2:
console.quiet = False
err_console.quiet = False
verbose_console.quiet = False
json_console.quiet = True
elif verbosity_level == 3:
console.quiet = True
err_console.quiet = True
verbose_console.quiet = False
json_console.quiet = False
def get_optional_netuid(netuid: Optional[int], all_netuids: bool) -> Optional[int]:
"""
Parses options to determine if the user wants to use a specific netuid or all netuids (None)
Returns:
None if using all netuids, otherwise int for the netuid to use
"""
if netuid is None and all_netuids is True:
return None
elif netuid is None and all_netuids is False:
answer = Prompt.ask(
f"Enter the [{COLORS.G.SUBHEAD_MAIN}]netuid"
f"[/{COLORS.G.SUBHEAD_MAIN}] to use. Leave blank for all netuids",
default=None,
show_default=False,
)
if answer is None:
return None
answer = answer.strip()
if answer.lower() == "all":
return None
else:
try:
return int(answer)
except ValueError:
print_error(f"Invalid netuid: {answer}")
return get_optional_netuid(None, False)
else:
return netuid
def get_n_words(n_words: Optional[int]) -> int:
"""
Prompts the user to select the number of words used in the mnemonic if not supplied or not within the
acceptable criteria of [12, 15, 18, 21, 24]
"""
while n_words not in [12, 15, 18, 21, 24]:
n_words = int(
Prompt.ask(
"Choose the number of words",
choices=["12", "15", "18", "21", "24"],
default=12,
)
)
return n_words
def parse_mnemonic(mnemonic: str) -> str:
if "-" in mnemonic:
items = sorted(
[tuple(item.split("-")) for item in mnemonic.split(" ")],
key=lambda x: int(x[0]),
)
if int(items[0][0]) != 1:
print_error("Numbered mnemonics must begin with 1")
raise typer.Exit()
if [int(x[0]) for x in items] != list(
range(int(items[0][0]), int(items[-1][0]) + 1)
):
print_error(
"Missing or duplicate numbers in a numbered mnemonic. "
"Double-check your numbered mnemonics and try again."
)
raise typer.Exit()
response = " ".join(item[1] for item in items)
else:
response = mnemonic
return response
def get_creation_data(
mnemonic: Optional[str],
seed: Optional[str],
json_path: Optional[str],
json_password: Optional[str],
) -> tuple[str, str, str, str]:
"""
Determines which of the key creation elements have been supplied, if any. If None have been supplied,
prompts to user, and determines what they've supplied. Returns all elements in a tuple.
"""
if not mnemonic and not seed and not json_path:
choices = {
1: "mnemonic",
2: "seed hex string",
3: "path to JSON File",
}
type_answer = IntPrompt.ask(
"Select one of the following to enter\n"
f"[{COLORS.G.HINT}][1][/{COLORS.G.HINT}] Mnemonic\n"
f"[{COLORS.G.HINT}][2][/{COLORS.G.HINT}] Seed hex string\n"
f"[{COLORS.G.HINT}][3][/{COLORS.G.HINT}] Path to JSON File\n",
choices=["1", "2", "3"],
show_choices=False,
)
prompt_answer = Prompt.ask(f"Please enter your {choices[type_answer]}")
if type_answer == 1:
mnemonic = prompt_answer
elif type_answer == 2:
seed = prompt_answer
if seed.startswith("0x"):
seed = seed[2:]
elif type_answer == 3:
json_path = prompt_answer
elif mnemonic:
mnemonic = parse_mnemonic(mnemonic)
if json_path:
if not os.path.exists(json_path):
print_error(f"The JSON file '{json_path}' does not exist.")
raise typer.Exit()
if json_path and not json_password:
json_password = Prompt.ask(
"Enter the backup password for JSON file.", password=True
)
return mnemonic, seed, json_path, json_password
def config_selector(conf: dict, title: str):
def curses_selector(stdscr):
"""
Enhanced Curses TUI to make selections.
"""
# Load the current selections from the config
items = list(conf.keys())
selections = conf
# Track the current index for navigation
current_index = 0
# Hide cursor
curses.curs_set(0)
while True:
stdscr.clear()
height, width = stdscr.getmaxyx()
stdscr.box()
stdscr.addstr(0, (width - len(title)) // 2, title, curses.A_BOLD)
instructions = (
"Use UP/DOWN keys to navigate, SPACE to toggle, ENTER to confirm."
)
stdscr.addstr(
2, (width - len(instructions)) // 2, instructions, curses.A_DIM
)
for idx, item in enumerate(items):
indicator = "[x]" if selections[item] else "[ ]"
line_text = f" {item} {indicator}"
x_pos = (width - len(line_text)) // 2
if idx == current_index:
stdscr.addstr(
4 + idx, x_pos, line_text, curses.A_REVERSE | curses.A_BOLD
)
else:
stdscr.addstr(4 + idx, x_pos, line_text)
stdscr.refresh()
key = stdscr.getch()
if key == curses.KEY_UP:
current_index = (current_index - 1) % len(items)
elif key == curses.KEY_DOWN:
current_index = (current_index + 1) % len(items)
elif key == ord(" "): # Toggle selection with spacebar
selections[items[current_index]] = not selections[items[current_index]]
elif key == ord("\n"): # Exit with Enter key
break
return selections
return curses.wrapper(curses_selector)
def version_callback(value: bool):
"""
Prints the current version/branch-name
"""
if value:
try:
repo = Repo(os.path.dirname(os.path.dirname(__file__)))
version = (
f"BTCLI version: {__version__}/"
f"{repo.active_branch.name}/"
f"{repo.commit()}"
)
except (TypeError, GitError):
version = f"BTCLI version: {__version__}"
typer.echo(version)
raise typer.Exit()
def commands_callback(value: bool):
"""
Prints a tree of commands for the app
"""
if value:
cli = CLIManager()
console.print(cli.generate_command_tree())
raise typer.Exit()
def debug_callback(value: bool):
if value:
debug_file_loc = Path(
os.getenv("BTCLI_DEBUG_FILE")
or os.path.expanduser(defaults.config.debug_file_path)
)
if not debug_file_loc.exists():
print_error(
f"Error: The debug file '{arg__(str(debug_file_loc))}' does not exist. This indicates that you have"
f" not run a command which has logged debug output, or you deleted this file. Debug logging only occurs"
f" if {arg__('use_cache')} is set to True in your config ({arg__('btcli config set')}). If the debug "
f"file was created using the {arg__('BTCLI_DEBUG_FILE')} environment variable, please set the value for"
f" the same location, and re-run this {arg__('btcli --debug')} command."
)
raise typer.Exit()
save_file_loc_ = Prompt.ask(
"Enter the file location to save the debug log for the previous command.",
default="~/.bittensor/debug-export",
).strip()
save_file_loc = Path(os.path.expanduser(save_file_loc_))
if not save_file_loc.parent.exists():
if confirm_action(
f"The directory '{save_file_loc.parent}' does not exist. Would you like to create it?",
decline=False,
quiet=False,
):
save_file_loc.parent.mkdir(parents=True, exist_ok=True)
try:
with (
open(save_file_loc, "w+") as save_file,
open(debug_file_loc, "r") as current_file,
):
save_file.write(current_file.read())
console.print(f"Saved debug log to {save_file_loc}")
except FileNotFoundError as e:
print_error(str(e))
raise typer.Exit()
class CLIManager:
"""
:var app: the main CLI Typer app
:var config_app: the Typer app as it relates to config commands
:var wallet_app: the Typer app as it relates to wallet commands
:var stake_app: the Typer app as it relates to stake commands
:var sudo_app: the Typer app as it relates to sudo commands
:var subnet_mechanisms_app: the Typer app for subnet mechanism commands
:var subnets_app: the Typer app as it relates to subnets commands
:var subtensor: the `SubtensorInterface` object passed to the various commands that require it
"""
subtensor: Optional[SubtensorInterface]
app: typer.Typer
config_app: typer.Typer
wallet_app: typer.Typer
sudo_app: typer.Typer
subnets_app: typer.Typer
subnet_mechanisms_app: typer.Typer
weights_app: typer.Typer
crowd_app: typer.Typer
utils_app: typer.Typer
view_app: typer.Typer
asyncio_runner = asyncio
def __init__(self):
self.config = {
"wallet_name": None,
"wallet_path": None,
"wallet_hotkey": None,
"network": None,
"use_cache": True,
"disk_cache": True,
"rate_tolerance": None,
"safe_staking": True,
"allow_partial_stake": False,
"dashboard_path": None,
# Commenting this out as this needs to get updated
# "metagraph_cols": {
# "UID": True,
# "GLOBAL_STAKE": True,
# "LOCAL_STAKE": True,
# "STAKE_WEIGHT": True,
# "RANK": True,
# "TRUST": True,
# "CONSENSUS": True,
# "INCENTIVE": True,
# "DIVIDENDS": True,
# "EMISSION": True,
# "VTRUST": True,
# "VAL": True,
# "UPDATED": True,
# "ACTIVE": True,
# "AXON": True,
# "HOTKEY": True,
# "COLDKEY": True,
# },
}
self.proxies = {}
self.subtensor = None
if sys.version_info < (3, 10):
# For Python 3.9 or lower
self.event_loop = asyncio.new_event_loop()
else:
try:
uvloop = importlib.import_module("uvloop")
self.event_loop = uvloop.new_event_loop()
except ModuleNotFoundError:
self.event_loop = asyncio.new_event_loop()
self.config_base_path = os.path.expanduser(defaults.config.base_path)
self.config_path = os.getenv("BTCLI_CONFIG_PATH") or os.path.expanduser(
defaults.config.path
)
self.debug_file_path = os.getenv("BTCLI_DEBUG_FILE") or os.path.expanduser(
defaults.config.debug_file_path
)
self.proxies_path = os.getenv("BTCLI_PROXIES_PATH") or os.path.expanduser(
defaults.proxies.path
)
self.app = typer.Typer(
rich_markup_mode="rich",
callback=self.main_callback,
epilog=_epilog,
no_args_is_help=True,
context_settings={"help_option_names": ["-h", "--help"]},
)
self.config_app = typer.Typer(
epilog=_epilog,
help=f"Allows for getting/setting the config. "
f"Default path for the config file is {arg__(defaults.config.path)}. "
f"You can set your own with the env var {arg__('BTCLI_CONFIG_PATH')}",
)
self.wallet_app = typer.Typer(epilog=_epilog)
self.stake_app = typer.Typer(epilog=_epilog)
self.sudo_app = typer.Typer(epilog=_epilog)
self.subnets_app = typer.Typer(epilog=_epilog)
self.subnet_mechanisms_app = typer.Typer(epilog=_epilog)
self.weights_app = typer.Typer(epilog=_epilog)
self.view_app = typer.Typer(epilog=_epilog)
self.liquidity_app = typer.Typer(epilog=_epilog)
self.crowd_app = typer.Typer(epilog=_epilog)
self.utils_app = typer.Typer(epilog=_epilog)
self.axon_app = typer.Typer(epilog=_epilog)
self.proxy_app = typer.Typer(epilog=_epilog)
# config alias
self.app.add_typer(
self.config_app,
name="config",
short_help="Config commands, aliases: `c`, `conf`",
no_args_is_help=True,
)
self.app.add_typer(
self.config_app, name="conf", hidden=True, no_args_is_help=True
)
self.app.add_typer(self.config_app, name="c", hidden=True, no_args_is_help=True)
# wallet aliases
self.app.add_typer(
self.wallet_app,
name="wallet",
short_help="Wallet commands, aliases: `wallets`, `w`",
no_args_is_help=True,
)
self.app.add_typer(self.wallet_app, name="w", hidden=True, no_args_is_help=True)
self.app.add_typer(
self.wallet_app, name="wallets", hidden=True, no_args_is_help=True
)
# stake aliases
self.app.add_typer(
self.stake_app,
name="stake",
short_help="Stake commands, alias: `st`",
no_args_is_help=True,
)
self.app.add_typer(self.stake_app, name="st", hidden=True, no_args_is_help=True)
# sudo aliases
self.app.add_typer(
self.sudo_app,
name="sudo",
short_help="Sudo commands, alias: `su`",
no_args_is_help=True,
)
self.app.add_typer(self.sudo_app, name="su", hidden=True, no_args_is_help=True)
# subnets aliases
self.app.add_typer(
self.subnets_app,
name="subnets",
short_help="Subnets commands, alias: `s`, `subnet`",
no_args_is_help=True,
)
self.app.add_typer(
self.subnets_app, name="s", hidden=True, no_args_is_help=True
)
self.app.add_typer(
self.subnets_app, name="subnet", hidden=True, no_args_is_help=True
)
# subnet mechanisms aliases
self.subnets_app.add_typer(
self.subnet_mechanisms_app,
name="mechanisms",
short_help="Subnet mechanism commands, alias: `mech`",
no_args_is_help=True,
)
self.subnets_app.add_typer(
self.subnet_mechanisms_app,
name="mech",
hidden=True,
no_args_is_help=True,
)
# weights aliases
self.app.add_typer(
self.weights_app,
name="weights",
short_help="Weights commands, aliases: `wt`, `weight`",
hidden=True,
no_args_is_help=True,
)
self.app.add_typer(
self.weights_app, name="wt", hidden=True, no_args_is_help=True
)
self.app.add_typer(
self.weights_app, name="weight", hidden=True, no_args_is_help=True
)
# utils app
self.app.add_typer(
self.utils_app, name="utils", no_args_is_help=True, hidden=False
)
# view app
self.app.add_typer(
self.view_app,
name="view",
short_help="HTML view commands",
no_args_is_help=True,
)
# axon app
self.app.add_typer(
self.axon_app,
name="axon",
short_help="Axon serving commands",
no_args_is_help=True,
)
# proxy app
self.app.add_typer(
self.proxy_app,
name="proxy",
short_help="Proxy commands",
no_args_is_help=True,
)
# config commands
self.config_app.command("set")(self.set_config)
self.config_app.command("get")(self.get_config)
self.config_app.command("clear")(self.del_config)
self.config_app.command("add-proxy")(self.config_add_proxy)
self.config_app.command("proxies")(self.config_get_proxies)
self.config_app.command("remove-proxy")(self.config_remove_proxy)
self.config_app.command("update-proxy")(self.config_update_proxy)
self.config_app.command("clear-proxies")(self.config_clear_proxy_book)
# self.config_app.command("metagraph", hidden=True)(self.metagraph_config)
# wallet commands