-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathcli.py
executable file
·2765 lines (2315 loc) · 104 KB
/
cli.py
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 os.path
import re
from typing import Optional, Coroutine
from bittensor_wallet import Wallet
from git import Repo
import rich
from rich.prompt import Confirm, Prompt, FloatPrompt
from rich.table import Table, Column
import typer
from typing_extensions import Annotated
from websockets import ConnectionClosed
from yaml import safe_load, safe_dump
from src import defaults, utils, HYPERPARAMS
from src.commands import wallets, root, stake, sudo
from src.subtensor_interface import SubtensorInterface
from src.bittensor.async_substrate_interface import SubstrateRequestException
from src.utils import console, err_console
__version__ = "8.0.0"
class Options:
"""
Re-usable typer args
"""
wallet_name = typer.Option(None, "--wallet-name", "-w", help="Name of wallet")
wallet_name_req = typer.Option(None, "--wallet-name", "-w", help="Name of wallet", prompt=True)
wallet_path = typer.Option(
None, "--wallet-path", "-p", help="Filepath of root of wallets"
)
wallet_hotkey = typer.Option(None, "--hotkey", "-H", help="Hotkey of wallet")
wallet_hk_req = typer.Option(
None,
"--hotkey",
"-H",
help="Hotkey name of wallet",
prompt=True,
)
mnemonic = typer.Option(
None, help="Mnemonic used to regen your key i.e. horse cart dog ..."
)
seed = typer.Option(
None, help="Seed hex string used to regen your key i.e. 0x1234..."
)
json = typer.Option(
None,
"--json",
"-j",
help="Path to a json file containing the encrypted key backup. (e.g. from PolkadotJS)",
)
json_password = typer.Option(
None, "--json-password", help="Password to decrypt the json file."
)
use_password = typer.Option(
True,
help="Set true to protect the generated bittensor key with a password.",
is_flag=True,
flag_value=False,
)
public_hex_key = typer.Option(None, help="The public key in hex format.")
ss58_address = typer.Option(None, help="The SS58 address of the coldkey")
overwrite_coldkey = typer.Option(
False,
help="Overwrite the old coldkey with the newly generated coldkey",
prompt=True,
)
overwrite_hotkey = typer.Option(
False,
help="Overwrite the old hotkey with the newly generated hotkey",
prompt=True,
)
network = typer.Option(
None,
help="The subtensor network to connect to. Default: finney.",
show_default=False,
)
chain = typer.Option(
None, help="The subtensor chain endpoint to connect to.", show_default=False
)
netuids = typer.Option(
[], "--netuids", "-n", help="Set the netuid(s) to filter by (e.g. `0 1 2`)"
)
netuid = typer.Option(
None,
help="The netuid (network unique identifier) of the subnet within the root network, (e.g. 1)",
prompt=True,
)
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 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 number of words: 12, 15, 18, 21, 24",
choices=["12", "15", "18", "21", "24"],
default=12,
)
)
return n_words
def get_creation_data(
mnemonic: str, seed: str, json: str, json_password: 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:
prompt_answer = Prompt.ask("Enter mnemonic, seed, or json file location")
if prompt_answer.startswith("0x"):
seed = prompt_answer
elif len(prompt_answer.split(" ")) > 1:
mnemonic = prompt_answer
else:
json = prompt_answer
if json and not json_password:
json_password = Prompt.ask("Enter json backup password", password=True)
return mnemonic, seed, json, json_password
def version_callback(value: bool):
"""
Prints the current version/branch-name
"""
if value:
typer.echo(
f"BTCLI Version: {__version__}/{Repo(os.path.dirname(__file__)).active_branch.name}"
)
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 root_app: the Typer app as it relates to root 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 not_subtensor: the `SubtensorInterface` object passed to the various commands that require it
"""
not_subtensor: Optional[SubtensorInterface]
app: typer.Typer
config_app: typer.Typer
wallet_app: typer.Typer
root_app: typer.Typer
def __init__(self):
self.config = {
"wallet_name": None,
"wallet_path": None,
"wallet_hotkey": None,
"network": None,
"chain": None,
}
self.not_subtensor = None
self.app = typer.Typer(rich_markup_mode="markdown", callback=self.main_callback)
self.config_app = typer.Typer()
self.wallet_app = typer.Typer()
self.root_app = typer.Typer()
self.stake_app = typer.Typer()
self.sudo_app = typer.Typer()
# config alias
self.app.add_typer(
self.config_app,
name="config",
short_help="Config commands, aliases: `c`, `conf`",
)
self.app.add_typer(self.config_app, name="conf", hidden=True)
self.app.add_typer(self.config_app, name="c", hidden=True)
# wallet aliases
self.app.add_typer(
self.wallet_app,
name="wallet",
short_help="Wallet commands, aliases: `wallets`, `w`",
)
self.app.add_typer(self.wallet_app, name="w", hidden=True)
self.app.add_typer(self.wallet_app, name="wallets", hidden=True)
# root aliases
self.app.add_typer(
self.root_app,
name="root",
short_help="Root commands, alias: `r`",
)
self.app.add_typer(self.root_app, name="d", hidden=True)
# stake aliases
self.app.add_typer(
self.stake_app,
name="stake",
short_help="Stake commands, alias: `st`",
)
self.app.add_typer(self.stake_app, name="st", hidden=True)
# sudo aliases
self.app.add_typer(
self.sudo_app,
name="sudo",
short_help="Sudo commands, alias: `su`",
)
self.app.add_typer(self.sudo_app, name="su", hidden=True)
# config commands
self.config_app.command("set")(self.set_config)
self.config_app.command("get")(self.get_config)
# wallet commands
self.wallet_app.command("list")(self.wallet_list)
self.wallet_app.command("regen-coldkey")(self.wallet_regen_coldkey)
self.wallet_app.command("regen-coldkeypub")(self.wallet_regen_coldkey_pub)
self.wallet_app.command("regen-hotkey")(self.wallet_regen_hotkey)
self.wallet_app.command("new-hotkey")(self.wallet_new_hotkey)
self.wallet_app.command("new-coldkey")(self.wallet_new_coldkey)
self.wallet_app.command("create")(self.wallet_create_wallet)
self.wallet_app.command("balance")(self.wallet_balance)
self.wallet_app.command("history")(self.wallet_history)
self.wallet_app.command("overview")(self.wallet_overview)
self.wallet_app.command("transfer")(self.wallet_transfer)
self.wallet_app.command("inspect")(self.wallet_inspect)
self.wallet_app.command("faucet")(self.wallet_faucet)
self.wallet_app.command("set-identity")(self.wallet_set_id)
self.wallet_app.command("get-identity")(self.wallet_get_id)
self.wallet_app.command("check-swap")(self.wallet_check_ck_swap)
# root commands
self.root_app.command("list")(self.root_list)
self.root_app.command("set-weights")(self.root_set_weights)
self.root_app.command("get-weights")(self.root_get_weights)
self.root_app.command("boost")(self.root_boost)
self.root_app.command("senate")(self.root_senate)
self.root_app.command("senate-vote")(self.root_senate_vote)
self.root_app.command("register")(self.root_register)
self.root_app.command("proposals")(self.root_proposals)
self.root_app.command("set-take")(self.root_set_take)
self.root_app.command("delegate-stake")(self.root_delegate_stake)
self.root_app.command("undelegate-stake")(self.root_undelegate_stake)
self.root_app.command("my-delegates")(self.root_my_delegates)
self.root_app.command("list-delegates")(self.root_list_delegates)
self.root_app.command("nominate")(self.root_nominate)
# stake commands
self.stake_app.command("show")(self.stake_show)
self.stake_app.command("add")(self.stake_add)
self.stake_app.command("remove")(self.stake_remove)
self.stake_app.command("get-children")(self.stake_get_children)
self.stake_app.command("set-children")(self.stake_set_children)
self.stake_app.command("revoke-children")(self.stake_revoke_children)
# sudo commands
self.sudo_app.command("set")(self.sudo_set)
self.sudo_app.command("get")(self.sudo_get)
# subnets commands
# self.subnets_app.command("hyperparameters")(self.sudo_get)
def initialize_chain(
self,
network: Optional[str] = typer.Option("default_network", help="Network name"),
chain: Optional[str] = typer.Option("default_chain", help="Chain name"),
) -> SubtensorInterface:
"""
Intelligently initializes a connection to the chain, depending on the supplied (or in config) values. Set's the
`self.not_subtensor` object to this created connection.
:param network: Network name (e.g. finney, test, etc.)
:param chain: the chain endpoint (e.g. ws://127.0.0.1:9945, wss://entrypoint-finney.opentensor.ai:443, etc.)
"""
if not self.not_subtensor:
if network or chain:
self.not_subtensor = SubtensorInterface(network, chain)
elif self.config["chain"] or self.config["chain"]:
self.not_subtensor = SubtensorInterface(
self.config["network"], self.config["chain"]
)
else:
self.not_subtensor = SubtensorInterface(
defaults.subtensor.network, defaults.subtensor.chain_endpoint
)
console.print(f"[yellow] Connected to [/yellow][white]{self.not_subtensor}")
return self.not_subtensor
def _run_command(self, cmd: Coroutine) -> None:
"""
Runs the supplied coroutine with asyncio.run
"""
async def _run():
if self.not_subtensor:
async with self.not_subtensor:
await cmd
else:
await cmd
try:
return asyncio.run(_run())
except ConnectionRefusedError:
err_console.print(
f"Connection refused when connecting to chain: {self.not_subtensor}"
)
except ConnectionClosed:
pass
except SubstrateRequestException as e:
err_console.print(str(e))
def main_callback(
self,
version: Annotated[
Optional[bool], typer.Option("--version", callback=version_callback)
] = None,
):
"""
Method called before all others when using any CLI command. Gives version if that flag is set, otherwise
loads the config from the config file.
"""
fp = os.path.expanduser(defaults.config.path)
# create config file if it does not exist
if not os.path.exists(fp):
with open(fp, "w") as f:
safe_dump(defaults.config.dictionary, f)
# check config
with open(fp, "r") as f:
config = safe_load(f)
for k, v in config.items():
if k in self.config.keys():
self.config[k] = v
def set_config(
self,
wallet_name: Optional[str] = typer.Option(
None,
"--wallet-name",
"--name",
help="Wallet name",
),
wallet_path: Optional[str] = typer.Option(
None,
"--wallet-path",
"--path",
"-p",
help="Path to root of wallets",
),
wallet_hotkey: Optional[str] = typer.Option(
None, "--wallet-hotkey", "--hotkey", "-k", help="Path to root of wallets"
),
network: Optional[str] = typer.Option(
None,
"--network",
"-n",
help="Network name: [finney, test, local]",
),
chain: Optional[str] = typer.Option(
None,
"--chain",
"-c",
help="Chain name",
),
):
"""
Sets values in config file
:param wallet_name: name of the wallet
:param wallet_path: root path of the wallets
:param wallet_hotkey: name of the wallet hotkey file
:param network: name of the network (e.g. finney, test, local)
:param chain: chain endpoint for the network (e.g. ws://127.0.0.1:9945,
wss://entrypoint-finney.opentensor.ai:443)
"""
args = locals()
for arg in ["wallet_name", "wallet_path", "wallet_hotkey", "network", "chain"]:
if val := args.get(arg):
self.config[arg] = val
with open(os.path.expanduser("~/.bittensor/config.yml"), "w") as f:
safe_dump(self.config, f)
def get_config(self):
"""
Prints the current config file in a table
"""
table = Table(Column("Name"), Column("Value"))
for k, v in self.config.items():
table.add_row(*[k, v])
console.print(table)
def wallet_ask(
self,
wallet_name: Optional[str],
wallet_path: Optional[str],
wallet_hotkey: Optional[str],
validate: bool = True,
) -> Wallet:
"""
Generates a wallet object based on supplied values, validating the wallet is valid if flag is set
:param wallet_name: name of the wallet
:param wallet_path: root path of the wallets
:param wallet_hotkey: name of the wallet hotkey file
:param validate: flag whether to check for the wallet's validity
:return: created Wallet object
"""
wallet_name = wallet_name or self.config.get("wallet_name")
wallet_path = wallet_path or self.config.get("wallet_path")
wallet_hotkey = wallet_hotkey or self.config.get("wallet_hotkey")
if not any([wallet_name, wallet_path, wallet_hotkey]):
wallet_name = typer.prompt("Enter wallet name")
wallet = Wallet(name=wallet_name)
else:
wallet = Wallet(name=wallet_name, hotkey=wallet_hotkey, path=wallet_path)
if validate:
valid = utils.is_valid_wallet(wallet)
if not valid[0]:
utils.err_console.print(
f"[red]Error: Wallet does not appear valid. Please verify your wallet information: {wallet}[/red]"
)
raise typer.Exit()
elif not valid[1]:
if not Confirm.ask(
f"[yellow]Warning: Wallet appears valid, but hotkey '{wallet.hotkey_str}' does not. Proceed?"
):
raise typer.Exit()
return wallet
def wallet_list(
self,
wallet_path: str = typer.Option(
defaults.wallet.path,
"--wallet-path",
"-p",
help="Filepath of root of wallets",
prompt=True,
),
):
"""
# wallet list
Executes the `list` command which enumerates all wallets and their respective hotkeys present in the user's
Bittensor configuration directory.
The command organizes the information in a tree structure, displaying each
wallet along with the `ss58` addresses for the coldkey public key and any hotkeys associated with it.
The output is presented in a hierarchical tree format, with each wallet as a root node,
and any associated hotkeys as child nodes. The ``ss58`` address is displayed for each
coldkey and hotkey that is not encrypted and exists on the device.
## Usage:
Upon invocation, the command scans the wallet directory and prints a list of all wallets, indicating whether the
public keys are available (`?` denotes unavailable or encrypted keys).
### Example usage:
```
btcli wallet list --path ~/.bittensor
```
#### Note:
This command is read-only and does not modify the filesystem or the network state. It is intended for use within
the Bittensor CLI to provide a quick overview of the user's wallets.
"""
return self._run_command(wallets.wallet_list(wallet_path))
def wallet_overview(
self,
wallet_name: Optional[str] = Options.wallet_name,
wallet_path: Optional[str] = Options.wallet_path,
wallet_hotkey: Optional[str] = Options.wallet_hotkey,
all_wallets: bool = typer.Option(
False, "--all", "-a", help="View overview for all wallets"
),
sort_by: Optional[str] = typer.Option(
None,
help="Sort the hotkeys by the specified column title (e.g. name, uid, axon).",
),
sort_order: Optional[str] = typer.Option(
None,
help="Sort the hotkeys in the specified ordering. (ascending/asc or descending/desc/reverse)",
),
include_hotkeys: list[str] = typer.Option(
[],
"--include-hotkeys",
"-in",
help="Specify the hotkeys to include by name or ss58 address. (e.g. `hk1 hk2 hk3`). "
"If left empty, all hotkeys not excluded will be included.",
),
exclude_hotkeys: list[str] = typer.Option(
[],
"--exclude-hotkeys",
"-ex",
help="Specify the hotkeys to exclude by name or ss58 address. (e.g. `hk1 hk2 hk3`). "
"If left empty, and no hotkeys included in --include-hotkeys, all hotkeys will be included.",
),
netuids: list[int] = Options.netuids,
network: str = Options.network,
chain: str = Options.chain,
):
"""
# wallet overview
Executes the `overview` command to present a detailed overview of the user's registered accounts on the
Bittensor network.
This command compiles and displays comprehensive information about each neuron associated with the user's
wallets, including both hotkeys and coldkeys. It is especially useful for users managing multiple accounts or
seeking a summary of their network activities and stake distributions.
## Usage:
The command offers various options to customize the output. Users can filter the displayed data by specific
netuids, sort by different criteria, and choose to include all wallets in the user's configuration directory.
The output is presented in a tabular format with the following columns:
- COLDKEY: The SS58 address of the coldkey.
- HOTKEY: The SS58 address of the hotkey.
- UID: Unique identifier of the neuron.
- ACTIVE: Indicates if the neuron is active.
- STAKE(τ): Amount of stake in the neuron, in Tao.
- RANK: The rank of the neuron within the network.
- TRUST: Trust score of the neuron.
- CONSENSUS: Consensus score of the neuron.
- INCENTIVE: Incentive score of the neuron.
- DIVIDENDS: Dividends earned by the neuron.
- EMISSION(p): Emission received by the neuron, in Rho.
- VTRUST: Validator trust score of the neuron.
- VPERMIT: Indicates if the neuron has a validator permit.
- UPDATED: Time since last update.
- AXON: IP address and port of the neuron.
- HOTKEY_SS58: Human-readable representation of the hotkey.
### Example usage:
- ```
btcli wallet overview
```
- ```
btcli wallet overview --all --sort-by stake --sort-order descending
```
- ```
btcli wallet overview -in hk1 -in hk2 --sort-by stake
```
#### Note:
This command is read-only and does not modify the network state or account configurations. It provides a quick
and comprehensive view of the user's network presence, making it ideal for monitoring account status, stake
distribution, and overall contribution to the Bittensor network.
"""
if include_hotkeys and exclude_hotkeys:
utils.err_console.print(
"[red]You have specified hotkeys for inclusion and exclusion. Pick only one or neither."
)
raise typer.Exit()
# if all-wallets is entered, ask for path
if all_wallets:
if not wallet_path:
wallet_path = Prompt.ask(
"Enter the path of the wallets", default=defaults.wallet.path
)
wallet = self.wallet_ask(wallet_name, wallet_path, wallet_hotkey)
return self._run_command(
wallets.overview(
wallet,
self.initialize_chain(network, chain),
all_wallets,
sort_by,
sort_order,
include_hotkeys,
exclude_hotkeys,
netuids_filter=netuids,
)
)
def wallet_transfer(
self,
destination: str = typer.Option(
None,
"--destination",
"--dest",
"-d",
prompt=True,
help="Destination address of the wallet.",
),
amount: float = typer.Option(
None,
"--amount",
"-a",
prompt=True,
help="Amount (in TAO) to transfer.",
),
wallet_name: str = Options.wallet_name,
wallet_path: str = Options.wallet_path,
wallet_hotkey: str = Options.wallet_hotkey,
network: str = Options.network,
chain: str = Options.chain,
):
"""
# wallet transfer
Executes the ``transfer`` command to transfer TAO tokens from one account to another on the Bittensor network.
This command is used for transactions between different accounts, enabling users to send tokens to other
participants on the network. The command displays the user's current balance before prompting for the amount
to transfer, ensuring transparency and accuracy in the transaction.
## Usage:
The command requires specifying the destination address (public key) and the amount of TAO to be transferred.
It checks for sufficient balance and prompts for confirmation before proceeding with the transaction.
### Example usage:
```
btcli wallet transfer --dest 5Dp8... --amount 100
```
#### Note:
This command is crucial for executing token transfers within the Bittensor network. Users should verify the
destination address and amount before confirming the transaction to avoid errors or loss of funds.
"""
wallet = self.wallet_ask(wallet_name, wallet_path, wallet_hotkey)
subtensor = self.initialize_chain(network, chain)
return self._run_command(
wallets.transfer(wallet, subtensor, destination, amount)
)
def wallet_swap_hotkey(
self,
wallet_name: Optional[str] = Options.wallet_name,
wallet_path: Optional[str] = Options.wallet_path,
wallet_hotkey: Optional[str] = Options.wallet_hotkey,
network: Optional[str] = Options.network,
chain: Optional[str] = Options.chain,
destination_hotkey_name: Optional[str] = typer.Argument(
help="Destination hotkey name."
),
):
"""
# wallet swap-hotkey
Executes the `swap_hotkey` command to swap the hotkeys for a neuron on the network.
## Usage:
The command is used to swap the hotkey of a wallet for another hotkey on that same wallet.
### Example usage:
```
btcli wallet swap_hotkey new_hotkey --wallet-name your_wallet_name --wallet-hotkey original_hotkey
```
"""
original_wallet = self.wallet_ask(wallet_name, wallet_path, wallet_hotkey)
new_wallet = self.wallet_ask(wallet_name, wallet_path, destination_hotkey_name)
self.initialize_chain(network, chain)
return self._run_command(
wallets.swap_hotkey(original_wallet, new_wallet, self.not_subtensor)
)
def wallet_inspect(
self,
all_wallets: bool = typer.Option(
False,
"--all",
"--all-wallets",
"-a",
help="Inspect all wallets within specified path.",
),
wallet_name: str = Options.wallet_name,
wallet_path: str = Options.wallet_path,
wallet_hotkey: str = Options.wallet_hotkey,
network: str = Options.network,
chain: str = Options.chain,
netuids: list[int] = Options.netuids,
):
"""
# wallet inspect
Executes the ``inspect`` command, which compiles and displays a detailed report of a user's wallet pairs
(coldkey, hotkey) on the Bittensor network.
This report includes balance and staking information for both the coldkey and hotkey associated with the wallet.
The command gathers data on:
- Coldkey balance and delegated stakes.
- Hotkey stake and emissions per neuron on the network.
- Delegate names and details fetched from the network.
The resulting table includes columns for:
- **Coldkey**: The coldkey associated with the user's wallet.
- **Balance**: The balance of the coldkey.
- **Delegate**: The name of the delegate to which the coldkey has staked funds.
- **Stake**: The amount of stake held by both the coldkey and hotkey.
- **Emission**: The emission or rewards earned from staking.
- **Netuid**: The network unique identifier of the subnet where the hotkey is active.
- **Hotkey**: The hotkey associated with the neuron on the network.
## Usage:
This command can be used to inspect a single wallet or all wallets located within a
specified path. It is useful for a comprehensive overview of a user's participation
and performance in the Bittensor network.
#### Example usage::
```
btcli wallet inspect
```
```
btcli wallet inspect --all -n 1 -n 2 -n 3
```
#### Note:
The `inspect` command is for displaying information only and does not perform any
transactions or state changes on the Bittensor network. It is intended to be used as
part of the Bittensor CLI and not as a standalone function within user code.
"""
# if all-wallets is entered, ask for path
if all_wallets:
if not wallet_path:
wallet_path = Prompt.ask(
"Enter the path of the wallets", default=defaults.wallet.path
)
wallet = self.wallet_ask(wallet_name, wallet_path, wallet_hotkey)
self.initialize_chain(network, chain)
return self._run_command(
wallets.inspect(
wallet,
self.not_subtensor,
netuids_filter=netuids,
all_wallets=all_wallets,
)
)
def wallet_faucet(
self,
wallet_name: Optional[str] = Options.wallet_name,
wallet_path: Optional[str] = Options.wallet_path,
wallet_hotkey: Optional[str] = Options.wallet_hotkey,
network: Optional[str] = Options.network,
chain: Optional[str] = Options.chain,
# TODO add the following to config
processors: Optional[int] = typer.Option(
defaults.pow_register.num_processes,
"-processors",
"-p",
help="Number of processors to use for POW registration.",
),
update_interval: Optional[int] = typer.Option(
defaults.pow_register.update_interval,
"-update-interval",
"-u",
help="The number of nonces to process before checking for next block during registration",
),
output_in_place: Optional[bool] = typer.Option(
defaults.pow_register.output_in_place,
help="Whether to output the registration statistics in-place.",
),
verbose: Optional[bool] = typer.Option(
defaults.pow_register.verbose,
"--verbose",
"-v",
help="Whether to output the registration statistics verbosely.",
),
use_cuda: Optional[bool] = typer.Option(
defaults.pow_register.cuda.use_cuda,
"--use-cuda/--no-use-cuda",
"--cuda/--no-cuda",
help="Set flag to use CUDA to pow_register.",
),
dev_id: Optional[int] = typer.Option(
defaults.pow_register.cuda.dev_id,
"--dev-id",
"-d",
help="Set the CUDA device id(s). Goes by the order of speed. (i.e. 0 is the fastest).",
),
threads_per_block: Optional[int] = typer.Option(
defaults.pow_register.cuda.tpb,
"--threads-per-block",
"-tbp",
help="Set the number of Threads Per Block for CUDA.",
),
max_successes: Optional[int] = typer.Option(
3,
"--max-successes",
help="Set the maximum number of times to successfully run the faucet for this command.",
),
):
"""
# wallet faucet
Executes the `faucet` command to obtain test TAO tokens by performing Proof of Work (PoW).
This command is particularly useful for users who need test tokens for operations on a local chain.
## IMPORTANT:
**THIS COMMAND IS DISABLED ON FINNEY AND TESTNET.**
## Usage:
The command uses the PoW mechanism to validate the user's effort and rewards them with test TAO tokens. It is
typically used in local chain environments where real value transactions are not necessary.
### Example usage:
```
btcli wallet faucet --faucet.num_processes 4 --faucet.cuda.use_cuda
```
#### Note:
This command is meant for use in local environments where users can experiment with the network without using
real TAO tokens. It's important for users to have the necessary hardware setup, especially when opting for
CUDA-based GPU calculations. It is currently disabled on testnet and finney. You must use this on a local chain.
"""
wallet = self.wallet_ask(wallet_name, wallet_path, wallet_hotkey)
return self._run_command(
wallets.faucet(
wallet,
self.initialize_chain(network, chain),
threads_per_block,
update_interval,
processors,
use_cuda,
dev_id,
output_in_place,
verbose,
max_successes,
)
)
def wallet_regen_coldkey(
self,
wallet_name: Optional[str] = Options.wallet_name,
wallet_path: Optional[str] = Options.wallet_path,
wallet_hotkey: Optional[str] = Options.wallet_hotkey,
mnemonic: Optional[str] = Options.mnemonic,
seed: Optional[str] = Options.seed,
json: Optional[str] = Options.json,
json_password: Optional[str] = Options.json_password,
use_password: Optional[bool] = Options.use_password,
overwrite_coldkey: Optional[bool] = Options.overwrite_coldkey,
):
"""
# wallet regen-coldkey
Executes the `regen-coldkey` command to regenerate a coldkey for a wallet on the Bittensor network.
This command is used to create a new coldkey from an existing mnemonic, seed, or JSON file.
## Usage:
Users can specify a mnemonic, a seed string, or a JSON file path to regenerate a coldkey.
The command supports optional password protection for the generated key and can overwrite an existing coldkey.
### Example usage:
```
btcli wallet regen-coldkey --mnemonic "word1 word2 ... word12"
```
### Note: This command is critical for users who need to regenerate their coldkey, possibly for recovery or
security reasons. It should be used with caution to avoid overwriting existing keys unintentionally.
"""
wallet = self.wallet_ask(wallet_name, wallet_path, wallet_hotkey, validate=False)
mnemonic, seed, json, json_password = get_creation_data(
mnemonic, seed, json, json_password
)
return self._run_command(
wallets.regen_coldkey(
wallet,
mnemonic,
seed,
json,
json_password,
use_password,
overwrite_coldkey,
)
)
def wallet_regen_coldkey_pub(
self,
wallet_name: Optional[str] = Options.wallet_name,
wallet_path: Optional[str] = Options.wallet_path,
wallet_hotkey: Optional[str] = Options.wallet_hotkey,
public_key_hex: Optional[str] = Options.public_hex_key,
ss58_address: Optional[str] = Options.ss58_address,
overwrite_coldkeypub: Optional[bool] = typer.Option(
False,
help="Overwrites the existing coldkeypub file with the new one.",
prompt=True,
),
):
"""
# wallet regen-coldkeypub
Executes the `regen-coldkeypub` command to regenerate the public part of a coldkey (coldkeypub) for a wallet
on the Bittensor network.
This command is used when a user needs to recreate their coldkeypub from an existing public key or SS58 address.
## Usage:
The command requires either a public key in hexadecimal format or an ``SS58`` address to regenerate the
coldkeypub. It optionally allows overwriting an existing coldkeypub file.
### Example usage:
```
btcli wallet regen_coldkeypub --ss58_address 5DkQ4...
```
### Note:
This command is particularly useful for users who need to regenerate their coldkeypub, perhaps due to file
corruption or loss. It is a recovery-focused utility that ensures continued access to wallet
functionalities.
"""
wallet = self.wallet_ask(wallet_name, wallet_path, wallet_hotkey, validate=False)
if not ss58_address and not public_key_hex:
prompt_answer = typer.prompt(
"Enter the ss58_address or the public key in hex"
)
if prompt_answer.startswith("0x"):
public_key_hex = prompt_answer
else:
ss58_address = prompt_answer
if not utils.is_valid_bittensor_address_or_public_key(
address=ss58_address if ss58_address else public_key_hex
):
rich.print("[red]Error: Invalid SS58 address or public key![/red]")
raise typer.Exit()
return self._run_command(
wallets.regen_coldkey_pub(
wallet, ss58_address, public_key_hex, overwrite_coldkeypub
)
)
def wallet_regen_hotkey(
self,
wallet_name: Optional[str] = Options.wallet_name,
wallet_path: Optional[str] = Options.wallet_path,
wallet_hotkey: Optional[str] = Options.wallet_hk_req,
mnemonic: Optional[str] = Options.mnemonic,
seed: Optional[str] = Options.seed,
json: Optional[str] = Options.json,
json_password: Optional[str] = Options.json_password,
use_password: Optional[bool] = Options.use_password,
overwrite_hotkey: Optional[bool] = Options.overwrite_hotkey,
):
"""
# wallet regen-hotkey
Executes the `regen-hotkey` command to regenerate a hotkey for a wallet on the Bittensor network.
Similar to regenerating a coldkey, this command creates a new hotkey from a mnemonic, seed, or JSON file.
## Usage:
Users can provide a mnemonic, seed string, or a JSON file to regenerate the hotkey.
The command supports optional password protection and can overwrite an existing hotkey.
### Example usage:
```
btcli wallet regen_hotkey --seed 0x1234...
```
### Note:
This command is essential for users who need to regenerate their hotkey, possibly for security upgrades or
key recovery.
It should be used cautiously to avoid accidental overwrites of existing keys.
"""