bittensor-cli 8.4.3__py3-none-any.whl → 9.0.0rc2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. bittensor_cli/__init__.py +2 -2
  2. bittensor_cli/cli.py +1508 -1385
  3. bittensor_cli/src/__init__.py +627 -197
  4. bittensor_cli/src/bittensor/balances.py +41 -8
  5. bittensor_cli/src/bittensor/chain_data.py +557 -428
  6. bittensor_cli/src/bittensor/extrinsics/registration.py +161 -47
  7. bittensor_cli/src/bittensor/extrinsics/root.py +14 -8
  8. bittensor_cli/src/bittensor/extrinsics/transfer.py +14 -21
  9. bittensor_cli/src/bittensor/minigraph.py +46 -8
  10. bittensor_cli/src/bittensor/subtensor_interface.py +572 -253
  11. bittensor_cli/src/bittensor/utils.py +326 -75
  12. bittensor_cli/src/commands/stake/__init__.py +154 -0
  13. bittensor_cli/src/commands/stake/children_hotkeys.py +121 -87
  14. bittensor_cli/src/commands/stake/move.py +1000 -0
  15. bittensor_cli/src/commands/stake/stake.py +1637 -1264
  16. bittensor_cli/src/commands/subnets/__init__.py +0 -0
  17. bittensor_cli/src/commands/subnets/price.py +867 -0
  18. bittensor_cli/src/commands/subnets/subnets.py +2055 -0
  19. bittensor_cli/src/commands/sudo.py +529 -26
  20. bittensor_cli/src/commands/wallets.py +234 -544
  21. bittensor_cli/src/commands/weights.py +15 -11
  22. {bittensor_cli-8.4.3.dist-info → bittensor_cli-9.0.0rc2.dist-info}/METADATA +7 -4
  23. bittensor_cli-9.0.0rc2.dist-info/RECORD +32 -0
  24. bittensor_cli/src/bittensor/async_substrate_interface.py +0 -2748
  25. bittensor_cli/src/commands/root.py +0 -1752
  26. bittensor_cli/src/commands/subnets.py +0 -897
  27. bittensor_cli-8.4.3.dist-info/RECORD +0 -31
  28. {bittensor_cli-8.4.3.dist-info → bittensor_cli-9.0.0rc2.dist-info}/WHEEL +0 -0
  29. {bittensor_cli-8.4.3.dist-info → bittensor_cli-9.0.0rc2.dist-info}/entry_points.txt +0 -0
  30. {bittensor_cli-8.4.3.dist-info → bittensor_cli-9.0.0rc2.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,2055 @@
1
+ import asyncio
2
+ import json
3
+ import sqlite3
4
+ from typing import TYPE_CHECKING, Optional, cast
5
+ import typer
6
+
7
+ from bittensor_wallet import Wallet
8
+ from bittensor_wallet.errors import KeyFileError
9
+ from rich.prompt import Confirm, Prompt
10
+ from rich.console import Group
11
+ from rich.progress import Progress, BarColumn, TextColumn
12
+ from rich.table import Column, Table
13
+ from rich import box
14
+
15
+ from bittensor_cli.src import COLOR_PALETTE
16
+ from bittensor_cli.src.bittensor.balances import Balance
17
+ from bittensor_cli.src.bittensor.extrinsics.registration import (
18
+ register_extrinsic,
19
+ burned_register_extrinsic,
20
+ )
21
+ from bittensor_cli.src.bittensor.extrinsics.root import root_register_extrinsic
22
+ from rich.live import Live
23
+ from bittensor_cli.src.bittensor.minigraph import MiniGraph
24
+ from bittensor_cli.src.commands.wallets import set_id, get_id
25
+ from bittensor_cli.src.bittensor.utils import (
26
+ console,
27
+ create_table,
28
+ err_console,
29
+ print_verbose,
30
+ print_error,
31
+ format_error_message,
32
+ get_metadata_table,
33
+ millify_tao,
34
+ render_table,
35
+ update_metadata_table,
36
+ prompt_for_identity,
37
+ get_subnet_name,
38
+ )
39
+
40
+ if TYPE_CHECKING:
41
+ from bittensor_cli.src.bittensor.subtensor_interface import SubtensorInterface
42
+
43
+ TAO_WEIGHT = 0.018
44
+
45
+ # helpers and extrinsics
46
+
47
+
48
+ async def register_subnetwork_extrinsic(
49
+ subtensor: "SubtensorInterface",
50
+ wallet: Wallet,
51
+ subnet_identity: dict,
52
+ wait_for_inclusion: bool = False,
53
+ wait_for_finalization: bool = True,
54
+ prompt: bool = False,
55
+ ) -> bool:
56
+ """Registers a new subnetwork.
57
+
58
+ wallet (bittensor.wallet):
59
+ bittensor wallet object.
60
+ wait_for_inclusion (bool):
61
+ 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.
62
+ wait_for_finalization (bool):
63
+ 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.
64
+ prompt (bool):
65
+ If true, the call waits for confirmation from the user before proceeding.
66
+ Returns:
67
+ success (bool):
68
+ Flag is ``true`` if extrinsic was finalized or included in the block.
69
+ If we did not wait for finalization / inclusion, the response is ``true``.
70
+ """
71
+
72
+ async def _find_event_attributes_in_extrinsic_receipt(
73
+ response_, event_name: str
74
+ ) -> list:
75
+ """
76
+ Searches for the attributes of a specified event within an extrinsic receipt.
77
+
78
+ :param response_: The receipt of the extrinsic to be searched.
79
+ :param event_name: The name of the event to search for.
80
+
81
+ :return: A list of attributes for the specified event. Returns [-1] if the event is not found.
82
+ """
83
+ for event in await response_.triggered_events:
84
+ # Access the event details
85
+ event_details = event["event"]
86
+ # Check if the event_id is 'NetworkAdded'
87
+ if event_details["event_id"] == event_name:
88
+ # Once found, you can access the attributes of the event_name
89
+ return event_details["attributes"]
90
+ return [-1]
91
+
92
+ print_verbose("Fetching balance")
93
+ your_balance = await subtensor.get_balance(wallet.coldkeypub.ss58_address)
94
+
95
+ print_verbose("Fetching burn_cost")
96
+ sn_burn_cost = await burn_cost(subtensor)
97
+ if sn_burn_cost > your_balance:
98
+ err_console.print(
99
+ f"Your balance of: [{COLOR_PALETTE['POOLS']['TAO']}]{your_balance}[{COLOR_PALETTE['POOLS']['TAO']}] is not enough to pay the subnet lock cost of: "
100
+ f"[{COLOR_PALETTE['POOLS']['TAO']}]{sn_burn_cost}[{COLOR_PALETTE['POOLS']['TAO']}]"
101
+ )
102
+ return False
103
+
104
+ if prompt:
105
+ console.print(
106
+ f"Your balance is: [{COLOR_PALETTE['POOLS']['TAO']}]{your_balance}"
107
+ )
108
+ if not Confirm.ask(
109
+ f"Do you want to register a subnet for [{COLOR_PALETTE['POOLS']['TAO']}]{sn_burn_cost}?"
110
+ ):
111
+ return False
112
+
113
+ has_identity = any(subnet_identity.values())
114
+ if has_identity:
115
+ identity_data = {
116
+ "subnet_name": subnet_identity["subnet_name"].encode()
117
+ if subnet_identity.get("subnet_name")
118
+ else b"",
119
+ "github_repo": subnet_identity["github_repo"].encode()
120
+ if subnet_identity.get("github_repo")
121
+ else b"",
122
+ "subnet_contact": subnet_identity["subnet_contact"].encode()
123
+ if subnet_identity.get("subnet_contact")
124
+ else b"",
125
+ "subnet_url": subnet_identity["subnet_url"].encode()
126
+ if subnet_identity.get("subnet_url")
127
+ else b"",
128
+ "discord": subnet_identity["discord"].encode()
129
+ if subnet_identity.get("discord")
130
+ else b"",
131
+ "description": subnet_identity["description"].encode()
132
+ if subnet_identity.get("description")
133
+ else b"",
134
+ "additional": subnet_identity["additional"].encode()
135
+ if subnet_identity.get("additional")
136
+ else b"",
137
+ }
138
+ for field, value in identity_data.items():
139
+ max_size = 64 # bytes
140
+ if len(value) > max_size:
141
+ err_console.print(
142
+ f"[red]Error:[/red] Identity field [white]{field}[/white] must be <= {max_size} bytes.\n"
143
+ f"Value '{value.decode()}' is {len(value)} bytes."
144
+ )
145
+ return False
146
+
147
+ try:
148
+ wallet.unlock_coldkey()
149
+ except KeyFileError:
150
+ err_console.print("Error decrypting coldkey (possibly incorrect password)")
151
+ return False
152
+
153
+ with console.status(":satellite: Registering subnet...", spinner="earth"):
154
+ call_params = {
155
+ "hotkey": wallet.hotkey.ss58_address,
156
+ "mechid": 1,
157
+ }
158
+ call_function = "register_network"
159
+ if has_identity:
160
+ call_params["identity"] = identity_data
161
+ call_function = "register_network_with_identity"
162
+
163
+ substrate = subtensor.substrate
164
+ # create extrinsic call
165
+ call = await substrate.compose_call(
166
+ call_module="SubtensorModule",
167
+ call_function=call_function,
168
+ call_params=call_params,
169
+ )
170
+ extrinsic = await substrate.create_signed_extrinsic(
171
+ call=call, keypair=wallet.coldkey
172
+ )
173
+ response = await substrate.submit_extrinsic(
174
+ extrinsic,
175
+ wait_for_inclusion=wait_for_inclusion,
176
+ wait_for_finalization=wait_for_finalization,
177
+ )
178
+
179
+ # We only wait here if we expect finalization.
180
+ if not wait_for_finalization and not wait_for_inclusion:
181
+ return True
182
+
183
+ await response.process_events()
184
+ if not await response.is_success:
185
+ err_console.print(
186
+ f":cross_mark: [red]Failed[/red]: {format_error_message(await response.error_message, substrate)}"
187
+ )
188
+ await asyncio.sleep(0.5)
189
+ return False
190
+
191
+ # Successful registration, final check for membership
192
+ else:
193
+ attributes = await _find_event_attributes_in_extrinsic_receipt(
194
+ response, "NetworkAdded"
195
+ )
196
+ console.print(
197
+ f":white_heavy_check_mark: [dark_sea_green3]Registered subnetwork with netuid: {attributes[0]}"
198
+ )
199
+ return True
200
+
201
+
202
+ # commands
203
+
204
+
205
+ async def subnets_list(
206
+ subtensor: "SubtensorInterface",
207
+ reuse_last: bool,
208
+ html_output: bool,
209
+ no_cache: bool,
210
+ verbose: bool,
211
+ live: bool,
212
+ ):
213
+ """List all subnet netuids in the network."""
214
+
215
+ async def fetch_subnet_data():
216
+ block_number = await subtensor.substrate.get_block_number(None)
217
+ subnets = await subtensor.all_subnets()
218
+
219
+ # Sort subnets by market cap, keeping the root subnet in the first position
220
+ root_subnet = next(s for s in subnets if s.netuid == 0)
221
+ other_subnets = sorted(
222
+ [s for s in subnets if s.netuid != 0],
223
+ key=lambda x: (x.alpha_in.tao + x.alpha_out.tao) * x.price.tao,
224
+ reverse=True,
225
+ )
226
+ sorted_subnets = [root_subnet] + other_subnets
227
+ return sorted_subnets, block_number
228
+
229
+ def calculate_emission_stats(
230
+ subnets: list, block_number: int
231
+ ) -> tuple[Balance, str]:
232
+ # We do not include the root subnet in the emission calculation
233
+ total_tao_emitted = sum(
234
+ subnet.tao_in.tao for subnet in subnets if subnet.netuid != 0
235
+ )
236
+ emission_percentage = (total_tao_emitted / block_number) * 100
237
+ percentage_color = "dark_sea_green" if emission_percentage < 100 else "red"
238
+ formatted_percentage = (
239
+ f"[{percentage_color}]{emission_percentage:.2f}%[/{percentage_color}]"
240
+ )
241
+ if not verbose:
242
+ percentage_string = f"τ {millify_tao(total_tao_emitted)}/{millify_tao(block_number)} ({formatted_percentage})"
243
+ else:
244
+ percentage_string = (
245
+ f"τ {total_tao_emitted:.1f}/{block_number} ({formatted_percentage})"
246
+ )
247
+ return total_tao_emitted, percentage_string
248
+
249
+ def define_table(
250
+ total_emissions: float,
251
+ total_rate: float,
252
+ total_netuids: int,
253
+ tao_emission_percentage: str,
254
+ ):
255
+ table = Table(
256
+ title=f"\n[{COLOR_PALETTE['GENERAL']['HEADER']}]Subnets"
257
+ f"\nNetwork: [{COLOR_PALETTE['GENERAL']['SUBHEADING']}]{subtensor.network}\n\n",
258
+ show_footer=True,
259
+ show_edge=False,
260
+ header_style="bold white",
261
+ border_style="bright_black",
262
+ style="bold",
263
+ title_justify="center",
264
+ show_lines=False,
265
+ pad_edge=True,
266
+ )
267
+
268
+ table.add_column(
269
+ "[bold white]Netuid",
270
+ style="grey89",
271
+ justify="center",
272
+ footer=str(total_netuids),
273
+ )
274
+ table.add_column("[bold white]Name", style="cyan", justify="left")
275
+ table.add_column(
276
+ f"[bold white]Price \n({Balance.get_unit(0)}_in/{Balance.get_unit(1)}_in)",
277
+ style="dark_sea_green2",
278
+ justify="left",
279
+ footer=f"τ {total_rate}",
280
+ )
281
+ table.add_column(
282
+ f"[bold white]Market Cap \n({Balance.get_unit(1)} * Price)",
283
+ style="steel_blue3",
284
+ justify="left",
285
+ )
286
+ table.add_column(
287
+ f"[bold white]Emission ({Balance.get_unit(0)})",
288
+ style=COLOR_PALETTE["POOLS"]["EMISSION"],
289
+ justify="left",
290
+ footer=f"τ {total_emissions}",
291
+ )
292
+ table.add_column(
293
+ f"[bold white]P ({Balance.get_unit(0)}_in, {Balance.get_unit(1)}_in)",
294
+ style=COLOR_PALETTE["STAKE"]["TAO"],
295
+ justify="left",
296
+ footer=f"{tao_emission_percentage}",
297
+ )
298
+ table.add_column(
299
+ f"[bold white]Stake ({Balance.get_unit(1)}_out)",
300
+ style=COLOR_PALETTE["STAKE"]["STAKE_ALPHA"],
301
+ justify="left",
302
+ )
303
+ table.add_column(
304
+ f"[bold white]Supply ({Balance.get_unit(1)})",
305
+ style=COLOR_PALETTE["POOLS"]["ALPHA_IN"],
306
+ justify="left",
307
+ )
308
+
309
+ table.add_column(
310
+ "[bold white]Tempo (k/n)",
311
+ style=COLOR_PALETTE["GENERAL"]["TEMPO"],
312
+ justify="left",
313
+ overflow="fold",
314
+ )
315
+ return table
316
+
317
+ # Non-live mode
318
+ def create_table(subnets, block_number):
319
+ rows = []
320
+ _, percentage_string = calculate_emission_stats(subnets, block_number)
321
+
322
+ for subnet in subnets:
323
+ netuid = subnet.netuid
324
+ symbol = f"{subnet.symbol}\u200e"
325
+
326
+ if netuid == 0:
327
+ emission_tao = 0.0
328
+ else:
329
+ emission_tao = subnet.emission.tao
330
+
331
+ alpha_in_value = (
332
+ f"{millify_tao(subnet.alpha_in.tao)}"
333
+ if not verbose
334
+ else f"{subnet.alpha_in.tao:,.4f}"
335
+ )
336
+ alpha_out_value = (
337
+ f"{millify_tao(subnet.alpha_out.tao)}"
338
+ if not verbose
339
+ else f"{subnet.alpha_out.tao:,.4f}"
340
+ )
341
+ price_value = f"{subnet.price.tao:,.4f}"
342
+
343
+ # Market Cap
344
+ market_cap = (subnet.alpha_in.tao + subnet.alpha_out.tao) * subnet.price.tao
345
+ market_cap_value = (
346
+ f"{millify_tao(market_cap)}" if not verbose else f"{market_cap:,.4f}"
347
+ )
348
+
349
+ # Liquidity
350
+ tao_in_cell = (
351
+ (
352
+ f"τ {millify_tao(subnet.tao_in.tao)}"
353
+ if not verbose
354
+ else f"τ {subnet.tao_in.tao:,.4f}"
355
+ )
356
+ if netuid != 0
357
+ else "-"
358
+ )
359
+ alpha_in_cell = f"{alpha_in_value} {symbol}" if netuid != 0 else "-"
360
+ liquidity_cell = f"{tao_in_cell}, {alpha_in_cell}"
361
+
362
+ # Supply
363
+ supply = subnet.alpha_in.tao + subnet.alpha_out.tao
364
+ supply_value = f"{millify_tao(supply)}" if not verbose else f"{supply:,.4f}"
365
+
366
+ # Prepare cells
367
+ netuid_cell = str(netuid)
368
+ subnet_name_cell = (
369
+ f"[{COLOR_PALETTE['GENERAL']['SYMBOL']}]{subnet.symbol if netuid != 0 else 'τ'}[/{COLOR_PALETTE['GENERAL']['SYMBOL']}]"
370
+ f" {get_subnet_name(subnet)}"
371
+ )
372
+ emission_cell = f"τ {emission_tao:,.4f}"
373
+ price_cell = f"{price_value} τ/{symbol}"
374
+ alpha_out_cell = (
375
+ f"{alpha_out_value} {symbol}"
376
+ if netuid != 0
377
+ else f"{symbol} {alpha_out_value}"
378
+ )
379
+ market_cap_cell = f"τ {market_cap_value}"
380
+ supply_cell = f"{supply_value} {symbol} [#806DAF]/21M"
381
+
382
+ if netuid != 0:
383
+ tempo_cell = f"{subnet.blocks_since_last_step}/{subnet.tempo}"
384
+ else:
385
+ tempo_cell = "-/-"
386
+
387
+ rows.append(
388
+ (
389
+ netuid_cell, # Netuid
390
+ subnet_name_cell, # Name
391
+ price_cell, # Rate τ_in/α_in
392
+ market_cap_cell, # Market Cap
393
+ emission_cell, # Emission (τ)
394
+ liquidity_cell, # Liquidity (t_in, a_in)
395
+ alpha_out_cell, # Stake α_out
396
+ supply_cell, # Supply
397
+ tempo_cell, # Tempo k/n
398
+ )
399
+ )
400
+
401
+ total_emissions = round(
402
+ sum(float(subnet.emission.tao) for subnet in subnets if subnet.netuid != 0),
403
+ 4,
404
+ )
405
+ total_rate = round(
406
+ sum(float(subnet.price.tao) for subnet in subnets if subnet.netuid != 0), 4
407
+ )
408
+ total_netuids = len(subnets)
409
+ table = define_table(
410
+ total_emissions, total_rate, total_netuids, percentage_string
411
+ )
412
+
413
+ for row in rows:
414
+ table.add_row(*row)
415
+ return table
416
+
417
+ # Live mode
418
+ def create_table_live(subnets, previous_data, block_number):
419
+ def format_cell(
420
+ value, previous_value, unit="", unit_first=False, precision=4, millify=False
421
+ ):
422
+ if previous_value is not None:
423
+ change = value - previous_value
424
+ if abs(change) > 10 ** (-precision):
425
+ formatted_change = (
426
+ f"{change:.{precision}f}"
427
+ if not millify
428
+ else f"{millify_tao(change)}"
429
+ )
430
+ change_text = (
431
+ f" [pale_green3](+{formatted_change})[/pale_green3]"
432
+ if change > 0
433
+ else f" [hot_pink3]({formatted_change})[/hot_pink3]"
434
+ )
435
+ else:
436
+ change_text = ""
437
+ else:
438
+ change_text = ""
439
+ formatted_value = (
440
+ f"{value:,.{precision}f}" if not millify else millify_tao(value)
441
+ )
442
+ return (
443
+ f"{formatted_value} {unit}{change_text}"
444
+ if not unit_first
445
+ else f"{unit} {formatted_value}{change_text}"
446
+ )
447
+
448
+ def format_liquidity_cell(
449
+ tao_val,
450
+ alpha_val,
451
+ prev_tao,
452
+ prev_alpha,
453
+ symbol,
454
+ precision=4,
455
+ millify=False,
456
+ netuid=None,
457
+ ):
458
+ """Format liquidity cell with combined changes"""
459
+
460
+ tao_str = (
461
+ f"τ {millify_tao(tao_val)}"
462
+ if millify
463
+ else f"τ {tao_val:,.{precision}f}"
464
+ )
465
+ _alpha_str = f"{millify_tao(alpha_val) if millify else f'{alpha_val:,.{precision}f}'}"
466
+ alpha_str = (
467
+ f"{_alpha_str} {symbol}" if netuid != 0 else f"{symbol} {_alpha_str}"
468
+ )
469
+
470
+ # Show delta
471
+ if prev_tao is not None and prev_alpha is not None:
472
+ tao_change = tao_val - prev_tao
473
+ alpha_change = alpha_val - prev_alpha
474
+
475
+ # Show changes if either value changed
476
+ if abs(tao_change) > 10 ** (-precision) or abs(alpha_change) > 10 ** (
477
+ -precision
478
+ ):
479
+ if millify:
480
+ tao_change_str = (
481
+ f"+{millify_tao(tao_change)}"
482
+ if tao_change > 0
483
+ else f"{millify_tao(tao_change)}"
484
+ )
485
+ alpha_change_str = (
486
+ f"+{millify_tao(alpha_change)}"
487
+ if alpha_change > 0
488
+ else f"{millify_tao(alpha_change)}"
489
+ )
490
+ else:
491
+ tao_change_str = (
492
+ f"+{tao_change:.{precision}f}"
493
+ if tao_change > 0
494
+ else f"{tao_change:.{precision}f}"
495
+ )
496
+ alpha_change_str = (
497
+ f"+{alpha_change:.{precision}f}"
498
+ if alpha_change > 0
499
+ else f"{alpha_change:.{precision}f}"
500
+ )
501
+
502
+ changes_str = (
503
+ f" [pale_green3]({tao_change_str}[/pale_green3]"
504
+ if tao_change > 0
505
+ else f" [hot_pink3]({tao_change_str}[/hot_pink3]"
506
+ if tao_change < 0
507
+ else f" [white]({tao_change_str}[/white]"
508
+ )
509
+ changes_str += (
510
+ f"[pale_green3],{alpha_change_str})[/pale_green3]"
511
+ if alpha_change > 0
512
+ else f"[hot_pink3],{alpha_change_str})[/hot_pink3]"
513
+ if alpha_change < 0
514
+ else f"[white],{alpha_change_str})[/white]"
515
+ )
516
+ return f"{tao_str}, {alpha_str}{changes_str}"
517
+
518
+ return f"{tao_str}, {alpha_str}"
519
+
520
+ rows = []
521
+ current_data = {} # To store current values for comparison in the next update
522
+ _, percentage_string = calculate_emission_stats(subnets, block_number)
523
+
524
+ for subnet in subnets:
525
+ netuid = subnet.netuid
526
+ symbol = f"{subnet.symbol}\u200e"
527
+
528
+ if netuid == 0:
529
+ emission_tao = 0.0
530
+ else:
531
+ emission_tao = subnet.emission.tao
532
+
533
+ market_cap = (subnet.alpha_in.tao + subnet.alpha_out.tao) * subnet.price.tao
534
+ supply = subnet.alpha_in.tao + subnet.alpha_out.tao
535
+
536
+ # Store current values for comparison
537
+ current_data[netuid] = {
538
+ "market_cap": market_cap,
539
+ "emission_tao": emission_tao,
540
+ "alpha_out": subnet.alpha_out.tao,
541
+ "tao_in": subnet.tao_in.tao,
542
+ "alpha_in": subnet.alpha_in.tao,
543
+ "price": subnet.price.tao,
544
+ "supply": supply,
545
+ "blocks_since_last_step": subnet.blocks_since_last_step,
546
+ }
547
+ prev = previous_data.get(netuid, {}) if previous_data else {}
548
+
549
+ # Prepare cells
550
+ if netuid == 0:
551
+ unit_first = True
552
+ else:
553
+ unit_first = False
554
+
555
+ netuid_cell = str(netuid)
556
+ subnet_name_cell = (
557
+ f"[{COLOR_PALETTE['GENERAL']['SYMBOL']}]{subnet.symbol if netuid != 0 else 'τ'}[/{COLOR_PALETTE['GENERAL']['SYMBOL']}]"
558
+ f" {get_subnet_name(subnet)}"
559
+ )
560
+ emission_cell = format_cell(
561
+ emission_tao,
562
+ prev.get("emission_tao"),
563
+ unit="τ",
564
+ unit_first=True,
565
+ precision=4,
566
+ )
567
+ price_cell = format_cell(
568
+ subnet.price.tao,
569
+ prev.get("price"),
570
+ unit=f"τ/{symbol}",
571
+ precision=4,
572
+ millify=False,
573
+ )
574
+
575
+ alpha_out_cell = format_cell(
576
+ subnet.alpha_out.tao,
577
+ prev.get("alpha_out"),
578
+ unit=f"{symbol}",
579
+ unit_first=unit_first,
580
+ precision=5,
581
+ millify=True if not verbose else False,
582
+ )
583
+ liquidity_cell = (
584
+ format_liquidity_cell(
585
+ subnet.tao_in.tao,
586
+ subnet.alpha_in.tao,
587
+ prev.get("tao_in"),
588
+ prev.get("alpha_in"),
589
+ symbol,
590
+ precision=4,
591
+ millify=not verbose,
592
+ netuid=netuid,
593
+ )
594
+ if netuid != 0
595
+ else "-, -"
596
+ )
597
+
598
+ market_cap_cell = format_cell(
599
+ market_cap,
600
+ prev.get("market_cap"),
601
+ unit="τ",
602
+ unit_first=True,
603
+ precision=4,
604
+ millify=True if not verbose else False,
605
+ )
606
+
607
+ # Supply cell
608
+ supply_cell = format_cell(
609
+ supply,
610
+ prev.get("supply"),
611
+ unit=f"{symbol} [#806DAF]/21M",
612
+ unit_first=False,
613
+ precision=2,
614
+ millify=True if not verbose else False,
615
+ )
616
+
617
+ # Tempo cell
618
+ prev_blocks_since_last_step = prev.get("blocks_since_last_step")
619
+ if prev_blocks_since_last_step is not None:
620
+ if subnet.blocks_since_last_step >= prev_blocks_since_last_step:
621
+ block_change = (
622
+ subnet.blocks_since_last_step - prev_blocks_since_last_step
623
+ )
624
+ else:
625
+ # Tempo restarted
626
+ block_change = (
627
+ subnet.blocks_since_last_step + subnet.tempo + 1
628
+ ) - prev_blocks_since_last_step
629
+ if block_change > 0:
630
+ block_change_text = f" [pale_green3](+{block_change})[/pale_green3]"
631
+ elif block_change < 0:
632
+ block_change_text = f" [hot_pink3]({block_change})[/hot_pink3]"
633
+ else:
634
+ block_change_text = ""
635
+ else:
636
+ block_change_text = ""
637
+ tempo_cell = (
638
+ (f"{subnet.blocks_since_last_step}/{subnet.tempo}{block_change_text}")
639
+ if netuid != 0
640
+ else "-/-"
641
+ )
642
+
643
+ rows.append(
644
+ (
645
+ netuid_cell, # Netuid
646
+ subnet_name_cell, # Name
647
+ price_cell, # Rate τ_in/α_in
648
+ market_cap_cell, # Market Cap
649
+ emission_cell, # Emission (τ)
650
+ liquidity_cell, # Liquidity (t_in, a_in)
651
+ alpha_out_cell, # Stake α_out
652
+ supply_cell, # Supply
653
+ tempo_cell, # Tempo k/n
654
+ )
655
+ )
656
+
657
+ # Calculate totals
658
+ total_netuids = len(subnets)
659
+ _total_emissions = sum(
660
+ float(subnet.emission.tao) for subnet in subnets if subnet.netuid != 0
661
+ )
662
+ total_emissions = (
663
+ f"{millify_tao(_total_emissions)}"
664
+ if not verbose
665
+ else f"{_total_emissions:,.2f}"
666
+ )
667
+
668
+ total_rate = sum(
669
+ float(subnet.price.tao) for subnet in subnets if subnet.netuid != 0
670
+ )
671
+ total_rate = (
672
+ f"{millify_tao(total_rate)}" if not verbose else f"{total_rate:,.2f}"
673
+ )
674
+ table = define_table(
675
+ total_emissions, total_rate, total_netuids, percentage_string
676
+ )
677
+
678
+ for row in rows:
679
+ table.add_row(*row)
680
+ return table, current_data
681
+
682
+ # Live mode
683
+ if live:
684
+ refresh_interval = 10 # seconds
685
+
686
+ progress = Progress(
687
+ TextColumn("[progress.description]{task.description}"),
688
+ BarColumn(bar_width=20, style="green", complete_style="green"),
689
+ TextColumn("[progress.percentage]{task.percentage:>3.0f}%"),
690
+ console=console,
691
+ auto_refresh=True,
692
+ )
693
+ progress_task = progress.add_task("Updating:", total=refresh_interval)
694
+
695
+ previous_block = None
696
+ current_block = None
697
+ previous_data = None
698
+
699
+ with Live(console=console, screen=True, auto_refresh=True) as live:
700
+ try:
701
+ while True:
702
+ subnets, block_number = await fetch_subnet_data()
703
+
704
+ # Update block numbers
705
+ previous_block = current_block
706
+ current_block = block_number
707
+ new_blocks = (
708
+ "N/A"
709
+ if previous_block is None
710
+ else str(current_block - previous_block)
711
+ )
712
+
713
+ table, current_data = create_table_live(
714
+ subnets, previous_data, block_number
715
+ )
716
+ previous_data = current_data
717
+ progress.reset(progress_task)
718
+ start_time = asyncio.get_event_loop().time()
719
+
720
+ block_info = (
721
+ f"Previous: [dark_sea_green]{previous_block if previous_block else 'N/A'}[/dark_sea_green] "
722
+ f"Current: [dark_sea_green]{current_block}[/dark_sea_green] "
723
+ f"Diff: [dark_sea_green]{new_blocks}[/dark_sea_green] "
724
+ )
725
+
726
+ message = f"Live view active. Press [bold red]Ctrl + C[/bold red] to exit\n{block_info}"
727
+
728
+ live_render = Group(message, progress, table)
729
+ live.update(live_render)
730
+
731
+ while not progress.finished:
732
+ await asyncio.sleep(0.1)
733
+ elapsed = asyncio.get_event_loop().time() - start_time
734
+ progress.update(progress_task, completed=elapsed)
735
+
736
+ except KeyboardInterrupt:
737
+ pass # Ctrl + C
738
+ else:
739
+ # Non-live mode
740
+ subnets, block_number = await fetch_subnet_data()
741
+ table = create_table(subnets, block_number)
742
+ console.print(table)
743
+
744
+ return
745
+ # TODO: Temporarily returning till we update docs
746
+ display_table = Prompt.ask(
747
+ "\nPress Enter to view column descriptions or type 'q' to skip:",
748
+ choices=["", "q"],
749
+ default="",
750
+ ).lower()
751
+
752
+ if display_table == "q":
753
+ console.print(
754
+ f"[{COLOR_PALETTE['GENERAL']['SUBHEADING_EXTRA_1']}]Column descriptions skipped."
755
+ )
756
+ else:
757
+ header = """
758
+ [bold white]Description[/bold white]: The table displays information about each subnet. The columns are as follows:
759
+ """
760
+ console.print(header)
761
+ description_table = Table(
762
+ show_header=False, box=box.SIMPLE, show_edge=False, show_lines=True
763
+ )
764
+
765
+ fields = [
766
+ ("[bold tan]Netuid[/bold tan]", "The netuid of the subnet."),
767
+ (
768
+ "[bold tan]Symbol[/bold tan]",
769
+ "The symbol for the subnet's dynamic TAO token.",
770
+ ),
771
+ (
772
+ "[bold tan]Emission (τ)[/bold tan]",
773
+ "Shows how the one τ per block emission is distributed among all the subnet pools. For each subnet, this fraction is first calculated by dividing the subnet's alpha token price by the sum of all alpha prices across all the subnets. This fraction of TAO is then added to the TAO Pool (τ_in) of the subnet. This can change every block. \nFor more, see [blue]https://docs.bittensor.com/dynamic-tao/dtao-guide#emissions[/blue].",
774
+ ),
775
+ (
776
+ "[bold tan]TAO Pool (τ_in)[/bold tan]",
777
+ 'Number of TAO in the TAO reserves of the pool for this subnet. Attached to every subnet is a subnet pool, containing a TAO reserve and the alpha reserve. See also "Alpha Pool (α_in)" description. This can change every block. \nFor more, see [blue]https://docs.bittensor.com/dynamic-tao/dtao-guide#subnet-pool[/blue].',
778
+ ),
779
+ (
780
+ "[bold tan]Alpha Pool (α_in)[/bold tan]",
781
+ "Number of subnet alpha tokens in the alpha reserves of the pool for this subnet. This reserve, together with 'TAO Pool (τ_in)', form the subnet pool for every subnet. This can change every block. \nFor more, see [blue]https://docs.bittensor.com/dynamic-tao/dtao-guide#subnet-pool[/blue].",
782
+ ),
783
+ (
784
+ "[bold tan]STAKE (α_out)[/bold tan]",
785
+ "Total stake in the subnet, expressed in the subnet's alpha token currency. This is the sum of all the stakes present in all the hotkeys in this subnet. This can change every block. \nFor more, see [blue]https://docs.bittensor.com/dynamic-tao/dtao-guide#stake-%CE%B1_out-or-alpha-out-%CE%B1_out[/blue].",
786
+ ),
787
+ (
788
+ "[bold tan]RATE (τ_in/α_in)[/bold tan]",
789
+ "Exchange rate between TAO and subnet dTAO token. Calculated as the reserve ratio: (TAO Pool (τ_in) / Alpha Pool (α_in)). Note that the terms relative price, alpha token price, alpha price are the same as exchange rate. This rate can change every block. \nFor more, see [blue]https://docs.bittensor.com/dynamic-tao/dtao-guide#rate-%CF%84_in%CE%B1_in[/blue].",
790
+ ),
791
+ (
792
+ "[bold tan]Tempo (k/n)[/bold tan]",
793
+ 'The tempo status of the subnet. Represented as (k/n) where "k" is the number of blocks elapsed since the last tempo and "n" is the total number of blocks in the tempo. The number "n" is a subnet hyperparameter and does not change every block. \nFor more, see [blue]https://docs.bittensor.com/dynamic-tao/dtao-guide#tempo-kn[/blue].',
794
+ ),
795
+ ]
796
+
797
+ description_table.add_column("Field", no_wrap=True, style="bold tan")
798
+ description_table.add_column("Description", overflow="fold")
799
+ for field_name, description in fields:
800
+ description_table.add_row(field_name, description)
801
+ console.print(description_table)
802
+
803
+
804
+ async def show(
805
+ subtensor: "SubtensorInterface",
806
+ netuid: int,
807
+ max_rows: Optional[int] = None,
808
+ delegate_selection: bool = False,
809
+ verbose: bool = False,
810
+ prompt: bool = True,
811
+ ) -> Optional[str]:
812
+ async def show_root():
813
+ block_hash = await subtensor.substrate.get_chain_head()
814
+ all_subnets = await subtensor.all_subnets(block_hash=block_hash)
815
+ root_info = next((s for s in all_subnets if s.netuid == 0), None)
816
+ if root_info is None:
817
+ print_error("The root subnet does not exist")
818
+ raise typer.Exit()
819
+
820
+ root_state, identities, old_identities = await asyncio.gather(
821
+ subtensor.get_subnet_state(netuid=0, block_hash=block_hash),
822
+ subtensor.query_all_identities(block_hash=block_hash),
823
+ subtensor.get_delegate_identities(block_hash=block_hash),
824
+ )
825
+
826
+ if root_state is None:
827
+ err_console.print("The root subnet does not exist")
828
+ return
829
+
830
+ if len(root_state.hotkeys) == 0:
831
+ err_console.print(
832
+ "The root-subnet is currently empty with 0 UIDs registered."
833
+ )
834
+ return
835
+
836
+ tao_sum = sum(
837
+ [root_state.tao_stake[idx].tao for idx in range(len(root_state.tao_stake))]
838
+ )
839
+
840
+ table = Table(
841
+ title=f"[{COLOR_PALETTE['GENERAL']['HEADER']}]Root Network\n[{COLOR_PALETTE['GENERAL']['SUBHEADING']}]Network: {subtensor.network}[/{COLOR_PALETTE['GENERAL']['SUBHEADING']}]\n",
842
+ show_footer=True,
843
+ show_edge=False,
844
+ header_style="bold white",
845
+ border_style="bright_black",
846
+ style="bold",
847
+ title_justify="center",
848
+ show_lines=False,
849
+ pad_edge=True,
850
+ )
851
+
852
+ table.add_column("[bold white]Position", style="white", justify="center")
853
+ # table.add_column(
854
+ # f"[bold white]Total Stake ({Balance.get_unit(0)})",
855
+ # style=COLOR_PALETTE["POOLS"]["ALPHA_IN"],
856
+ # justify="center",
857
+ # )
858
+ # ------- Temporary columns for testing -------
859
+ # table.add_column(
860
+ # "Alpha (τ)",
861
+ # style=COLOR_PALETTE["POOLS"]["EXTRA_2"],
862
+ # no_wrap=True,
863
+ # justify="right",
864
+ # )
865
+ table.add_column(
866
+ "Tao (τ)",
867
+ style=COLOR_PALETTE["POOLS"]["EXTRA_2"],
868
+ no_wrap=True,
869
+ justify="right",
870
+ footer=f"{tao_sum:.4f} τ" if verbose else f"{millify_tao(tao_sum)} τ",
871
+ )
872
+ # ------- End Temporary columns for testing -------
873
+ table.add_column(
874
+ f"[bold white]Emission ({Balance.get_unit(0)}/block)",
875
+ style=COLOR_PALETTE["POOLS"]["EMISSION"],
876
+ justify="center",
877
+ )
878
+ table.add_column(
879
+ "[bold white]Hotkey",
880
+ style=COLOR_PALETTE["GENERAL"]["HOTKEY"],
881
+ justify="center",
882
+ )
883
+ table.add_column(
884
+ "[bold white]Coldkey",
885
+ style=COLOR_PALETTE["GENERAL"]["COLDKEY"],
886
+ justify="center",
887
+ )
888
+ table.add_column(
889
+ "[bold white]Identity",
890
+ style=COLOR_PALETTE["GENERAL"]["SYMBOL"],
891
+ justify="left",
892
+ )
893
+
894
+ sorted_hotkeys = sorted(
895
+ enumerate(root_state.hotkeys),
896
+ key=lambda x: root_state.tao_stake[x[0]],
897
+ reverse=True,
898
+ )
899
+ sorted_rows = []
900
+ sorted_hks_delegation = []
901
+ for pos, (idx, hk) in enumerate(sorted_hotkeys):
902
+ total_emission_per_block = 0
903
+ for netuid_ in range(len(all_subnets)):
904
+ subnet = all_subnets[netuid_]
905
+ emission_on_subnet = (
906
+ root_state.emission_history[netuid_][idx] / subnet.tempo
907
+ )
908
+ total_emission_per_block += subnet.alpha_to_tao(
909
+ Balance.from_rao(emission_on_subnet)
910
+ )
911
+
912
+ # Get identity for this validator
913
+ coldkey_identity = identities.get(root_state.coldkeys[idx], {}).get(
914
+ "name", ""
915
+ )
916
+ hotkey_identity = old_identities.get(root_state.hotkeys[idx])
917
+ validator_identity = (
918
+ coldkey_identity
919
+ if coldkey_identity
920
+ else (hotkey_identity.display if hotkey_identity else "")
921
+ )
922
+
923
+ sorted_rows.append(
924
+ (
925
+ str((pos + 1)), # Position
926
+ # f"τ {millify_tao(root_state.total_stake[idx].tao)}"
927
+ # if not verbose
928
+ # else f"{root_state.total_stake[idx]}", # Total Stake
929
+ # f"τ {root_state.alpha_stake[idx].tao:.4f}"
930
+ # if verbose
931
+ # else f"τ {millify_tao(root_state.alpha_stake[idx])}", # Alpha Stake
932
+ f"τ {root_state.tao_stake[idx].tao:.4f}"
933
+ if verbose
934
+ else f"τ {millify_tao(root_state.tao_stake[idx])}", # Tao Stake
935
+ f"{total_emission_per_block}", # Emission
936
+ f"{root_state.hotkeys[idx][:6]}"
937
+ if not verbose
938
+ else f"{root_state.hotkeys[idx]}", # Hotkey
939
+ f"{root_state.coldkeys[idx][:6]}"
940
+ if not verbose
941
+ else f"{root_state.coldkeys[idx]}", # Coldkey
942
+ validator_identity, # Identity
943
+ )
944
+ )
945
+ sorted_hks_delegation.append(root_state.hotkeys[idx])
946
+
947
+ for pos, row in enumerate(sorted_rows, 1):
948
+ table_row = []
949
+ # if delegate_selection:
950
+ # table_row.append(str(pos))
951
+ table_row.extend(row)
952
+ table.add_row(*table_row)
953
+ if delegate_selection and pos == max_rows:
954
+ break
955
+ # Print the table
956
+ console.print(table)
957
+ console.print("\n")
958
+
959
+ if not delegate_selection:
960
+ tao_pool = (
961
+ f"{millify_tao(root_info.tao_in.tao)}"
962
+ if not verbose
963
+ else f"{root_info.tao_in.tao:,.4f}"
964
+ )
965
+ stake = (
966
+ f"{millify_tao(root_info.alpha_out.tao)}"
967
+ if not verbose
968
+ else f"{root_info.alpha_out.tao:,.5f}"
969
+ )
970
+ rate = (
971
+ f"{millify_tao(root_info.price.tao)}"
972
+ if not verbose
973
+ else f"{root_info.price.tao:,.4f}"
974
+ )
975
+ console.print(
976
+ f"[{COLOR_PALETTE['GENERAL']['SUBHEADING']}]Root Network (Subnet 0)[/{COLOR_PALETTE['GENERAL']['SUBHEADING']}]"
977
+ f"\n Rate: [{COLOR_PALETTE['GENERAL']['HOTKEY']}]{rate} τ/τ[/{COLOR_PALETTE['GENERAL']['HOTKEY']}]"
978
+ f"\n Emission: [{COLOR_PALETTE['GENERAL']['HOTKEY']}]τ 0[/{COLOR_PALETTE['GENERAL']['HOTKEY']}]"
979
+ f"\n TAO Pool: [{COLOR_PALETTE['POOLS']['ALPHA_IN']}]τ {tao_pool}[/{COLOR_PALETTE['POOLS']['ALPHA_IN']}]"
980
+ f"\n Stake: [{COLOR_PALETTE['STAKE']['STAKE_ALPHA']}]τ {stake}[/{COLOR_PALETTE['STAKE']['STAKE_ALPHA']}]"
981
+ f"\n Tempo: [{COLOR_PALETTE['STAKE']['STAKE_ALPHA']}]{root_info.blocks_since_last_step}/{root_info.tempo}[/{COLOR_PALETTE['STAKE']['STAKE_ALPHA']}]"
982
+ )
983
+ console.print(
984
+ """
985
+ Description:
986
+ The table displays the root subnet participants and their metrics.
987
+ The columns are as follows:
988
+ - Position: The sorted position of the hotkey by total TAO.
989
+ - TAO: The sum of all TAO balances for this hotkey accross all subnets.
990
+ - Stake: The stake balance of this hotkey on root (measured in TAO).
991
+ - Emission: The emission accrued to this hotkey across all subnets every block measured in TAO.
992
+ - Hotkey: The hotkey ss58 address.
993
+ - Coldkey: The coldkey ss58 address.
994
+ """
995
+ )
996
+ if delegate_selection:
997
+ valid_uids = [str(row[0]) for row in sorted_rows[:max_rows]]
998
+ while True:
999
+ selection = Prompt.ask(
1000
+ "\nEnter the Position of the delegate you want to stake to [dim](or press Enter to cancel)[/dim]",
1001
+ default="",
1002
+ choices=[""] + valid_uids,
1003
+ show_choices=False,
1004
+ show_default=False,
1005
+ )
1006
+
1007
+ if selection == "":
1008
+ return None
1009
+
1010
+ position = int(selection)
1011
+ idx = position - 1
1012
+ original_idx = sorted_hotkeys[idx][0]
1013
+ selected_hotkey = root_state.hotkeys[original_idx]
1014
+
1015
+ coldkey_identity = identities.get(
1016
+ root_state.coldkeys[original_idx], {}
1017
+ ).get("name", "")
1018
+ hotkey_identity = old_identities.get(selected_hotkey)
1019
+ validator_identity = (
1020
+ coldkey_identity
1021
+ if coldkey_identity
1022
+ else (hotkey_identity.display if hotkey_identity else "")
1023
+ )
1024
+ identity_str = f" ({validator_identity})" if validator_identity else ""
1025
+
1026
+ console.print(
1027
+ f"\nSelected delegate: [{COLOR_PALETTE['GENERAL']['SUBHEADING']}]{selected_hotkey}{identity_str}"
1028
+ )
1029
+ return selected_hotkey
1030
+
1031
+ async def show_subnet(netuid_: int):
1032
+ if not await subtensor.subnet_exists(netuid=netuid):
1033
+ err_console.print(f"[red]Subnet {netuid} does not exist[/red]")
1034
+ raise typer.Exit()
1035
+ block_hash = await subtensor.substrate.get_chain_head()
1036
+ (
1037
+ subnet_info,
1038
+ subnet_state,
1039
+ identities,
1040
+ old_identities,
1041
+ current_burn_cost,
1042
+ ) = await asyncio.gather(
1043
+ subtensor.subnet(netuid=netuid_, block_hash=block_hash),
1044
+ subtensor.get_subnet_state(netuid=netuid_, block_hash=block_hash),
1045
+ subtensor.query_all_identities(block_hash=block_hash),
1046
+ subtensor.get_delegate_identities(block_hash=block_hash),
1047
+ subtensor.get_hyperparameter(
1048
+ param_name="Burn", netuid=netuid_, block_hash=block_hash
1049
+ ),
1050
+ )
1051
+ if subnet_state is None:
1052
+ print_error(f"Subnet {netuid_} does not exist")
1053
+ raise typer.Exit()
1054
+
1055
+ if subnet_info is None:
1056
+ print_error(f"Subnet {netuid_} does not exist")
1057
+ raise typer.Exit()
1058
+
1059
+ if len(subnet_state.hotkeys) == 0:
1060
+ print_error(f"Subnet {netuid_} is currently empty with 0 UIDs registered.")
1061
+ raise typer.Exit()
1062
+
1063
+ # Define table properties
1064
+ table = Table(
1065
+ title=f"[{COLOR_PALETTE['GENERAL']['HEADER']}]Subnet [{COLOR_PALETTE['GENERAL']['SUBHEADING']}]{netuid_}"
1066
+ f"{': ' + get_subnet_name(subnet_info)}"
1067
+ f"\nNetwork: [{COLOR_PALETTE['GENERAL']['SUBHEADING']}]{subtensor.network}[/{COLOR_PALETTE['GENERAL']['SUBHEADING']}]\n",
1068
+ show_footer=True,
1069
+ show_edge=False,
1070
+ header_style="bold white",
1071
+ border_style="bright_black",
1072
+ style="bold",
1073
+ title_justify="center",
1074
+ show_lines=False,
1075
+ pad_edge=True,
1076
+ )
1077
+
1078
+ # For hotkey_block_emission calculation
1079
+ emission_sum = sum(
1080
+ [
1081
+ subnet_state.emission[idx].tao
1082
+ for idx in range(len(subnet_state.emission))
1083
+ ]
1084
+ )
1085
+
1086
+ # For table footers
1087
+ alpha_sum = sum(
1088
+ [
1089
+ subnet_state.alpha_stake[idx].tao
1090
+ for idx in range(len(subnet_state.alpha_stake))
1091
+ ]
1092
+ )
1093
+ stake_sum = sum(
1094
+ [
1095
+ subnet_state.total_stake[idx].tao
1096
+ for idx in range(len(subnet_state.total_stake))
1097
+ ]
1098
+ )
1099
+ tao_sum = sum(
1100
+ [
1101
+ subnet_state.tao_stake[idx].tao * TAO_WEIGHT
1102
+ for idx in range(len(subnet_state.tao_stake))
1103
+ ]
1104
+ )
1105
+ relative_emissions_sum = 0
1106
+ owner_hotkeys = await subtensor.get_owned_hotkeys(subnet_info.owner_coldkey)
1107
+ if subnet_info.owner_hotkey not in owner_hotkeys:
1108
+ owner_hotkeys.append(subnet_info.owner_hotkey)
1109
+
1110
+ owner_identity = identities.get(subnet_info.owner_coldkey, {}).get("name", "")
1111
+ if not owner_identity:
1112
+ # If no coldkey identity found, try each owner hotkey
1113
+ for hotkey in owner_hotkeys:
1114
+ if hotkey_identity := old_identities.get(hotkey):
1115
+ owner_identity = hotkey_identity.display
1116
+ break
1117
+
1118
+ sorted_indices = sorted(
1119
+ range(len(subnet_state.hotkeys)),
1120
+ key=lambda i: (
1121
+ # Sort by owner status first
1122
+ not (
1123
+ subnet_state.coldkeys[i] == subnet_info.owner_coldkey
1124
+ or subnet_state.hotkeys[i] in owner_hotkeys
1125
+ ),
1126
+ # Then sort by stake amount (higher stakes first)
1127
+ -subnet_state.total_stake[i].tao,
1128
+ ),
1129
+ )
1130
+
1131
+ rows = []
1132
+ for idx in sorted_indices:
1133
+ hotkey_block_emission = (
1134
+ subnet_state.emission[idx].tao / emission_sum
1135
+ if emission_sum != 0
1136
+ else 0
1137
+ )
1138
+ relative_emissions_sum += hotkey_block_emission
1139
+
1140
+ # Get identity for this uid
1141
+ coldkey_identity = identities.get(subnet_state.coldkeys[idx], {}).get(
1142
+ "name", ""
1143
+ )
1144
+ hotkey_identity = old_identities.get(subnet_state.hotkeys[idx])
1145
+ uid_identity = (
1146
+ coldkey_identity
1147
+ if coldkey_identity
1148
+ else (hotkey_identity.display if hotkey_identity else "~")
1149
+ )
1150
+
1151
+ if (
1152
+ subnet_state.coldkeys[idx] == subnet_info.owner_coldkey
1153
+ or subnet_state.hotkeys[idx] in owner_hotkeys
1154
+ ):
1155
+ if uid_identity == "~":
1156
+ uid_identity = (
1157
+ "[dark_sea_green3](*Owner controlled)[/dark_sea_green3]"
1158
+ )
1159
+ else:
1160
+ uid_identity = (
1161
+ f"[dark_sea_green3]{uid_identity} (*Owner)[/dark_sea_green3]"
1162
+ )
1163
+
1164
+ # Modify tao stake with TAO_WEIGHT
1165
+ tao_stake = subnet_state.tao_stake[idx] * TAO_WEIGHT
1166
+ rows.append(
1167
+ (
1168
+ str(idx), # UID
1169
+ f"{subnet_state.total_stake[idx].tao:.4f} {subnet_info.symbol}"
1170
+ if verbose
1171
+ else f"{millify_tao(subnet_state.total_stake[idx])} {subnet_info.symbol}", # Stake
1172
+ f"{subnet_state.alpha_stake[idx].tao:.4f} {subnet_info.symbol}"
1173
+ if verbose
1174
+ else f"{millify_tao(subnet_state.alpha_stake[idx])} {subnet_info.symbol}", # Alpha Stake
1175
+ f"τ {tao_stake.tao:.4f}"
1176
+ if verbose
1177
+ else f"τ {millify_tao(tao_stake)}", # Tao Stake
1178
+ # str(subnet_state.dividends[idx]),
1179
+ f"{Balance.from_tao(hotkey_block_emission).set_unit(netuid_).tao:.5f}", # Dividends
1180
+ f"{subnet_state.incentives[idx]:.4f}", # Incentive
1181
+ # f"{Balance.from_tao(hotkey_block_emission).set_unit(netuid_).tao:.5f}", # Emissions relative
1182
+ f"{Balance.from_tao(subnet_state.emission[idx].tao).set_unit(netuid_).tao:.5f} {subnet_info.symbol}", # Emissions
1183
+ f"{subnet_state.hotkeys[idx][:6]}"
1184
+ if not verbose
1185
+ else f"{subnet_state.hotkeys[idx]}", # Hotkey
1186
+ f"{subnet_state.coldkeys[idx][:6]}"
1187
+ if not verbose
1188
+ else f"{subnet_state.coldkeys[idx]}", # Coldkey
1189
+ uid_identity, # Identity
1190
+ )
1191
+ )
1192
+
1193
+ # Add columns to the table
1194
+ table.add_column("UID", style="grey89", no_wrap=True, justify="center")
1195
+ table.add_column(
1196
+ f"Stake ({Balance.get_unit(netuid_)})",
1197
+ style=COLOR_PALETTE["POOLS"]["ALPHA_IN"],
1198
+ no_wrap=True,
1199
+ justify="right",
1200
+ footer=f"{stake_sum:.4f} {subnet_info.symbol}"
1201
+ if verbose
1202
+ else f"{millify_tao(stake_sum)} {subnet_info.symbol}",
1203
+ )
1204
+ # ------- Temporary columns for testing -------
1205
+ table.add_column(
1206
+ f"Alpha ({Balance.get_unit(netuid_)})",
1207
+ style=COLOR_PALETTE["POOLS"]["EXTRA_2"],
1208
+ no_wrap=True,
1209
+ justify="right",
1210
+ footer=f"{alpha_sum:.4f} {subnet_info.symbol}"
1211
+ if verbose
1212
+ else f"{millify_tao(alpha_sum)} {subnet_info.symbol}",
1213
+ )
1214
+ table.add_column(
1215
+ "Tao (τ)",
1216
+ style=COLOR_PALETTE["POOLS"]["EXTRA_2"],
1217
+ no_wrap=True,
1218
+ justify="right",
1219
+ footer=f"{tao_sum:.4f} {subnet_info.symbol}"
1220
+ if verbose
1221
+ else f"{millify_tao(tao_sum)} {subnet_info.symbol}",
1222
+ )
1223
+ # ------- End Temporary columns for testing -------
1224
+ table.add_column(
1225
+ "Dividends",
1226
+ style=COLOR_PALETTE["POOLS"]["EMISSION"],
1227
+ no_wrap=True,
1228
+ justify="center",
1229
+ footer=f"{relative_emissions_sum:.3f}",
1230
+ )
1231
+ table.add_column("Incentive", style="#5fd7ff", no_wrap=True, justify="center")
1232
+
1233
+ # Hiding relative emissions for now
1234
+ # table.add_column(
1235
+ # "Emissions",
1236
+ # style="light_goldenrod2",
1237
+ # no_wrap=True,
1238
+ # justify="center",
1239
+ # footer=f"{relative_emissions_sum:.3f}",
1240
+ # )
1241
+ table.add_column(
1242
+ f"Emissions ({Balance.get_unit(netuid_)})",
1243
+ style=COLOR_PALETTE["POOLS"]["EMISSION"],
1244
+ no_wrap=True,
1245
+ justify="center",
1246
+ footer=str(Balance.from_tao(emission_sum).set_unit(subnet_info.netuid)),
1247
+ )
1248
+ table.add_column(
1249
+ "Hotkey",
1250
+ style=COLOR_PALETTE["GENERAL"]["HOTKEY"],
1251
+ no_wrap=True,
1252
+ justify="center",
1253
+ )
1254
+ table.add_column(
1255
+ "Coldkey",
1256
+ style=COLOR_PALETTE["GENERAL"]["COLDKEY"],
1257
+ no_wrap=True,
1258
+ justify="center",
1259
+ )
1260
+ table.add_column(
1261
+ "Identity",
1262
+ style=COLOR_PALETTE["GENERAL"]["SYMBOL"],
1263
+ no_wrap=True,
1264
+ justify="left",
1265
+ )
1266
+ for pos, row in enumerate(rows, 1):
1267
+ table_row = []
1268
+ table_row.extend(row)
1269
+ table.add_row(*table_row)
1270
+ if delegate_selection and pos == max_rows:
1271
+ break
1272
+
1273
+ # Print the table
1274
+ console.print("\n\n")
1275
+ console.print(table)
1276
+ console.print("\n")
1277
+
1278
+ if not delegate_selection:
1279
+ subnet_name_display = f": {get_subnet_name(subnet_info)}"
1280
+ tao_pool = (
1281
+ f"{millify_tao(subnet_info.tao_in.tao)}"
1282
+ if not verbose
1283
+ else f"{subnet_info.tao_in.tao:,.4f}"
1284
+ )
1285
+ alpha_pool = (
1286
+ f"{millify_tao(subnet_info.alpha_in.tao)}"
1287
+ if not verbose
1288
+ else f"{subnet_info.alpha_in.tao:,.4f}"
1289
+ )
1290
+ current_registration_burn = (
1291
+ Balance.from_rao(int(current_burn_cost))
1292
+ if current_burn_cost
1293
+ else Balance(0)
1294
+ )
1295
+
1296
+ console.print(
1297
+ f"[{COLOR_PALETTE['GENERAL']['SUBHEADING']}]Subnet {netuid_}{subnet_name_display}[/{COLOR_PALETTE['GENERAL']['SUBHEADING']}]"
1298
+ f"\n Owner: [{COLOR_PALETTE['GENERAL']['COLDKEY']}]{subnet_info.owner_coldkey}{' (' + owner_identity + ')' if owner_identity else ''}[/{COLOR_PALETTE['GENERAL']['COLDKEY']}]"
1299
+ f"\n Rate: [{COLOR_PALETTE['GENERAL']['HOTKEY']}]{subnet_info.price.tao:.4f} τ/{subnet_info.symbol}[/{COLOR_PALETTE['GENERAL']['HOTKEY']}]"
1300
+ f"\n Emission: [{COLOR_PALETTE['GENERAL']['HOTKEY']}]τ {subnet_info.emission.tao:,.4f}[/{COLOR_PALETTE['GENERAL']['HOTKEY']}]"
1301
+ f"\n TAO Pool: [{COLOR_PALETTE['POOLS']['ALPHA_IN']}]τ {tao_pool}[/{COLOR_PALETTE['POOLS']['ALPHA_IN']}]"
1302
+ f"\n Alpha Pool: [{COLOR_PALETTE['POOLS']['ALPHA_IN']}]{alpha_pool} {subnet_info.symbol}[/{COLOR_PALETTE['POOLS']['ALPHA_IN']}]"
1303
+ # f"\n Stake: [{COLOR_PALETTE['STAKE']['STAKE_ALPHA']}]{subnet_info.alpha_out.tao:,.5f} {subnet_info.symbol}[/{COLOR_PALETTE['STAKE']['STAKE_ALPHA']}]"
1304
+ f"\n Tempo: [{COLOR_PALETTE['STAKE']['STAKE_ALPHA']}]{subnet_info.blocks_since_last_step}/{subnet_info.tempo}[/{COLOR_PALETTE['STAKE']['STAKE_ALPHA']}]"
1305
+ f"\n Registration cost (recycled): [{COLOR_PALETTE['STAKE']['STAKE_ALPHA']}]τ {current_registration_burn.tao:.4f}[/{COLOR_PALETTE['STAKE']['STAKE_ALPHA']}]"
1306
+ )
1307
+ # console.print(
1308
+ # """
1309
+ # Description:
1310
+ # The table displays the subnet participants and their metrics.
1311
+ # The columns are as follows:
1312
+ # - UID: The hotkey index in the subnet.
1313
+ # - TAO: The sum of all TAO balances for this hotkey accross all subnets.
1314
+ # - Stake: The stake balance of this hotkey on this subnet.
1315
+ # - Weight: The stake-weight of this hotkey on this subnet. Computed as an average of the normalized TAO and Stake columns of this subnet.
1316
+ # - Dividends: Validating dividends earned by the hotkey.
1317
+ # - Incentives: Mining incentives earned by the hotkey (always zero in the RAO demo.)
1318
+ # - Emission: The emission accrued to this hokey on this subnet every block (in staking units).
1319
+ # - Hotkey: The hotkey ss58 address.
1320
+ # - Coldkey: The coldkey ss58 address.
1321
+ # """
1322
+ # )
1323
+
1324
+ if delegate_selection:
1325
+ while True:
1326
+ valid_uids = [str(row[0]) for row in rows[:max_rows]]
1327
+ selection = Prompt.ask(
1328
+ "\nEnter the UID of the delegate you want to stake to [dim](or press Enter to cancel)[/dim]",
1329
+ default="",
1330
+ choices=[""] + valid_uids,
1331
+ show_choices=False,
1332
+ show_default=False,
1333
+ )
1334
+
1335
+ if selection == "":
1336
+ return None
1337
+
1338
+ try:
1339
+ uid = int(selection)
1340
+ # Check if the UID exists in the subnet
1341
+ if uid in [int(row[0]) for row in rows]:
1342
+ row_data = next(row for row in rows if int(row[0]) == uid)
1343
+ hotkey = subnet_state.hotkeys[uid]
1344
+ identity = "" if row_data[9] == "~" else row_data[9]
1345
+ identity_str = f" ({identity})" if identity else ""
1346
+ console.print(
1347
+ f"\nSelected delegate: [{COLOR_PALETTE['GENERAL']['SUBHEADING']}]{hotkey}{identity_str}"
1348
+ )
1349
+ return hotkey
1350
+ else:
1351
+ console.print(
1352
+ f"[red]Invalid UID. Please enter a valid UID from the table above[/red]"
1353
+ )
1354
+ except ValueError:
1355
+ console.print("[red]Please enter a valid number[/red]")
1356
+
1357
+ return None
1358
+
1359
+ if netuid == 0:
1360
+ result = await show_root()
1361
+ return result
1362
+ else:
1363
+ result = await show_subnet(netuid)
1364
+ return result
1365
+
1366
+
1367
+ async def burn_cost(subtensor: "SubtensorInterface") -> Optional[Balance]:
1368
+ """View locking cost of creating a new subnetwork"""
1369
+ with console.status(
1370
+ f":satellite:Retrieving lock cost from {subtensor.network}...",
1371
+ spinner="aesthetic",
1372
+ ):
1373
+ burn_cost = await subtensor.burn_cost()
1374
+ if burn_cost:
1375
+ console.print(
1376
+ f"Subnet burn cost: [{COLOR_PALETTE['STAKE']['STAKE_AMOUNT']}]{burn_cost}"
1377
+ )
1378
+ return burn_cost
1379
+ else:
1380
+ err_console.print(
1381
+ "Subnet burn cost: [red]Failed to get subnet burn cost[/red]"
1382
+ )
1383
+ return None
1384
+
1385
+
1386
+ async def create(
1387
+ wallet: Wallet, subtensor: "SubtensorInterface", subnet_identity: dict, prompt: bool
1388
+ ):
1389
+ """Register a subnetwork"""
1390
+
1391
+ # Call register command.
1392
+ success = await register_subnetwork_extrinsic(
1393
+ subtensor, wallet, subnet_identity, prompt=prompt
1394
+ )
1395
+ if success and prompt:
1396
+ # Prompt for user to set identity.
1397
+ do_set_identity = Confirm.ask(
1398
+ "Would you like to set your own [blue]identity?[/blue]"
1399
+ )
1400
+
1401
+ if do_set_identity:
1402
+ current_identity = await get_id(
1403
+ subtensor, wallet.coldkeypub.ss58_address, "Current on-chain identity"
1404
+ )
1405
+ if prompt:
1406
+ if not Confirm.ask(
1407
+ "\nCost to register an [blue]Identity[/blue] is [blue]0.1 TAO[/blue],"
1408
+ " are you sure you wish to continue?"
1409
+ ):
1410
+ console.print(":cross_mark: Aborted!")
1411
+ raise typer.Exit()
1412
+
1413
+ identity = prompt_for_identity(
1414
+ current_identity=current_identity,
1415
+ name=None,
1416
+ web_url=None,
1417
+ image_url=None,
1418
+ discord=None,
1419
+ description=None,
1420
+ additional=None,
1421
+ github_repo=None,
1422
+ )
1423
+
1424
+ await set_id(
1425
+ wallet,
1426
+ subtensor,
1427
+ identity["name"],
1428
+ identity["url"],
1429
+ identity["image"],
1430
+ identity["discord"],
1431
+ identity["description"],
1432
+ identity["additional"],
1433
+ identity["github_repo"],
1434
+ prompt,
1435
+ )
1436
+
1437
+
1438
+ async def pow_register(
1439
+ wallet: Wallet,
1440
+ subtensor: "SubtensorInterface",
1441
+ netuid,
1442
+ processors,
1443
+ update_interval,
1444
+ output_in_place,
1445
+ verbose,
1446
+ use_cuda,
1447
+ dev_id,
1448
+ threads_per_block,
1449
+ ):
1450
+ """Register neuron."""
1451
+
1452
+ await register_extrinsic(
1453
+ subtensor,
1454
+ wallet=wallet,
1455
+ netuid=netuid,
1456
+ prompt=True,
1457
+ tpb=threads_per_block,
1458
+ update_interval=update_interval,
1459
+ num_processes=processors,
1460
+ cuda=use_cuda,
1461
+ dev_id=dev_id,
1462
+ output_in_place=output_in_place,
1463
+ log_verbose=verbose,
1464
+ )
1465
+
1466
+
1467
+ async def register(
1468
+ wallet: Wallet, subtensor: "SubtensorInterface", netuid: int, prompt: bool
1469
+ ):
1470
+ """Register neuron by recycling some TAO."""
1471
+
1472
+ # Verify subnet exists
1473
+ print_verbose("Checking subnet status")
1474
+ block_hash = await subtensor.substrate.get_chain_head()
1475
+ if not await subtensor.subnet_exists(netuid=netuid, block_hash=block_hash):
1476
+ err_console.print(f"[red]Subnet {netuid} does not exist[/red]")
1477
+ return
1478
+
1479
+ # Check current recycle amount
1480
+ print_verbose("Fetching recycle amount")
1481
+ current_recycle_, balance = await asyncio.gather(
1482
+ subtensor.get_hyperparameter(
1483
+ param_name="Burn", netuid=netuid, block_hash=block_hash
1484
+ ),
1485
+ subtensor.get_balance(wallet.coldkeypub.ss58_address, block_hash=block_hash),
1486
+ )
1487
+ current_recycle = (
1488
+ Balance.from_rao(int(current_recycle_)) if current_recycle_ else Balance(0)
1489
+ )
1490
+
1491
+ # Check balance is sufficient
1492
+ if balance < current_recycle:
1493
+ err_console.print(
1494
+ f"[red]Insufficient balance {balance} to register neuron. Current recycle is {current_recycle} TAO[/red]"
1495
+ )
1496
+ return
1497
+
1498
+ if prompt:
1499
+ # TODO make this a reusable function, also used in subnets list
1500
+ # Show creation table.
1501
+ table = Table(
1502
+ title=f"\n[{COLOR_PALETTE['GENERAL']['HEADER']}]Register to [{COLOR_PALETTE['GENERAL']['SUBHEADING']}]netuid: {netuid}[/{COLOR_PALETTE['GENERAL']['SUBHEADING']}]"
1503
+ f"\nNetwork: [{COLOR_PALETTE['GENERAL']['SUBHEADING']}]{subtensor.network}[/{COLOR_PALETTE['GENERAL']['SUBHEADING']}]\n",
1504
+ show_footer=True,
1505
+ show_edge=False,
1506
+ header_style="bold white",
1507
+ border_style="bright_black",
1508
+ style="bold",
1509
+ title_justify="center",
1510
+ show_lines=False,
1511
+ pad_edge=True,
1512
+ )
1513
+ table.add_column(
1514
+ "Netuid", style="rgb(253,246,227)", no_wrap=True, justify="center"
1515
+ )
1516
+ table.add_column(
1517
+ "Symbol",
1518
+ style=COLOR_PALETTE["GENERAL"]["SYMBOL"],
1519
+ no_wrap=True,
1520
+ justify="center",
1521
+ )
1522
+ table.add_column(
1523
+ f"Cost ({Balance.get_unit(0)})",
1524
+ style=COLOR_PALETTE["POOLS"]["TAO"],
1525
+ no_wrap=True,
1526
+ justify="center",
1527
+ )
1528
+ table.add_column(
1529
+ "Hotkey",
1530
+ style=COLOR_PALETTE["GENERAL"]["HOTKEY"],
1531
+ no_wrap=True,
1532
+ justify="center",
1533
+ )
1534
+ table.add_column(
1535
+ "Coldkey",
1536
+ style=COLOR_PALETTE["GENERAL"]["COLDKEY"],
1537
+ no_wrap=True,
1538
+ justify="center",
1539
+ )
1540
+ table.add_row(
1541
+ str(netuid),
1542
+ f"{Balance.get_unit(netuid)}",
1543
+ f"τ {current_recycle.tao:.4f}",
1544
+ f"{wallet.hotkey.ss58_address}",
1545
+ f"{wallet.coldkeypub.ss58_address}",
1546
+ )
1547
+ console.print(table)
1548
+ if not (
1549
+ Confirm.ask(
1550
+ f"Your balance is: [{COLOR_PALETTE['GENERAL']['BALANCE']}]{balance}[/{COLOR_PALETTE['GENERAL']['BALANCE']}]\nThe cost to register by recycle is "
1551
+ f"[{COLOR_PALETTE['GENERAL']['COST']}]{current_recycle}[/{COLOR_PALETTE['GENERAL']['COST']}]\nDo you want to continue?",
1552
+ default=False,
1553
+ )
1554
+ ):
1555
+ return
1556
+
1557
+ if netuid == 0:
1558
+ await root_register_extrinsic(subtensor, wallet=wallet)
1559
+ else:
1560
+ await burned_register_extrinsic(
1561
+ subtensor,
1562
+ wallet=wallet,
1563
+ netuid=netuid,
1564
+ prompt=False,
1565
+ old_balance=balance,
1566
+ )
1567
+
1568
+
1569
+ # TODO: Confirm emissions, incentive, Dividends are to be fetched from subnet_state or keep NeuronInfo
1570
+ async def metagraph_cmd(
1571
+ subtensor: Optional["SubtensorInterface"],
1572
+ netuid: Optional[int],
1573
+ reuse_last: bool,
1574
+ html_output: bool,
1575
+ no_cache: bool,
1576
+ display_cols: dict,
1577
+ ):
1578
+ """Prints an entire metagraph."""
1579
+ # TODO allow config to set certain columns
1580
+ if not reuse_last:
1581
+ cast("SubtensorInterface", subtensor)
1582
+ cast(int, netuid)
1583
+ with console.status(
1584
+ f":satellite: Syncing with chain: [white]{subtensor.network}[/white] ...",
1585
+ spinner="aesthetic",
1586
+ ) as status:
1587
+ block_hash = await subtensor.substrate.get_chain_head()
1588
+
1589
+ if not await subtensor.subnet_exists(netuid, block_hash):
1590
+ print_error(f"Subnet with netuid: {netuid} does not exist", status)
1591
+ return False
1592
+
1593
+ (
1594
+ neurons,
1595
+ difficulty_,
1596
+ total_issuance_,
1597
+ block,
1598
+ subnet_state,
1599
+ ) = await asyncio.gather(
1600
+ subtensor.neurons(netuid, block_hash=block_hash),
1601
+ subtensor.get_hyperparameter(
1602
+ param_name="Difficulty", netuid=netuid, block_hash=block_hash
1603
+ ),
1604
+ subtensor.query(
1605
+ module="SubtensorModule",
1606
+ storage_function="TotalIssuance",
1607
+ params=[],
1608
+ block_hash=block_hash,
1609
+ ),
1610
+ subtensor.substrate.get_block_number(block_hash=block_hash),
1611
+ subtensor.get_subnet_state(netuid=netuid),
1612
+ )
1613
+
1614
+ difficulty = int(difficulty_)
1615
+ total_issuance = Balance.from_rao(total_issuance_)
1616
+ metagraph = MiniGraph(
1617
+ netuid=netuid,
1618
+ neurons=neurons,
1619
+ subtensor=subtensor,
1620
+ subnet_state=subnet_state,
1621
+ block=block,
1622
+ )
1623
+ table_data = []
1624
+ db_table = []
1625
+ total_global_stake = 0.0
1626
+ total_local_stake = 0.0
1627
+ total_rank = 0.0
1628
+ total_validator_trust = 0.0
1629
+ total_trust = 0.0
1630
+ total_consensus = 0.0
1631
+ total_incentive = 0.0
1632
+ total_dividends = 0.0
1633
+ total_emission = 0
1634
+ for uid in metagraph.uids:
1635
+ neuron = metagraph.neurons[uid]
1636
+ ep = metagraph.axons[uid]
1637
+ row = [
1638
+ str(neuron.uid),
1639
+ "{:.4f}".format(metagraph.global_stake[uid]),
1640
+ "{:.4f}".format(metagraph.local_stake[uid]),
1641
+ "{:.4f}".format(metagraph.stake_weights[uid]),
1642
+ "{:.5f}".format(metagraph.ranks[uid]),
1643
+ "{:.5f}".format(metagraph.trust[uid]),
1644
+ "{:.5f}".format(metagraph.consensus[uid]),
1645
+ "{:.5f}".format(metagraph.incentive[uid]),
1646
+ "{:.5f}".format(metagraph.dividends[uid]),
1647
+ "{}".format(int(metagraph.emission[uid] * 1000000000)),
1648
+ "{:.5f}".format(metagraph.validator_trust[uid]),
1649
+ "*" if metagraph.validator_permit[uid] else "",
1650
+ str(metagraph.block.item() - metagraph.last_update[uid].item()),
1651
+ str(metagraph.active[uid].item()),
1652
+ (
1653
+ ep.ip + ":" + str(ep.port)
1654
+ if ep.is_serving
1655
+ else "[light_goldenrod2]none[/light_goldenrod2]"
1656
+ ),
1657
+ ep.hotkey[:10],
1658
+ ep.coldkey[:10],
1659
+ ]
1660
+ db_row = [
1661
+ neuron.uid,
1662
+ float(metagraph.global_stake[uid]),
1663
+ float(metagraph.local_stake[uid]),
1664
+ float(metagraph.stake_weights[uid]),
1665
+ float(metagraph.ranks[uid]),
1666
+ float(metagraph.trust[uid]),
1667
+ float(metagraph.consensus[uid]),
1668
+ float(metagraph.incentive[uid]),
1669
+ float(metagraph.dividends[uid]),
1670
+ int(metagraph.emission[uid] * 1000000000),
1671
+ float(metagraph.validator_trust[uid]),
1672
+ bool(metagraph.validator_permit[uid]),
1673
+ metagraph.block.item() - metagraph.last_update[uid].item(),
1674
+ metagraph.active[uid].item(),
1675
+ (ep.ip + ":" + str(ep.port) if ep.is_serving else "ERROR"),
1676
+ ep.hotkey[:10],
1677
+ ep.coldkey[:10],
1678
+ ]
1679
+ db_table.append(db_row)
1680
+ total_global_stake += metagraph.global_stake[uid]
1681
+ total_local_stake += metagraph.local_stake[uid]
1682
+ total_rank += metagraph.ranks[uid]
1683
+ total_validator_trust += metagraph.validator_trust[uid]
1684
+ total_trust += metagraph.trust[uid]
1685
+ total_consensus += metagraph.consensus[uid]
1686
+ total_incentive += metagraph.incentive[uid]
1687
+ total_dividends += metagraph.dividends[uid]
1688
+ total_emission += int(metagraph.emission[uid] * 1000000000)
1689
+ table_data.append(row)
1690
+ metadata_info = {
1691
+ "total_global_stake": "\u03c4 {:.5f}".format(total_global_stake),
1692
+ "total_local_stake": f"{Balance.get_unit(netuid)} "
1693
+ + "{:.5f}".format(total_local_stake),
1694
+ "rank": "{:.5f}".format(total_rank),
1695
+ "validator_trust": "{:.5f}".format(total_validator_trust),
1696
+ "trust": "{:.5f}".format(total_trust),
1697
+ "consensus": "{:.5f}".format(total_consensus),
1698
+ "incentive": "{:.5f}".format(total_incentive),
1699
+ "dividends": "{:.5f}".format(total_dividends),
1700
+ "emission": "\u03c1{}".format(int(total_emission)),
1701
+ "net": f"{subtensor.network}:{metagraph.netuid}",
1702
+ "block": str(metagraph.block.item()),
1703
+ "N": f"{sum(metagraph.active.tolist())}/{metagraph.n.item()}",
1704
+ "N0": str(sum(metagraph.active.tolist())),
1705
+ "N1": str(metagraph.n.item()),
1706
+ "issuance": str(total_issuance),
1707
+ "difficulty": str(difficulty),
1708
+ "total_neurons": str(len(metagraph.uids)),
1709
+ "table_data": json.dumps(table_data),
1710
+ }
1711
+ if not no_cache:
1712
+ update_metadata_table("metagraph", metadata_info)
1713
+ create_table(
1714
+ "metagraph",
1715
+ columns=[
1716
+ ("UID", "INTEGER"),
1717
+ ("GLOBAL_STAKE", "REAL"),
1718
+ ("LOCAL_STAKE", "REAL"),
1719
+ ("STAKE_WEIGHT", "REAL"),
1720
+ ("RANK", "REAL"),
1721
+ ("TRUST", "REAL"),
1722
+ ("CONSENSUS", "REAL"),
1723
+ ("INCENTIVE", "REAL"),
1724
+ ("DIVIDENDS", "REAL"),
1725
+ ("EMISSION", "INTEGER"),
1726
+ ("VTRUST", "REAL"),
1727
+ ("VAL", "INTEGER"),
1728
+ ("UPDATED", "INTEGER"),
1729
+ ("ACTIVE", "INTEGER"),
1730
+ ("AXON", "TEXT"),
1731
+ ("HOTKEY", "TEXT"),
1732
+ ("COLDKEY", "TEXT"),
1733
+ ],
1734
+ rows=db_table,
1735
+ )
1736
+ else:
1737
+ try:
1738
+ metadata_info = get_metadata_table("metagraph")
1739
+ table_data = json.loads(metadata_info["table_data"])
1740
+ except sqlite3.OperationalError:
1741
+ err_console.print(
1742
+ "[red]Error[/red] Unable to retrieve table data. This is usually caused by attempting to use "
1743
+ "`--reuse-last` before running the command a first time. In rare cases, this could also be due to "
1744
+ "a corrupted database. Re-run the command (do not use `--reuse-last`) and see if that resolves your "
1745
+ "issue."
1746
+ )
1747
+ return
1748
+
1749
+ if html_output:
1750
+ try:
1751
+ render_table(
1752
+ table_name="metagraph",
1753
+ table_info=f"Metagraph | "
1754
+ f"net: {metadata_info['net']}, "
1755
+ f"block: {metadata_info['block']}, "
1756
+ f"N: {metadata_info['N']}, "
1757
+ f"stake: {metadata_info['stake']}, "
1758
+ f"issuance: {metadata_info['issuance']}, "
1759
+ f"difficulty: {metadata_info['difficulty']}",
1760
+ columns=[
1761
+ {"title": "UID", "field": "UID"},
1762
+ {
1763
+ "title": "Global Stake",
1764
+ "field": "GLOBAL_STAKE",
1765
+ "formatter": "money",
1766
+ "formatterParams": {"symbol": "τ", "precision": 5},
1767
+ },
1768
+ {
1769
+ "title": "Local Stake",
1770
+ "field": "LOCAL_STAKE",
1771
+ "formatter": "money",
1772
+ "formatterParams": {
1773
+ "symbol": f"{Balance.get_unit(netuid)}",
1774
+ "precision": 5,
1775
+ },
1776
+ },
1777
+ {
1778
+ "title": "Stake Weight",
1779
+ "field": "STAKE_WEIGHT",
1780
+ "formatter": "money",
1781
+ "formatterParams": {"precision": 5},
1782
+ },
1783
+ {
1784
+ "title": "Rank",
1785
+ "field": "RANK",
1786
+ "formatter": "money",
1787
+ "formatterParams": {"precision": 5},
1788
+ },
1789
+ {
1790
+ "title": "Trust",
1791
+ "field": "TRUST",
1792
+ "formatter": "money",
1793
+ "formatterParams": {"precision": 5},
1794
+ },
1795
+ {
1796
+ "title": "Consensus",
1797
+ "field": "CONSENSUS",
1798
+ "formatter": "money",
1799
+ "formatterParams": {"precision": 5},
1800
+ },
1801
+ {
1802
+ "title": "Incentive",
1803
+ "field": "INCENTIVE",
1804
+ "formatter": "money",
1805
+ "formatterParams": {"precision": 5},
1806
+ },
1807
+ {
1808
+ "title": "Dividends",
1809
+ "field": "DIVIDENDS",
1810
+ "formatter": "money",
1811
+ "formatterParams": {"precision": 5},
1812
+ },
1813
+ {"title": "Emission", "field": "EMISSION"},
1814
+ {
1815
+ "title": "VTrust",
1816
+ "field": "VTRUST",
1817
+ "formatter": "money",
1818
+ "formatterParams": {"precision": 5},
1819
+ },
1820
+ {"title": "Validated", "field": "VAL"},
1821
+ {"title": "Updated", "field": "UPDATED"},
1822
+ {"title": "Active", "field": "ACTIVE"},
1823
+ {"title": "Axon", "field": "AXON"},
1824
+ {"title": "Hotkey", "field": "HOTKEY"},
1825
+ {"title": "Coldkey", "field": "COLDKEY"},
1826
+ ],
1827
+ )
1828
+ except sqlite3.OperationalError:
1829
+ err_console.print(
1830
+ "[red]Error[/red] Unable to retrieve table data. This may indicate that your database is corrupted, "
1831
+ "or was not able to load with the most recent data."
1832
+ )
1833
+ return
1834
+ else:
1835
+ cols: dict[str, tuple[int, Column]] = {
1836
+ "UID": (
1837
+ 0,
1838
+ Column(
1839
+ "[bold white]UID",
1840
+ footer=f"[white]{metadata_info['total_neurons']}[/white]",
1841
+ style="white",
1842
+ justify="right",
1843
+ ratio=0.75,
1844
+ ),
1845
+ ),
1846
+ "GLOBAL_STAKE": (
1847
+ 1,
1848
+ Column(
1849
+ "[bold white]GLOBAL STAKE(\u03c4)",
1850
+ footer=metadata_info["total_global_stake"],
1851
+ style="bright_cyan",
1852
+ justify="right",
1853
+ no_wrap=True,
1854
+ ratio=1.6,
1855
+ ),
1856
+ ),
1857
+ "LOCAL_STAKE": (
1858
+ 2,
1859
+ Column(
1860
+ f"[bold white]LOCAL STAKE({Balance.get_unit(netuid)})",
1861
+ footer=metadata_info["total_local_stake"],
1862
+ style="bright_green",
1863
+ justify="right",
1864
+ no_wrap=True,
1865
+ ratio=1.5,
1866
+ ),
1867
+ ),
1868
+ "STAKE_WEIGHT": (
1869
+ 3,
1870
+ Column(
1871
+ f"[bold white]WEIGHT (\u03c4x{Balance.get_unit(netuid)})",
1872
+ style="purple",
1873
+ justify="right",
1874
+ no_wrap=True,
1875
+ ratio=1.3,
1876
+ ),
1877
+ ),
1878
+ "RANK": (
1879
+ 4,
1880
+ Column(
1881
+ "[bold white]RANK",
1882
+ footer=metadata_info["rank"],
1883
+ style="medium_purple",
1884
+ justify="right",
1885
+ no_wrap=True,
1886
+ ratio=1,
1887
+ ),
1888
+ ),
1889
+ "TRUST": (
1890
+ 5,
1891
+ Column(
1892
+ "[bold white]TRUST",
1893
+ footer=metadata_info["trust"],
1894
+ style="dark_sea_green",
1895
+ justify="right",
1896
+ no_wrap=True,
1897
+ ratio=1,
1898
+ ),
1899
+ ),
1900
+ "CONSENSUS": (
1901
+ 6,
1902
+ Column(
1903
+ "[bold white]CONSENSUS",
1904
+ footer=metadata_info["consensus"],
1905
+ style="rgb(42,161,152)",
1906
+ justify="right",
1907
+ no_wrap=True,
1908
+ ratio=1,
1909
+ ),
1910
+ ),
1911
+ "INCENTIVE": (
1912
+ 7,
1913
+ Column(
1914
+ "[bold white]INCENTIVE",
1915
+ footer=metadata_info["incentive"],
1916
+ style="#5fd7ff",
1917
+ justify="right",
1918
+ no_wrap=True,
1919
+ ratio=1,
1920
+ ),
1921
+ ),
1922
+ "DIVIDENDS": (
1923
+ 8,
1924
+ Column(
1925
+ "[bold white]DIVIDENDS",
1926
+ footer=metadata_info["dividends"],
1927
+ style="#8787d7",
1928
+ justify="right",
1929
+ no_wrap=True,
1930
+ ratio=1,
1931
+ ),
1932
+ ),
1933
+ "EMISSION": (
1934
+ 9,
1935
+ Column(
1936
+ "[bold white]EMISSION(\u03c1)",
1937
+ footer=metadata_info["emission"],
1938
+ style="#d7d7ff",
1939
+ justify="right",
1940
+ no_wrap=True,
1941
+ ratio=1.5,
1942
+ ),
1943
+ ),
1944
+ "VTRUST": (
1945
+ 10,
1946
+ Column(
1947
+ "[bold white]VTRUST",
1948
+ footer=metadata_info["validator_trust"],
1949
+ style="magenta",
1950
+ justify="right",
1951
+ no_wrap=True,
1952
+ ratio=1,
1953
+ ),
1954
+ ),
1955
+ "VAL": (
1956
+ 11,
1957
+ Column(
1958
+ "[bold white]VAL",
1959
+ justify="center",
1960
+ style="bright_white",
1961
+ no_wrap=True,
1962
+ ratio=0.7,
1963
+ ),
1964
+ ),
1965
+ "UPDATED": (
1966
+ 12,
1967
+ Column("[bold white]UPDATED", justify="right", no_wrap=True, ratio=1),
1968
+ ),
1969
+ "ACTIVE": (
1970
+ 13,
1971
+ Column(
1972
+ "[bold white]ACTIVE",
1973
+ justify="center",
1974
+ style="#8787ff",
1975
+ no_wrap=True,
1976
+ ratio=1,
1977
+ ),
1978
+ ),
1979
+ "AXON": (
1980
+ 14,
1981
+ Column(
1982
+ "[bold white]AXON",
1983
+ justify="left",
1984
+ style="dark_orange",
1985
+ overflow="fold",
1986
+ ratio=2,
1987
+ ),
1988
+ ),
1989
+ "HOTKEY": (
1990
+ 15,
1991
+ Column(
1992
+ "[bold white]HOTKEY",
1993
+ justify="center",
1994
+ style="bright_magenta",
1995
+ overflow="fold",
1996
+ ratio=1.5,
1997
+ ),
1998
+ ),
1999
+ "COLDKEY": (
2000
+ 16,
2001
+ Column(
2002
+ "[bold white]COLDKEY",
2003
+ justify="center",
2004
+ style="bright_magenta",
2005
+ overflow="fold",
2006
+ ratio=1.5,
2007
+ ),
2008
+ ),
2009
+ }
2010
+ table_cols: list[Column] = []
2011
+ table_cols_indices: list[int] = []
2012
+ for k, (idx, v) in cols.items():
2013
+ if display_cols[k] is True:
2014
+ table_cols_indices.append(idx)
2015
+ table_cols.append(v)
2016
+
2017
+ table = Table(
2018
+ *table_cols,
2019
+ show_footer=True,
2020
+ show_edge=False,
2021
+ header_style="bold white",
2022
+ border_style="bright_black",
2023
+ style="bold",
2024
+ title_style="bold white",
2025
+ title_justify="center",
2026
+ show_lines=False,
2027
+ expand=True,
2028
+ title=(
2029
+ f"[underline dark_orange]Metagraph[/underline dark_orange]\n\n"
2030
+ f"Net: [bright_cyan]{metadata_info['net']}[/bright_cyan], "
2031
+ f"Block: [bright_cyan]{metadata_info['block']}[/bright_cyan], "
2032
+ f"N: [bright_green]{metadata_info['N0']}[/bright_green]/[bright_red]{metadata_info['N1']}[/bright_red], "
2033
+ f"Total Local Stake: [dark_orange]{metadata_info['total_local_stake']}[/dark_orange], "
2034
+ f"Issuance: [bright_blue]{metadata_info['issuance']}[/bright_blue], "
2035
+ f"Difficulty: [bright_cyan]{metadata_info['difficulty']}[/bright_cyan]\n"
2036
+ ),
2037
+ pad_edge=True,
2038
+ )
2039
+
2040
+ if all(x is False for x in display_cols.values()):
2041
+ console.print("You have selected no columns to display in your config.")
2042
+ table.add_row(" " * 256) # allows title to be printed
2043
+ elif any(x is False for x in display_cols.values()):
2044
+ console.print(
2045
+ "Limiting column display output based on your config settings. Hiding columns "
2046
+ f"{', '.join([k for (k, v) in display_cols.items() if v is False])}"
2047
+ )
2048
+ for row in table_data:
2049
+ new_row = [row[idx] for idx in table_cols_indices]
2050
+ table.add_row(*new_row)
2051
+ else:
2052
+ for row in table_data:
2053
+ table.add_row(*row)
2054
+
2055
+ console.print(table)