-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathstake.py
2778 lines (2524 loc) · 114 KB
/
stake.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
import asyncio
from functools import partial
from typing import TYPE_CHECKING, Optional, Sequence, Union, cast
import typer
from bittensor_wallet import Wallet
from bittensor_wallet.errors import KeyFileError
from rich.prompt import Confirm, FloatPrompt, Prompt
from rich.table import Table
from rich import box
from rich.progress import Progress, BarColumn, TextColumn
from rich.console import Console, Group
from rich.live import Live
from substrateinterface.exceptions import SubstrateRequestException
from bittensor_cli.src import COLOR_PALETTE
from bittensor_cli.src.bittensor.balances import Balance
from bittensor_cli.src.bittensor.chain_data import StakeInfo
from bittensor_cli.src.bittensor.utils import (
# TODO add back in caching
console,
err_console,
print_verbose,
print_error,
get_hotkey_wallets_for_wallet,
is_valid_ss58_address,
u16_normalized_float,
format_error_message,
group_subnets,
)
if TYPE_CHECKING:
from bittensor_cli.src.bittensor.subtensor_interface import SubtensorInterface
# Helpers and Extrinsics
async def _get_threshold_amount(
subtensor: "SubtensorInterface", block_hash: str
) -> Balance:
mrs = await subtensor.substrate.query(
module="SubtensorModule",
storage_function="NominatorMinRequiredStake",
block_hash=block_hash,
)
min_req_stake: Balance = Balance.from_rao(mrs)
return min_req_stake
async def _check_threshold_amount(
subtensor: "SubtensorInterface",
sb: Balance,
block_hash: str,
min_req_stake: Optional[Balance] = None,
) -> tuple[bool, Balance]:
"""
Checks if the new stake balance will be above the minimum required stake threshold.
:param sb: the balance to check for threshold limits.
:return: (success, threshold)
`True` if the staking balance is above the threshold, or `False` if the staking balance is below the
threshold.
The threshold balance required to stake.
"""
if not min_req_stake:
min_req_stake = await _get_threshold_amount(subtensor, block_hash)
if min_req_stake > sb:
return False, min_req_stake
else:
return True, min_req_stake
async def add_stake_extrinsic(
subtensor: "SubtensorInterface",
wallet: Wallet,
old_balance: Balance,
hotkey_ss58: Optional[str] = None,
amount: Optional[Balance] = None,
wait_for_inclusion: bool = True,
wait_for_finalization: bool = False,
prompt: bool = False,
) -> bool:
"""
Adds the specified amount of stake to passed hotkey `uid`.
:param subtensor: the initialized SubtensorInterface object to use
:param wallet: Bittensor wallet object.
:param old_balance: the balance prior to the staking
:param hotkey_ss58: The `ss58` address of the hotkey account to stake to defaults to the wallet's hotkey.
:param amount: Amount to stake as Bittensor balance, `None` if staking all.
: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 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`.
"""
# Decrypt keys,
try:
wallet.unlock_coldkey()
except KeyFileError:
err_console.print("Error decrypting coldkey (possibly incorrect password)")
return False
# Default to wallet's own hotkey if the value is not passed.
if hotkey_ss58 is None:
hotkey_ss58 = wallet.hotkey.ss58_address
# Flag to indicate if we are using the wallet's own hotkey.
own_hotkey: bool
with console.status(
f":satellite: Syncing with chain: [white]{subtensor}[/white] ...",
spinner="aesthetic",
) as status:
block_hash = await subtensor.substrate.get_chain_head()
# Get hotkey owner
print_verbose("Confirming hotkey owner", status)
hotkey_owner = await subtensor.get_hotkey_owner(
hotkey_ss58=hotkey_ss58, block_hash=block_hash
)
own_hotkey = wallet.coldkeypub.ss58_address == hotkey_owner
if not own_hotkey:
# This is not the wallet's own hotkey, so we are delegating.
if not await subtensor.is_hotkey_delegate(
hotkey_ss58, block_hash=block_hash
):
err_console.print(
f"Hotkey {hotkey_ss58} is not a delegate on the chain."
)
return False
# Get hotkey take
hk_result = await subtensor.substrate.query(
module="SubtensorModule",
storage_function="Delegates",
params=[hotkey_ss58],
block_hash=block_hash,
)
hotkey_take = u16_normalized_float(hk_result or 0)
else:
hotkey_take = None
# Get current stake
print_verbose("Fetching current stake", status)
old_stake = await subtensor.get_stake_for_coldkey_and_hotkey(
coldkey_ss58=wallet.coldkeypub.ss58_address,
hotkey_ss58=hotkey_ss58,
block_hash=block_hash,
)
print_verbose("Fetching existential deposit", status)
# Grab the existential deposit.
existential_deposit = await subtensor.get_existential_deposit()
# Convert to bittensor.Balance
if amount is None:
# Stake it all.
staking_balance = Balance.from_tao(old_balance.tao)
else:
staking_balance = Balance.from_tao(amount)
# Leave existential balance to keep key alive.
if staking_balance > old_balance - existential_deposit:
# If we are staking all, we need to leave at least the existential deposit.
staking_balance = old_balance - existential_deposit
else:
staking_balance = staking_balance
# Check enough to stake.
if staking_balance > old_balance:
err_console.print(
f":cross_mark: [red]Not enough stake[/red]:[bold white]\n"
f"\tbalance:\t{old_balance}\n"
f"\tamount:\t{staking_balance}\n"
f"\tcoldkey:\t{wallet.name}[/bold white]"
)
return False
# If nominating, we need to check if the new stake balance will be above the minimum required stake threshold.
if not own_hotkey:
new_stake_balance = old_stake + staking_balance
print_verbose("Fetching threshold amount")
is_above_threshold, threshold = await _check_threshold_amount(
subtensor, new_stake_balance, block_hash
)
if not is_above_threshold:
err_console.print(
f":cross_mark: [red]New stake balance of {new_stake_balance} is below the minimum required nomination"
f" stake threshold {threshold}.[/red]"
)
return False
# Ask before moving on.
if prompt:
if not own_hotkey:
# We are delegating.
if not Confirm.ask(
f"Do you want to delegate:[bold white]\n"
f"\tamount: {staking_balance}\n"
f"\tto: {hotkey_ss58}\n"
f"\ttake: {hotkey_take}\n[/bold white]"
f"\towner: {hotkey_owner}\n"
):
return False
else:
if not Confirm.ask(
f"Do you want to stake:[bold white]\n"
f"\tamount: {staking_balance}\n"
f"\tto: {wallet.hotkey_str}\n"
f"\taddress: {hotkey_ss58}[/bold white]\n"
):
return False
with console.status(
f":satellite: Staking to: [bold white]{subtensor}[/bold white] ...",
spinner="earth",
):
call = await subtensor.substrate.compose_call(
call_module="SubtensorModule",
call_function="add_stake",
call_params={"hotkey": hotkey_ss58, "amount_staked": staking_balance.rao},
)
staking_response, err_msg = await subtensor.sign_and_send_extrinsic(
call, wallet, wait_for_inclusion, wait_for_finalization
)
if staking_response is True: # If we successfully staked.
# We only wait here if we expect finalization.
if not wait_for_finalization and not wait_for_inclusion:
return True
console.print(":white_heavy_check_mark: [green]Finalized[/green]")
with console.status(
f":satellite: Checking Balance on: [white]{subtensor}[/white] ..."
):
new_block_hash = await subtensor.substrate.get_chain_head()
new_balance, new_stake = await asyncio.gather(
subtensor.get_balance(
wallet.coldkeypub.ss58_address, block_hash=new_block_hash
),
subtensor.get_stake_for_coldkey_and_hotkey(
coldkey_ss58=wallet.coldkeypub.ss58_address,
hotkey_ss58=hotkey_ss58,
block_hash=new_block_hash,
),
)
console.print(
f"Balance:\n"
f"\t[blue]{old_balance}[/blue] :arrow_right: "
f"[green]{new_balance[wallet.coldkeypub.ss58_address]}[/green]"
)
console.print(
f"Stake:\n"
f"\t[blue]{old_stake}[/blue] :arrow_right: [green]{new_stake}[/green]"
)
return True
else:
err_console.print(f":cross_mark: [red]Failed[/red]: {err_msg}")
return False
async def add_stake_multiple_extrinsic(
subtensor: "SubtensorInterface",
wallet: Wallet,
old_balance: Balance,
hotkey_ss58s: list[str],
amounts: Optional[list[Balance]] = None,
wait_for_inclusion: bool = True,
wait_for_finalization: bool = False,
prompt: bool = False,
) -> bool:
"""Adds stake to each ``hotkey_ss58`` in the list, using each amount, from a common coldkey.
:param subtensor: The initialized SubtensorInterface object.
:param wallet: Bittensor wallet object for the coldkey.
:param old_balance: The balance of the wallet prior to staking.
:param hotkey_ss58s: List of hotkeys to stake to.
:param amounts: List of amounts to stake. If `None`, stake all to the first hotkey.
: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 prompt: If `True`, the call waits for confirmation from the user before proceeding.
:return: success: `True` if extrinsic was finalized or included in the block. `True` if any wallet was staked. If
we did not wait for finalization/inclusion, the response is `True`.
"""
if len(hotkey_ss58s) == 0:
return True
if amounts is not None and len(amounts) != len(hotkey_ss58s):
raise ValueError("amounts must be a list of the same length as hotkey_ss58s")
new_amounts: Sequence[Optional[Balance]]
if amounts is None:
new_amounts = [None] * len(hotkey_ss58s)
else:
new_amounts = [Balance.from_tao(amount) for amount in amounts]
if sum(amount.tao for amount in new_amounts) == 0:
# Staking 0 tao
return True
# Decrypt coldkey.
try:
wallet.unlock_coldkey()
except KeyFileError:
err_console.print("Error decrypting coldkey (possibly incorrect password)")
return False
with console.status(
f":satellite: Syncing with chain: [white]{subtensor}[/white] ..."
):
block_hash = await subtensor.substrate.get_chain_head()
old_stakes = await asyncio.gather(
*[
subtensor.get_stake_for_coldkey_and_hotkey(
hk, wallet.coldkeypub.ss58_address, block_hash=block_hash
)
for hk in hotkey_ss58s
]
)
# Remove existential balance to keep key alive.
## Keys must maintain a balance of at least 1000 rao to stay alive.
total_staking_rao = sum(
[amount.rao if amount is not None else 0 for amount in new_amounts]
)
if total_staking_rao == 0:
# Staking all to the first wallet.
if old_balance.rao > 1000:
old_balance -= Balance.from_rao(1000)
elif total_staking_rao < 1000:
# Staking less than 1000 rao to the wallets.
pass
else:
# Staking more than 1000 rao to the wallets.
## Reduce the amount to stake to each wallet to keep the balance above 1000 rao.
percent_reduction = 1 - (1000 / total_staking_rao)
new_amounts = [
Balance.from_tao(amount.tao * percent_reduction)
for amount in cast(Sequence[Balance], new_amounts)
]
successful_stakes = 0
for idx, (hotkey_ss58, amount, old_stake) in enumerate(
zip(hotkey_ss58s, new_amounts, old_stakes)
):
staking_all = False
# Convert to bittensor.Balance
if amount is None:
# Stake it all.
staking_balance = Balance.from_tao(old_balance.tao)
staking_all = True
else:
# Amounts are cast to balance earlier in the function
assert isinstance(amount, Balance)
staking_balance = amount
# Check enough to stake
if staking_balance > old_balance:
err_console.print(
f":cross_mark: [red]Not enough balance[/red]:"
f" [green]{old_balance}[/green] to stake: [blue]{staking_balance}[/blue]"
f" from coldkey: [white]{wallet.name}[/white]"
)
continue
# Ask before moving on.
if prompt:
if not Confirm.ask(
f"Do you want to stake:\n"
f"\t[bold white]amount: {staking_balance}\n"
f"\thotkey: {wallet.hotkey_str}[/bold white ]?"
):
continue
call = await subtensor.substrate.compose_call(
call_module="SubtensorModule",
call_function="add_stake",
call_params={"hotkey": hotkey_ss58, "amount_staked": staking_balance.rao},
)
staking_response, err_msg = await subtensor.sign_and_send_extrinsic(
call, wallet, wait_for_inclusion, wait_for_finalization
)
if staking_response is True: # If we successfully staked.
# We only wait here if we expect finalization.
if idx < len(hotkey_ss58s) - 1:
# Wait for tx rate limit.
tx_query = await subtensor.substrate.query(
module="SubtensorModule",
storage_function="TxRateLimit",
block_hash=block_hash,
)
tx_rate_limit_blocks: int = tx_query
if tx_rate_limit_blocks > 0:
with console.status(
f":hourglass: [yellow]Waiting for tx rate limit:"
f" [white]{tx_rate_limit_blocks}[/white] blocks[/yellow]"
):
await asyncio.sleep(
tx_rate_limit_blocks * 12
) # 12 seconds per block
if not wait_for_finalization and not wait_for_inclusion:
old_balance -= staking_balance
successful_stakes += 1
if staking_all:
# If staked all, no need to continue
break
continue
console.print(":white_heavy_check_mark: [green]Finalized[/green]")
new_block_hash = await subtensor.substrate.get_chain_head()
new_stake, new_balance_ = await asyncio.gather(
subtensor.get_stake_for_coldkey_and_hotkey(
coldkey_ss58=wallet.coldkeypub.ss58_address,
hotkey_ss58=hotkey_ss58,
block_hash=new_block_hash,
),
subtensor.get_balance(
wallet.coldkeypub.ss58_address, block_hash=new_block_hash
),
)
new_balance = new_balance_[wallet.coldkeypub.ss58_address]
console.print(
"Stake ({}): [blue]{}[/blue] :arrow_right: [green]{}[/green]".format(
hotkey_ss58, old_stake, new_stake
)
)
old_balance = new_balance
successful_stakes += 1
if staking_all:
# If staked all, no need to continue
break
else:
err_console.print(f":cross_mark: [red]Failed[/red]: {err_msg}")
continue
if successful_stakes != 0:
with console.status(
f":satellite: Checking Balance on: ([white]{subtensor}[/white] ..."
):
new_balance_ = await subtensor.get_balance(
wallet.coldkeypub.ss58_address, reuse_block=False
)
new_balance = new_balance_[wallet.coldkeypub.ss58_address]
console.print(
f"Balance: [blue]{old_balance}[/blue] :arrow_right: [green]{new_balance}[/green]"
)
return True
return False
async def unstake_extrinsic(
subtensor: "SubtensorInterface",
wallet: Wallet,
hotkey_ss58: Optional[str] = None,
amount: Optional[Balance] = None,
wait_for_inclusion: bool = True,
wait_for_finalization: bool = False,
prompt: bool = False,
) -> bool:
"""Removes stake into the wallet coldkey from the specified hotkey ``uid``.
:param subtensor: the initialized SubtensorInterface object to use
:param wallet: Bittensor wallet object.
:param hotkey_ss58: The `ss58` address of the hotkey to unstake from. By default, the wallet hotkey is used.
:param amount: Amount to stake as Bittensor balance, or `None` is unstaking all
: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 prompt: If `True`, the call waits for confirmation from the user before proceeding.
:return: success: `True` if extrinsic was finalized or included in the block. If we did not wait for
finalization/inclusion, the response is `True`.
"""
# Decrypt keys,
try:
wallet.unlock_coldkey()
except KeyFileError:
err_console.print("Error decrypting coldkey (possibly incorrect password)")
return False
if hotkey_ss58 is None:
hotkey_ss58 = wallet.hotkey.ss58_address # Default to wallet's own hotkey.
with console.status(
f":satellite: Syncing with chain: [white]{subtensor}[/white] ...",
spinner="aesthetic",
) as status:
print_verbose("Fetching balance and stake", status)
block_hash = await subtensor.substrate.get_chain_head()
old_balance, old_stake, hotkey_owner = await asyncio.gather(
subtensor.get_balance(
wallet.coldkeypub.ss58_address, block_hash=block_hash
),
subtensor.get_stake_for_coldkey_and_hotkey(
coldkey_ss58=wallet.coldkeypub.ss58_address,
hotkey_ss58=hotkey_ss58,
block_hash=block_hash,
),
subtensor.get_hotkey_owner(hotkey_ss58, block_hash),
)
own_hotkey: bool = wallet.coldkeypub.ss58_address == hotkey_owner
# Convert to bittensor.Balance
if amount is None:
# Unstake it all.
unstaking_balance = old_stake
else:
unstaking_balance = Balance.from_tao(amount)
# Check enough to unstake.
stake_on_uid = old_stake
if unstaking_balance > stake_on_uid:
err_console.print(
f":cross_mark: [red]Not enough stake[/red]: "
f"[green]{stake_on_uid}[/green] to unstake: "
f"[blue]{unstaking_balance}[/blue] from hotkey:"
f" [white]{wallet.hotkey_str}[/white]"
)
return False
print_verbose("Fetching threshold amount")
# If nomination stake, check threshold.
if not own_hotkey and not await _check_threshold_amount(
subtensor=subtensor,
sb=(stake_on_uid - unstaking_balance),
block_hash=block_hash,
):
console.print(
":warning: [yellow]This action will unstake the entire staked balance![/yellow]"
)
unstaking_balance = stake_on_uid
# Ask before moving on.
if prompt:
if not Confirm.ask(
f"Do you want to unstake:\n"
f"[bold white]\tamount: {unstaking_balance}\n"
f"\thotkey: {wallet.hotkey_str}[/bold white ]?"
):
return False
with console.status(
f":satellite: Unstaking from chain: [white]{subtensor}[/white] ...",
spinner="earth",
):
call = await subtensor.substrate.compose_call(
call_module="SubtensorModule",
call_function="remove_stake",
call_params={
"hotkey": hotkey_ss58,
"amount_unstaked": unstaking_balance.rao,
},
)
staking_response, err_msg = await subtensor.sign_and_send_extrinsic(
call, wallet, wait_for_inclusion, wait_for_finalization
)
if staking_response is True: # If we successfully unstaked.
# We only wait here if we expect finalization.
if not wait_for_finalization and not wait_for_inclusion:
return True
console.print(":white_heavy_check_mark: [green]Finalized[/green]")
with console.status(
f":satellite: Checking Balance on: [white]{subtensor}[/white] ..."
):
new_block_hash = await subtensor.substrate.get_chain_head()
new_balance, new_stake = await asyncio.gather(
subtensor.get_balance(
wallet.coldkeypub.ss58_address, block_hash=new_block_hash
),
subtensor.get_stake_for_coldkey_and_hotkey(
hotkey_ss58, wallet.coldkeypub.ss58_address, new_block_hash
),
)
console.print(
f"Balance:\n"
f" [blue]{old_balance[wallet.coldkeypub.ss58_address]}[/blue] :arrow_right:"
f" [green]{new_balance[wallet.coldkeypub.ss58_address]}[/green]"
)
console.print(
f"Stake:\n [blue]{old_stake}[/blue] :arrow_right: [green]{new_stake}[/green]"
)
return True
else:
err_console.print(f":cross_mark: [red]Failed[/red]: {err_msg}")
return False
async def unstake_multiple_extrinsic(
subtensor: "SubtensorInterface",
wallet: Wallet,
hotkey_ss58s: list[str],
amounts: Optional[list[Union[Balance, float]]] = None,
wait_for_inclusion: bool = True,
wait_for_finalization: bool = False,
prompt: bool = False,
) -> bool:
"""
Removes stake from each `hotkey_ss58` in the list, using each amount, to a common coldkey.
:param subtensor: the initialized SubtensorInterface object to use
:param wallet: The wallet with the coldkey to unstake to.
:param hotkey_ss58s: List of hotkeys to unstake from.
:param amounts: List of amounts to unstake. If ``None``, unstake all.
: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 prompt: If `True`, the call waits for confirmation from the user before proceeding.
:return: success: `True` if extrinsic was finalized or included in the block. Flag is `True` if any wallet was
unstaked. If we did not wait for finalization/inclusion, the response is `True`.
"""
if not isinstance(hotkey_ss58s, list) or not all(
isinstance(hotkey_ss58, str) for hotkey_ss58 in hotkey_ss58s
):
raise TypeError("hotkey_ss58s must be a list of str")
if len(hotkey_ss58s) == 0:
return True
if amounts is not None and len(amounts) != len(hotkey_ss58s):
raise ValueError("amounts must be a list of the same length as hotkey_ss58s")
if amounts is not None and not all(
isinstance(amount, (Balance, float)) for amount in amounts
):
raise TypeError(
"amounts must be a [list of bittensor.Balance or float] or None"
)
new_amounts: Sequence[Optional[Balance]]
if amounts is None:
new_amounts = [None] * len(hotkey_ss58s)
else:
new_amounts = [
Balance(amount) if not isinstance(amount, Balance) else amount
for amount in (amounts or [None] * len(hotkey_ss58s))
]
if sum(amount.tao for amount in new_amounts if amount is not None) == 0:
return True
# Unlock coldkey.
try:
wallet.unlock_coldkey()
except KeyFileError:
err_console.print("Error decrypting coldkey (possibly incorrect password)")
return False
with console.status(
f":satellite: Syncing with chain: [white]{subtensor}[/white] ..."
):
block_hash = await subtensor.substrate.get_chain_head()
old_balance_ = subtensor.get_balance(
wallet.coldkeypub.ss58_address, block_hash=block_hash
)
old_stakes_ = asyncio.gather(
*[
subtensor.get_stake_for_coldkey_and_hotkey(
h, wallet.coldkeypub.ss58_address, block_hash
)
for h in hotkey_ss58s
]
)
hotkey_owners_ = asyncio.gather(
*[subtensor.get_hotkey_owner(h, block_hash) for h in hotkey_ss58s]
)
old_balance, old_stakes, hotkey_owners, threshold = await asyncio.gather(
old_balance_,
old_stakes_,
hotkey_owners_,
_get_threshold_amount(subtensor, block_hash),
)
own_hotkeys = [
wallet.coldkeypub.ss58_address == hotkey_owner
for hotkey_owner in hotkey_owners
]
successful_unstakes = 0
for idx, (hotkey_ss58, amount, old_stake, own_hotkey) in enumerate(
zip(hotkey_ss58s, new_amounts, old_stakes, own_hotkeys)
):
# Covert to bittensor.Balance
if amount is None:
# Unstake it all.
unstaking_balance = old_stake
else:
unstaking_balance = amount
# Check enough to unstake.
stake_on_uid = old_stake
if unstaking_balance > stake_on_uid:
err_console.print(
f":cross_mark: [red]Not enough stake[/red]:"
f" [green]{stake_on_uid}[/green] to unstake:"
f" [blue]{unstaking_balance}[/blue] from hotkey:"
f" [white]{wallet.hotkey_str}[/white]"
)
continue
# If nomination stake, check threshold.
if (
not own_hotkey
and (
await _check_threshold_amount(
subtensor=subtensor,
sb=(stake_on_uid - unstaking_balance),
block_hash=block_hash,
min_req_stake=threshold,
)
)[0]
is False
):
console.print(
":warning: [yellow]This action will unstake the entire staked balance![/yellow]"
)
unstaking_balance = stake_on_uid
# Ask before moving on.
if prompt:
if not Confirm.ask(
f"Do you want to unstake:\n"
f"[bold white]\tamount: {unstaking_balance}\n"
f"ss58: {hotkey_ss58}[/bold white ]?"
):
continue
with console.status(
f":satellite: Unstaking from chain: [white]{subtensor}[/white] ..."
):
call = await subtensor.substrate.compose_call(
call_module="SubtensorModule",
call_function="remove_stake",
call_params={
"hotkey": hotkey_ss58,
"amount_unstaked": unstaking_balance.rao,
},
)
staking_response, err_msg = await subtensor.sign_and_send_extrinsic(
call, wallet, wait_for_inclusion, wait_for_finalization
)
if staking_response is True: # If we successfully unstaked.
# We only wait here if we expect finalization.
if idx < len(hotkey_ss58s) - 1:
# Wait for tx rate limit.
tx_query = await subtensor.substrate.query(
module="SubtensorModule",
storage_function="TxRateLimit",
block_hash=block_hash,
)
tx_rate_limit_blocks: int = tx_query
# TODO: Handle in-case we have fast blocks
if tx_rate_limit_blocks > 0:
console.print(
":hourglass: [yellow]Waiting for tx rate limit:"
f" [white]{tx_rate_limit_blocks}[/white] blocks,"
f" estimated time: [white]{tx_rate_limit_blocks * 12} [/white] seconds[/yellow]"
)
await asyncio.sleep(
tx_rate_limit_blocks * 12
) # 12 seconds per block
if not wait_for_finalization and not wait_for_inclusion:
successful_unstakes += 1
continue
console.print(":white_heavy_check_mark: [green]Finalized[/green]")
with console.status(
f":satellite: Checking stake balance on: [white]{subtensor}[/white] ..."
):
new_stake = await subtensor.get_stake_for_coldkey_and_hotkey(
coldkey_ss58=wallet.coldkeypub.ss58_address,
hotkey_ss58=hotkey_ss58,
block_hash=(await subtensor.substrate.get_chain_head()),
)
console.print(
"Stake ({}): [blue]{}[/blue] :arrow_right: [green]{}[/green]".format(
hotkey_ss58, stake_on_uid, new_stake
)
)
successful_unstakes += 1
else:
err_console.print(":cross_mark: [red]Failed[/red]: Unknown Error.")
continue
if successful_unstakes != 0:
with console.status(
f":satellite: Checking balance on: ([white]{subtensor}[/white] ..."
):
new_balance = await subtensor.get_balance(wallet.coldkeypub.ss58_address)
console.print(
f"Balance: [blue]{old_balance[wallet.coldkeypub.ss58_address]}[/blue]"
f" :arrow_right: [green]{new_balance[wallet.coldkeypub.ss58_address]}[/green]"
)
return True
return False
# Commands
async def stake_add(
wallet: Wallet,
subtensor: "SubtensorInterface",
netuid: Optional[int],
stake_all: bool,
amount: float,
delegate: bool,
prompt: bool,
max_stake: float,
all_hotkeys: bool,
include_hotkeys: list[str],
exclude_hotkeys: list[str],
):
"""
Args:
wallet: wallet object
subtensor: SubtensorInterface object
netuid: the netuid to stake to (None indicates all subnets)
stake_all: whether to stake all available balance
amount: specified amount of balance to stake
delegate: whether to delegate stake, currently unused
prompt: whether to prompt the user
max_stake: maximum amount to stake (used in combination with stake_all), currently unused
all_hotkeys: whether to stake all hotkeys
include_hotkeys: list of hotkeys to include in staking process (if not specifying `--all`)
exclude_hotkeys: list of hotkeys to exclude in staking (if specifying `--all`)
Returns:
"""
netuids = (
[int(netuid)]
if netuid is not None
else await subtensor.get_all_subnet_netuids()
)
# Init the table.
table = Table(
title=f"\n[{COLOR_PALETTE['GENERAL']['HEADER']}]Staking to: \nWallet: [{COLOR_PALETTE['GENERAL']['COLDKEY']}]{wallet.name}[/{COLOR_PALETTE['GENERAL']['COLDKEY']}], Coldkey ss58: [{COLOR_PALETTE['GENERAL']['COLDKEY']}]{wallet.coldkeypub.ss58_address}[/{COLOR_PALETTE['GENERAL']['COLDKEY']}]\nNetwork: {subtensor.network}[/{COLOR_PALETTE['GENERAL']['HEADER']}]\n",
show_footer=True,
show_edge=False,
header_style="bold white",
border_style="bright_black",
style="bold",
title_justify="center",
show_lines=False,
pad_edge=True,
)
# Determine the amount we are staking.
rows = []
stake_amount_balance = []
current_stake_balances = []
current_wallet_balance_ = await subtensor.get_balance(
wallet.coldkeypub.ss58_address
)
current_wallet_balance = current_wallet_balance_[
wallet.coldkeypub.ss58_address
].set_unit(0)
remaining_wallet_balance = current_wallet_balance
max_slippage = 0.0
hotkeys_to_stake_to: list[tuple[Optional[str], str]] = []
if all_hotkeys:
# Stake to all hotkeys.
all_hotkeys_: list[Wallet] = get_hotkey_wallets_for_wallet(wallet=wallet)
# Get the hotkeys to exclude. (d)efault to no exclusions.
# Exclude hotkeys that are specified.
hotkeys_to_stake_to = [
(wallet.hotkey_str, wallet.hotkey.ss58_address)
for wallet in all_hotkeys_
if wallet.hotkey_str not in exclude_hotkeys
] # definitely wallets
elif include_hotkeys:
print_verbose("Staking to only included hotkeys")
# Stake to specific hotkeys.
for hotkey_ss58_or_hotkey_name in include_hotkeys:
if is_valid_ss58_address(hotkey_ss58_or_hotkey_name):
# If the hotkey is a valid ss58 address, we add it to the list.
hotkeys_to_stake_to.append((None, hotkey_ss58_or_hotkey_name))
else:
# If the hotkey is not a valid ss58 address, we assume it is a hotkey name.
# We then get the hotkey from the wallet and add it to the list.
wallet_ = Wallet(
path=wallet.path,
name=wallet.name,
hotkey=hotkey_ss58_or_hotkey_name,
)
hotkeys_to_stake_to.append(
(wallet_.hotkey_str, wallet_.hotkey.ss58_address)
)
else:
# Only config.wallet.hotkey is specified.
# so we stake to that single hotkey.
print_verbose(
f"Staking to hotkey: ({wallet.hotkey_str}) in wallet: ({wallet.name})"
)
assert wallet.hotkey is not None
hotkey_ss58_or_name = wallet.hotkey.ss58_address
hotkeys_to_stake_to = [(None, hotkey_ss58_or_name)]
starting_chain_head = await subtensor.substrate.get_chain_head()
all_dynamic_info, initial_stake_balances = await asyncio.gather(
asyncio.gather(
*[
subtensor.get_subnet_dynamic_info(x, starting_chain_head)
for x in netuids
]
),
subtensor.multi_get_stake_for_coldkey_and_hotkey_on_netuid(
hotkey_ss58s=[x[1] for x in hotkeys_to_stake_to],
coldkey_ss58=wallet.coldkeypub.ss58_address,
netuids=netuids,
block_hash=starting_chain_head,
),
)
for hk_name, hk_ss58 in hotkeys_to_stake_to:
if not is_valid_ss58_address(hk_ss58):
print_error(
f"The entered hotkey ss58 address is incorrect: {hk_name} | {hk_ss58}"
)
return False
for hotkey in hotkeys_to_stake_to:
for netuid, dynamic_info in zip(netuids, all_dynamic_info):
# Check that the subnet exists.
if not dynamic_info:
err_console.print(f"Subnet with netuid: {netuid} does not exist.")
continue
current_stake_balances.append(initial_stake_balances[hotkey[1]][netuid])
# Get the amount.
amount_to_stake_as_balance = Balance(0)
if amount:
amount_to_stake_as_balance = Balance.from_tao(amount)
elif stake_all:
amount_to_stake_as_balance = current_wallet_balance / len(netuids)
elif not amount and not max_stake:
if Confirm.ask(f"Stake all: [bold]{remaining_wallet_balance}[/bold]?"):
amount_to_stake_as_balance = remaining_wallet_balance
else:
try:
amount = FloatPrompt.ask(
f"Enter amount to stake in {Balance.get_unit(0)} to subnet: {netuid}"
)
amount_to_stake_as_balance = Balance.from_tao(amount)
except ValueError:
err_console.print(
f":cross_mark:[red]Invalid amount: {amount}[/red]"
)
return False
stake_amount_balance.append(amount_to_stake_as_balance)
# Check enough to stake.
amount_to_stake_as_balance.set_unit(0)
if amount_to_stake_as_balance > remaining_wallet_balance:
err_console.print(
f"[red]Not enough stake[/red]:[bold white]\n wallet balance:{remaining_wallet_balance} < "
f"staking amount: {amount_to_stake_as_balance}[/bold white]"
)
return False
remaining_wallet_balance -= amount_to_stake_as_balance
# Slippage warning
received_amount, slippage = dynamic_info.tao_to_alpha_with_slippage(
amount_to_stake_as_balance
)
if dynamic_info.is_dynamic:
slippage_pct_float = (
100 * float(slippage) / float(slippage + received_amount)
if slippage + received_amount != 0
else 0
)