-
Notifications
You must be signed in to change notification settings - Fork 87
Expand file tree
/
Copy pathutils.py
More file actions
1908 lines (1608 loc) · 60.9 KB
/
utils.py
File metadata and controls
1908 lines (1608 loc) · 60.9 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
import ast
import json
from collections import namedtuple
import math
import os
import sqlite3
import webbrowser
from contextlib import contextmanager
from pathlib import Path
from typing import TYPE_CHECKING, Any, Collection, Optional, Union, Callable, Generator
from urllib.parse import urlparse
from functools import partial
import re
import aiohttp
from async_substrate_interface import AsyncExtrinsicReceipt
from bittensor_wallet import Wallet, Keypair
from bittensor_wallet.utils import SS58_FORMAT
from bittensor_wallet.errors import KeyFileError, PasswordError
from bittensor_wallet import utils
from jinja2 import Template, Environment, PackageLoader, select_autoescape
from markupsafe import Markup
import numpy as np
from numpy.typing import NDArray
from rich.console import Console
from rich.prompt import Prompt
from scalecodec import GenericCall
from scalecodec.utils.ss58 import ss58_encode, ss58_decode
import typer
from bittensor_cli.src.bittensor.balances import Balance
from bittensor_cli.src import defaults, Constants
if TYPE_CHECKING:
from bittensor_cli.src.bittensor.chain_data import SubnetHyperparameters
from rich.prompt import PromptBase
BT_DOCS_LINK = "https://docs.learnbittensor.org"
GLOBAL_MAX_SUBNET_COUNT = 4096
MEV_SHIELD_PUBLIC_KEY_SIZE = 1184
console = Console()
json_console = Console(no_color=True)
err_console = Console(stderr=True)
verbose_console = Console(quiet=True)
jinja_env = Environment(
loader=PackageLoader("bittensor_cli", "src/bittensor/templates"),
autoescape=select_autoescape(),
)
UnlockStatus = namedtuple("UnlockStatus", ["success", "message"])
class _Hotkey:
def __init__(self, hotkey_ss58=None):
self.ss58_address = hotkey_ss58
class _Coldkeypub:
def __init__(self, coldkey_ss58=None):
self.ss58_address = coldkey_ss58
class WalletLike:
def __init__(
self,
name=None,
hotkey_ss58=None,
hotkey_str=None,
coldkeypub_ss58=None,
):
self.name = name
self.hotkey_ss58 = hotkey_ss58
self.hotkey_str = hotkey_str
self._hotkey = _Hotkey(hotkey_ss58)
self._coldkeypub = _Coldkeypub(coldkeypub_ss58)
@property
def hotkey(self):
return self._hotkey
@property
def coldkeypub(self):
return self._coldkeypub
def print_console(message: str, colour: str, title: str, console_: Console):
console_.print(
f"[bold {colour}][{title}]:[/bold {colour}] [{colour}]{message}[/{colour}]\n"
)
def print_verbose(message: str, status=None):
"""Print verbose messages while temporarily pausing the status spinner."""
if status:
status.stop()
print_console(message, "green", "Verbose", verbose_console)
status.start()
else:
print_console(message, "green", "Verbose", verbose_console)
def print_error(message: str, status=None):
"""Print error messages while temporarily pausing the status spinner."""
if status:
status.stop()
print_console(message, "red", "Error", err_console)
status.start()
else:
print_console(message, "red", "Error", err_console)
RAO_PER_TAO = 1e9
U16_MAX = 65535
U64_MAX = 18446744073709551615
def u16_normalized_float(x: int) -> float:
"""Converts a u16 int to a float"""
return float(x) / float(U16_MAX)
def u64_normalized_float(x: int) -> float:
"""Converts a u64 int to a float"""
return float(x) / float(U64_MAX)
def string_to_u64(value: str) -> int:
"""Converts a string to u64"""
return float_to_u64(float(value))
def float_to_u64(value: float) -> int:
"""Converts a float to a u64 int"""
# Ensure the input is within the expected range
if not (0 <= value <= 1):
raise ValueError("Input value must be between 0 and 1")
# Convert the float to a u64 value
return int(value * (2**64 - 1))
def u64_to_float(value: int) -> float:
u64_max = 2**64 - 1
# Allow for a small margin of error (e.g., 1) to account for potential rounding issues
if not (0 <= value <= u64_max + 1):
raise ValueError(
f"Input value ({value}) must be between 0 and {u64_max} (2^64 - 1)"
)
return min(value / u64_max, 1.0) # Ensure the result is never greater than 1.0
def string_to_u16(value: str) -> int:
"""Converts a string to a u16 int"""
return float_to_u16(float(value))
def float_to_u16(value: float) -> int:
# Ensure the input is within the expected range
if not (0 <= value <= 1):
raise ValueError("Input value must be between 0 and 1")
# Calculate the u16 representation
u16_max = 65535
return int(value * u16_max)
def u16_to_float(value: int) -> float:
# Ensure the input is within the expected range
if not (0 <= value <= 65535):
raise ValueError("Input value must be between 0 and 65535")
# Calculate the float representation
u16_max = 65535
return value / u16_max
def convert_weight_uids_and_vals_to_tensor(
n: int, uids: Collection[int], weights: Collection[int]
) -> NDArray[np.float32]:
"""
Converts weights and uids from chain representation into a `np.array` (inverse operation from
convert_weights_and_uids_for_emit)
:param n: number of neurons on network.
:param uids: Tensor of uids as destinations for passed weights.
:param weights: Tensor of weights.
:return: row_weights: Converted row weights.
"""
row_weights = np.zeros([n], dtype=np.float32)
for uid_j, wij in list(zip(uids, weights)):
row_weights[uid_j] = float(
wij
) # assumes max-upscaled values (w_max = U16_MAX).
row_sum = row_weights.sum()
if row_sum > 0:
row_weights /= row_sum # normalize
return row_weights
def convert_bond_uids_and_vals_to_tensor(
n: int, uids: list[int], bonds: list[int]
) -> NDArray[np.int64]:
"""Converts bond and uids from chain representation into a np.array.
:param n: number of neurons on network.
:param uids: Tensor of uids as destinations for passed bonds.
:param bonds: Tensor of bonds.
:return: Converted row bonds.
"""
row_bonds = np.zeros([n], dtype=np.int64)
for uid_j, bij in list(zip(uids, bonds)):
row_bonds[uid_j] = int(bij)
return row_bonds
def convert_root_weight_uids_and_vals_to_tensor(
n: int, uids: list[int], weights: list[int], subnets: list[int]
) -> NDArray:
"""
Converts root weights and uids from chain representation into a `np.array` or `torch.FloatTensor` (inverse operation
from `convert_weights_and_uids_for_emit`)
:param n: number of neurons on network.
:param uids: Tensor of uids as destinations for passed weights.
:param weights: Tensor of weights.
:param subnets: list of subnets on the network
:return: row_weights: Converted row weights.
"""
row_weights = np.zeros([n], dtype=np.float32)
for uid_j, wij in list(zip(uids, weights)):
if uid_j in subnets:
index_s = subnets.index(uid_j)
row_weights[index_s] = float(
wij
) # assumes max-upscaled values (w_max = U16_MAX).
else:
# TODO standardise logging
# logging.warning(
# f"Incorrect Subnet uid {uid_j} in Subnets {subnets}. The subnet is unavailable at the moment."
# )
continue
row_sum = row_weights.sum()
if row_sum > 0:
row_weights /= row_sum # normalize
return row_weights
def get_hotkey_wallets_for_wallet(
wallet: Wallet, show_nulls: bool = False, show_encrypted: bool = False
) -> list[Optional[Wallet]]:
"""
Returns wallet objects with hotkeys for a single given wallet
:param wallet: Wallet object to use for the path
:param show_nulls: will add `None` into the output if a hotkey is encrypted or not on the device
:param show_encrypted: will add some basic info about the encrypted hotkey
:return: a list of wallets (with Nones included for cases of a hotkey being encrypted or not on the device, if
`show_nulls` is set to `True`)
"""
hotkey_wallets = []
wallet_path = Path(wallet.path).expanduser()
hotkeys_path = wallet_path / wallet.name / "hotkeys"
try:
hotkeys = [entry.name for entry in hotkeys_path.iterdir()]
except (FileNotFoundError, NotADirectoryError):
hotkeys = []
for h_name in hotkeys:
if h_name.endswith("pub.txt"):
if h_name.split("pub.txt")[0] in hotkeys:
continue
else:
hotkey_for_name = Wallet(
path=str(wallet_path),
name=wallet.name,
hotkey=h_name.split("pub.txt")[0],
)
else:
hotkey_for_name = Wallet(
path=str(wallet_path), name=wallet.name, hotkey=h_name
)
try:
exists = (
hotkey_for_name.hotkey_file.exists_on_device()
or hotkey_for_name.hotkeypub_file.exists_on_device()
)
if (
exists
and not hotkey_for_name.hotkey_file.is_encrypted()
# and hotkey_for_name.coldkeypub.ss58_address
and get_hotkey_pub_ss58(hotkey_for_name)
):
hotkey_wallets.append(hotkey_for_name)
elif (
show_encrypted and exists and hotkey_for_name.hotkey_file.is_encrypted()
):
hotkey_wallets.append(
WalletLike(str(wallet_path), "<ENCRYPTED>", h_name)
)
elif show_nulls:
hotkey_wallets.append(None)
except (
UnicodeDecodeError,
AttributeError,
TypeError,
KeyFileError,
ValueError,
): # usually an unrelated file like .DS_Store
continue
return hotkey_wallets
def get_coldkey_wallets_for_path(path: str) -> list[Wallet]:
"""Gets all wallets with coldkeys from a given path"""
wallet_path = Path(path).expanduser()
try:
wallets = [
Wallet(name=directory.name, path=path)
for directory in wallet_path.iterdir()
if directory.is_dir()
]
except FileNotFoundError:
wallets = []
return wallets
def get_all_wallets_for_path(path: str) -> list[Wallet]:
"""Gets all wallets from a given path."""
all_wallets = []
cold_wallets = get_coldkey_wallets_for_path(path)
for cold_wallet in cold_wallets:
try:
if (
cold_wallet.coldkeypub_file.exists_on_device()
and not cold_wallet.coldkeypub_file.is_encrypted()
):
all_wallets.extend(get_hotkey_wallets_for_wallet(cold_wallet))
except UnicodeDecodeError: # usually an incorrect file like .DS_Store
continue
return all_wallets
def validate_coldkey_presence(
wallets: list[Wallet],
) -> tuple[list[Wallet], list[Wallet]]:
"""
Validates the presence of coldkeypub.txt for each wallet.
Returns:
tuple[list[Wallet], list[Wallet]]: A tuple containing two lists:
- The first list contains wallets with the required coldkey.
- The second list contains wallets without the required coldkey.
"""
valid_wallets = []
invalid_wallets = []
for wallet in wallets:
if not os.path.exists(wallet.coldkeypub_file.path):
invalid_wallets.append(wallet)
else:
valid_wallets.append(wallet)
return valid_wallets, invalid_wallets
def is_valid_wallet(wallet: Wallet) -> tuple[bool, bool]:
"""
Verifies that the wallet with specified parameters.
:param wallet: a Wallet instance
:return: tuple[bool], whether wallet appears valid, whether valid hotkey in wallet
"""
return (
all(
[
os.path.exists(wp := os.path.expanduser(wallet.path)),
os.path.exists(os.path.join(wp, wallet.name)),
]
),
os.path.isfile(os.path.join(wp, wallet.name, "hotkeys", wallet.hotkey_str)),
)
def is_valid_ss58_address(address: str) -> bool:
"""
Checks if the given address is a valid ss58 address.
:param address: The address to check.
:return: `True` if the address is a valid ss58 address for Bittensor, `False` otherwise.
"""
try:
return utils.is_valid_ss58_address(
address
) # Default substrate ss58 format (legacy)
except IndexError:
return False
def is_valid_ss58_address_prompt(text: str) -> str:
valid = False
address = ""
while not valid:
address = Prompt.ask(text).strip()
valid = is_valid_ss58_address(address)
return address
def is_valid_ed25519_pubkey(public_key: Union[str, bytes]) -> bool:
"""
Checks if the given public_key is a valid ed25519 key.
:param public_key: The public_key to check.
:return: True if the public_key is a valid ed25519 key, False otherwise.
"""
try:
if isinstance(public_key, str):
if len(public_key) != 64 and len(public_key) != 66:
raise ValueError("a public_key should be 64 or 66 characters")
elif isinstance(public_key, bytes):
if len(public_key) != 32:
raise ValueError("a public_key should be 32 bytes")
else:
raise ValueError("public_key must be a string or bytes")
keypair = Keypair(public_key=public_key, ss58_format=SS58_FORMAT)
ss58_addr = keypair.ss58_address
return ss58_addr is not None
except (ValueError, IndexError):
return False
def is_valid_bittensor_address_or_public_key(address: Union[str, bytes]) -> bool:
"""
Checks if the given address is a valid destination address.
:param address: The address to check.
:return: True if the address is a valid destination address, False otherwise.
"""
if isinstance(address, str):
# Check if ed25519
if address.startswith("0x"):
return is_valid_ed25519_pubkey(address)
else:
# Assume ss58 address
return is_valid_ss58_address(address)
elif isinstance(address, bytes):
# Check if ed25519
return is_valid_ed25519_pubkey(address)
else:
# Invalid address type
return False
def decode_account_id(account_id_bytes: Union[tuple[int], tuple[tuple[int]]]):
if isinstance(account_id_bytes, tuple) and isinstance(account_id_bytes[0], tuple):
account_id_bytes = account_id_bytes[0]
# Convert the AccountId bytes to a Base64 string
return ss58_encode(bytes(account_id_bytes).hex(), SS58_FORMAT)
def encode_account_id(ss58_address: str) -> bytes:
return bytes.fromhex(ss58_decode(ss58_address, SS58_FORMAT))
def ss58_to_vec_u8(ss58_address: str) -> list[int]:
"""
Converts an SS58 address to a list of integers (vector of u8).
:param ss58_address: The SS58 address to be converted.
:return: A list of integers representing the byte values of the SS58 address.
"""
ss58_bytes: bytes = encode_account_id(ss58_address)
encoded_address: list[int] = [int(byte) for byte in ss58_bytes]
return encoded_address
def get_explorer_root_url_by_network_from_map(
network: str, network_map: dict[str, dict[str, str]]
) -> dict[str, str]:
"""
Returns the explorer root url for the given network name from the given network map.
:param network: The network to get the explorer url for.
:param network_map: The network map to get the explorer url from.
:return: The explorer url for the given network.
"""
explorer_urls: dict[str, str] = {}
for entity_nm, entity_network_map in network_map.items():
if network in entity_network_map:
explorer_urls[entity_nm] = entity_network_map[network]
return explorer_urls
def get_explorer_url_for_network(
network: str, block_hash: str, network_map: dict[str, dict[str, str]]
) -> dict[str, str]:
"""
Returns the explorer url for the given block hash and network.
:param network: The network to get the explorer url for.
:param block_hash: The block hash to get the explorer url for.
:param network_map: The network maps to get the explorer urls from.
:return: The explorer url for the given block hash and network
"""
# TODO remove
explorer_urls: dict[str, str] = {}
# Will be None if the network is not known. i.e. not in network_map
explorer_root_urls: dict[str, str] = get_explorer_root_url_by_network_from_map(
network, network_map
)
if explorer_root_urls != {}:
# We are on a known network.
explorer_opentensor_url = "{root_url}/query/{block_hash}".format(
root_url=explorer_root_urls.get("opentensor"), block_hash=block_hash
)
explorer_taostats_url = "{root_url}/hash/{block_hash}".format(
root_url=explorer_root_urls.get("taostats"), block_hash=block_hash
)
explorer_urls["opentensor"] = explorer_opentensor_url
explorer_urls["taostats"] = explorer_taostats_url
return explorer_urls
def format_error_message(error_message: Union[dict, Exception]) -> str:
"""
Formats an error message from the Subtensor error information for use in extrinsics.
Args:
error_message: A dictionary containing the error information from Subtensor, or a SubstrateRequestException
containing dictionary literal args.
Returns:
str: A formatted error message string.
"""
err_name = "UnknownError"
err_type = "UnknownType"
err_description = "Unknown Description"
if isinstance(error_message, Exception):
# generally gotten through SubstrateRequestException args
new_error_message = None
for arg in error_message.args:
try:
d = ast.literal_eval(arg)
if isinstance(d, dict):
if "error" in d:
new_error_message = d["error"]
break
elif all(x in d for x in ["code", "message", "data"]):
new_error_message = d
break
except (ValueError, TypeError, SyntaxError, MemoryError, RecursionError):
pass
if new_error_message is None:
return_val = " ".join(error_message.args)
return f"Subtensor returned: {return_val}"
else:
error_message = new_error_message
if isinstance(error_message, dict):
# subtensor error structure
if (
error_message.get("code")
and error_message.get("message")
and error_message.get("data")
):
err_name = "SubstrateRequestException"
err_type = error_message.get("message", "")
err_data = error_message.get("data", "")
# subtensor custom error marker
if err_data.startswith("Custom error:"):
err_description = (
f"{err_data} | Please consult {BT_DOCS_LINK}/errors/custom"
)
else:
err_description = err_data
elif (
error_message.get("type")
and error_message.get("name")
and error_message.get("docs")
):
err_type = error_message.get("type", err_type)
err_name = error_message.get("name", err_name)
err_docs = error_message.get("docs", [err_description])
err_description = (
" ".join(err_docs) if not isinstance(err_docs, str) else err_docs
)
err_description += (
f" | Please consult {BT_DOCS_LINK}/errors/subtensor#{err_name.lower()}"
)
elif error_message.get("code") and error_message.get("message"):
err_type = error_message.get("code", err_name)
err_name = "Custom type"
err_description = error_message.get("message", err_description)
else:
print_error(
f"String representation of real error_message: {str(error_message)}"
)
return f"Subtensor returned `{err_name}({err_type})` error. This means: `{err_description}`."
def convert_blocks_to_time(blocks: int, block_time: int = 12) -> tuple[int, int, int]:
"""
Converts number of blocks into number of hours, minutes, seconds.
:param blocks: number of blocks
:param block_time: time per block, by default this is 12
:return: tuple containing number of hours, number of minutes, number of seconds
"""
seconds = blocks * block_time
hours = seconds // 3600
minutes = (seconds % 3600) // 60
remaining_seconds = seconds % 60
return hours, minutes, remaining_seconds
def decode_hex_identity_dict(info_dictionary) -> dict[str, Any]:
"""
Decodes hex-encoded strings in a dictionary.
This function traverses the given dictionary, identifies hex-encoded strings, and decodes them into readable
strings. It handles nested dictionaries and lists within the dictionary.
Args:
info_dictionary (dict): The dictionary containing hex-encoded strings to decode.
Returns:
dict: The dictionary with decoded strings.
Examples:
input_dict = {
"name": {"value": "0x6a6f686e"},
"additional": [
{"data1": "0x64617461"},
("data2", "0x64617461")
]
}
decode_hex_identity_dict(input_dict)
{'name': 'john', 'additional': [('data1', 'data'), ('data2', 'data')]}
"""
def get_decoded(data: Optional[str]) -> str:
"""Decodes a hex-encoded string."""
if data is None:
return ""
try:
return hex_to_bytes(data).decode()
except (UnicodeDecodeError, ValueError):
print(f"Could not decode: {key}: {item}")
for key, value in info_dictionary.items():
if isinstance(value, dict):
item = list(value.values())[0]
if isinstance(item, str) and item.startswith("0x"):
try:
info_dictionary[key] = get_decoded(item)
except UnicodeDecodeError:
print(f"Could not decode: {key}: {item}")
else:
info_dictionary[key] = item
if key == "additional":
additional = []
for item in value:
if isinstance(item, dict):
for k, v in item.items():
additional.append((k, get_decoded(v)))
else:
if isinstance(item, (tuple, list)) and len(item) == 2:
k_, v = item
k = k_ if k_ is not None else ""
additional.append((k, get_decoded(v)))
info_dictionary[key] = additional
return info_dictionary
def get_human_readable(num: float, suffix="H"):
"""
Converts a number to a human-readable string.
:return: human-readable string representation of a number.
"""
for unit in ["", "K", "M", "G", "T", "P", "E", "Z"]:
if abs(num) < 1000.0:
return f"{num:3.1f}{unit}{suffix}"
num /= 1000.0
return f"{num:.1f}Y{suffix}"
def millify(n: int):
"""
Convert a large number into a more readable format with appropriate suffixes.
This function transforms a large integer into a shorter, human-readable string with
suffixes such as K, M, B, and T for thousands, millions, billions, and trillions,
respectively. The number is formatted to two decimal places.
:param n: The number to be converted.
:return: The formatted string representing the number with a suffix.
"""
mill_names = ["", " K", " M", " B", " T"]
n_ = float(n)
mill_idx = max(
0,
min(
len(mill_names) - 1,
int(math.floor(0 if n_ == 0 else math.log10(abs(n_)) / 3)),
),
)
return "{:.2f}{}".format(n_ / 10 ** (3 * mill_idx), mill_names[mill_idx])
def millify_tao(n: float, start_at: str = "K") -> str:
"""
Dupe of millify, but for ease in converting tao values.
Allows thresholds to be specified for different suffixes.
"""
mill_names = ["", "k", "m", "b", "t"]
thresholds = {"K": 1, "M": 2, "B": 3, "T": 4}
if start_at not in thresholds:
raise ValueError(f"start_at must be one of {list(thresholds.keys())}")
n_ = float(n)
if n_ == 0:
return "0.00"
mill_idx = int(math.floor(math.log10(abs(n_)) / 3))
# Number's index is below our threshold, return with commas
if mill_idx < thresholds[start_at]:
return f"{n_:,.2f}"
mill_idx = max(thresholds[start_at], min(len(mill_names) - 1, mill_idx))
return "{:.2f}{}".format(n_ / 10 ** (3 * mill_idx), mill_names[mill_idx])
def normalize_hyperparameters(
subnet: "SubnetHyperparameters",
json_output: bool = False,
) -> list[tuple[str, str, str]]:
"""
Normalizes the hyperparameters of a subnet.
:param subnet: The subnet hyperparameters object.
:param json_output: Whether this normalisation will be for a JSON output or console string (determines whether
items get stringified or safe for JSON encoding)
:return: A list of tuples containing the parameter name, value, and normalized value.
"""
param_mappings = {
"adjustment_alpha": u64_normalized_float,
"min_difficulty": u64_normalized_float,
"max_difficulty": u64_normalized_float,
"difficulty": u64_normalized_float,
"bonds_moving_avg": u64_normalized_float,
"max_weight_limit": u16_normalized_float,
"kappa": u16_normalized_float,
"alpha_high": u16_normalized_float,
"alpha_low": u16_normalized_float,
"alpha_sigmoid_steepness": u16_normalized_float,
"min_burn": Balance.from_rao,
"max_burn": Balance.from_rao,
}
normalized_values: list[tuple[str, str, str]] = []
subnet_dict = subnet.__dict__
for param, value in subnet_dict.items():
try:
if param in param_mappings:
norm_value = param_mappings[param](value)
if isinstance(norm_value, float):
norm_value = f"{norm_value:.{10}g}"
if isinstance(norm_value, Balance) and json_output:
norm_value = norm_value.to_dict()
else:
norm_value = value
except Exception:
# bittensor.logging.warning(f"Error normalizing parameter '{param}': {e}")
norm_value = "-"
if not json_output:
normalized_values.append((param, str(value), str(norm_value)))
else:
normalized_values.append((param, value, norm_value))
return normalized_values
class TableDefinition:
"""
Base class for address book table definitions/functions
"""
name: str
cols: tuple[tuple[str, str], ...]
@staticmethod
@contextmanager
def get_db() -> Generator[tuple[sqlite3.Connection, sqlite3.Cursor], None, None]:
"""
Helper function to get a DB connection
"""
with DB() as (conn, cursor):
yield conn, cursor
@classmethod
def create_if_not_exists(cls, conn: sqlite3.Connection, _: sqlite3.Cursor) -> None:
"""
Creates the table if it doesn't exist.
Args:
conn: sqlite3 connection
_: sqlite3 cursor
"""
columns_ = ", ".join([" ".join(x) for x in cls.cols])
conn.execute(f"CREATE TABLE IF NOT EXISTS {cls.name} ({columns_})")
conn.commit()
@classmethod
def read_rows(
cls,
_: sqlite3.Connection,
cursor: sqlite3.Cursor,
include_header: bool = True,
) -> list[tuple[Union[str, int], ...]]:
"""
Reads rows from a table.
Args:
_: sqlite3 connection
cursor: sqlite3 cursor
include_header: Whether to include the header row
Returns:
rows of the table, with column names as the header row if `include_header` is set
"""
header = tuple(x[0] for x in cls.cols)
cols = ", ".join(header)
cursor.execute(f"SELECT {cols} FROM {cls.name}")
rows = cursor.fetchall()
if not include_header:
return rows
else:
return [header] + rows
@classmethod
def update_entry(cls, *args, **kwargs):
"""
Updates an existing entry in the table.
"""
raise NotImplementedError()
@classmethod
def add_entry(cls, *args, **kwargs):
"""
Adds an entry to the table.
"""
raise NotImplementedError()
@classmethod
def delete_entry(cls, *args, **kwargs):
"""
Deletes an entry from the table.
"""
raise NotImplementedError()
class AddressBook(TableDefinition):
name = "address_book"
cols = (("name", "TEXT"), ("ss58_address", "TEXT"), ("note", "TEXT"))
@classmethod
def add_entry(
cls,
conn: sqlite3.Connection,
_: sqlite3.Cursor,
*,
name: str,
ss58_address: str,
note: str,
) -> None:
conn.execute(
f"INSERT INTO {cls.name} (name, ss58_address, note) VALUES (?, ?, ?)",
(name, ss58_address, note),
)
conn.commit()
@classmethod
def update_entry(
cls,
conn: sqlite3.Connection,
cursor: sqlite3.Cursor,
*,
name: str,
ss58_address: Optional[str] = None,
note: Optional[str] = None,
):
cursor.execute(
f"SELECT ss58_address, note FROM {cls.name} WHERE name = ?",
(name,),
)
row = cursor.fetchone()[0]
ss58_address_ = ss58_address or row[0]
note_ = note or row[1]
conn.execute(
f"UPDATE {cls.name} SET ss58_address = ?, note = ? WHERE name = ?",
(ss58_address_, note_, name),
)
conn.commit()
@classmethod
def delete_entry(
cls, conn: sqlite3.Connection, cursor: sqlite3.Cursor, *, name: str
):
conn.execute(
f"DELETE FROM {cls.name} WHERE name = ?",
(name,),
)
conn.commit()
class ProxyAddressBook(TableDefinition):
name = "proxy_address_book"
cols = (
("name", "TEXT"),
("ss58_address", "TEXT"),
("delay", "INTEGER"),
("spawner", "TEXT"),
("proxy_type", "TEXT"),
("note", "TEXT"),
)
@classmethod
def update_entry(
cls,
conn: sqlite3.Connection,
cursor: sqlite3.Cursor,
*,
name: str,
ss58_address: Optional[str] = None,
delay: Optional[int] = None,
spawner: Optional[str] = None,
proxy_type: Optional[str] = None,
note: Optional[str] = None,
) -> None:
cursor.execute(
f"SELECT ss58_address, spawner, proxy_type, delay, note FROM {cls.name} WHERE name = ?",
(name,),
)
row = cursor.fetchone()[0]
ss58_address_ = ss58_address or row[0]
spawner_ = spawner or row[1]
proxy_type_ = proxy_type or row[2]
delay = delay if delay is not None else row[3]
note_ = note or row[4]
conn.execute(
f"UPDATE {cls.name} SET ss58_address = ?, spawner = ?, proxy_type = ?, delay = ?, note = ? WHERE name = ?",
(ss58_address_, spawner_, proxy_type_, note_, delay, name),
)
conn.commit()
@classmethod
def add_entry(
cls,
conn: sqlite3.Connection,
_: sqlite3.Cursor,
*,