bittensor-cli 8.4.2__py3-none-any.whl → 9.0.0rc1__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 +1503 -1372
  3. bittensor_cli/src/__init__.py +625 -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 +123 -91
  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 +2043 -0
  19. bittensor_cli/src/commands/sudo.py +529 -26
  20. bittensor_cli/src/commands/wallets.py +231 -535
  21. bittensor_cli/src/commands/weights.py +15 -11
  22. {bittensor_cli-8.4.2.dist-info → bittensor_cli-9.0.0rc1.dist-info}/METADATA +7 -4
  23. bittensor_cli-9.0.0rc1.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.2.dist-info/RECORD +0 -31
  28. {bittensor_cli-8.4.2.dist-info → bittensor_cli-9.0.0rc1.dist-info}/WHEEL +0 -0
  29. {bittensor_cli-8.4.2.dist-info → bittensor_cli-9.0.0rc1.dist-info}/entry_points.txt +0 -0
  30. {bittensor_cli-8.4.2.dist-info → bittensor_cli-9.0.0rc1.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,2043 @@
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
+ all_subnets = await subtensor.all_subnets()
814
+ root_info = next((s for s in all_subnets if s.netuid == 0), None)
815
+ if root_info is None:
816
+ print_error("The root subnet does not exist")
817
+ raise typer.Exit()
818
+
819
+ root_state, identities, old_identities = await asyncio.gather(
820
+ subtensor.get_subnet_state(netuid=0),
821
+ subtensor.query_all_identities(),
822
+ subtensor.get_delegate_identities(),
823
+ )
824
+
825
+ if root_state is None:
826
+ err_console.print("The root subnet does not exist")
827
+ return
828
+
829
+ if len(root_state.hotkeys) == 0:
830
+ err_console.print(
831
+ "The root-subnet is currently empty with 0 UIDs registered."
832
+ )
833
+ return
834
+
835
+ tao_sum = sum(
836
+ [root_state.tao_stake[idx].tao for idx in range(len(root_state.tao_stake))]
837
+ )
838
+
839
+ table = Table(
840
+ title=f"[{COLOR_PALETTE['GENERAL']['HEADER']}]Root Network\n[{COLOR_PALETTE['GENERAL']['SUBHEADING']}]Network: {subtensor.network}[/{COLOR_PALETTE['GENERAL']['SUBHEADING']}]\n",
841
+ show_footer=True,
842
+ show_edge=False,
843
+ header_style="bold white",
844
+ border_style="bright_black",
845
+ style="bold",
846
+ title_justify="center",
847
+ show_lines=False,
848
+ pad_edge=True,
849
+ )
850
+
851
+ table.add_column("[bold white]Position", style="white", justify="center")
852
+ # table.add_column(
853
+ # f"[bold white]Total Stake ({Balance.get_unit(0)})",
854
+ # style=COLOR_PALETTE["POOLS"]["ALPHA_IN"],
855
+ # justify="center",
856
+ # )
857
+ # ------- Temporary columns for testing -------
858
+ # table.add_column(
859
+ # "Alpha (τ)",
860
+ # style=COLOR_PALETTE["POOLS"]["EXTRA_2"],
861
+ # no_wrap=True,
862
+ # justify="right",
863
+ # )
864
+ table.add_column(
865
+ "Tao (τ)",
866
+ style=COLOR_PALETTE["POOLS"]["EXTRA_2"],
867
+ no_wrap=True,
868
+ justify="right",
869
+ footer=f"{tao_sum:.4f} τ" if verbose else f"{millify_tao(tao_sum)} τ",
870
+ )
871
+ # ------- End Temporary columns for testing -------
872
+ table.add_column(
873
+ f"[bold white]Emission ({Balance.get_unit(0)}/block)",
874
+ style=COLOR_PALETTE["POOLS"]["EMISSION"],
875
+ justify="center",
876
+ )
877
+ table.add_column(
878
+ "[bold white]Hotkey",
879
+ style=COLOR_PALETTE["GENERAL"]["HOTKEY"],
880
+ justify="center",
881
+ )
882
+ table.add_column(
883
+ "[bold white]Coldkey",
884
+ style=COLOR_PALETTE["GENERAL"]["COLDKEY"],
885
+ justify="center",
886
+ )
887
+ table.add_column(
888
+ "[bold white]Identity",
889
+ style=COLOR_PALETTE["GENERAL"]["SYMBOL"],
890
+ justify="left",
891
+ )
892
+
893
+ sorted_hotkeys = sorted(
894
+ enumerate(root_state.hotkeys),
895
+ key=lambda x: root_state.tao_stake[x[0]],
896
+ reverse=True,
897
+ )
898
+ sorted_rows = []
899
+ sorted_hks_delegation = []
900
+ for pos, (idx, hk) in enumerate(sorted_hotkeys):
901
+ total_emission_per_block = 0
902
+ for netuid_ in range(len(all_subnets)):
903
+ subnet = all_subnets[netuid_]
904
+ emission_on_subnet = (
905
+ root_state.emission_history[netuid_][idx] / subnet.tempo
906
+ )
907
+ total_emission_per_block += subnet.alpha_to_tao(
908
+ Balance.from_rao(emission_on_subnet)
909
+ )
910
+
911
+ # Get identity for this validator
912
+ coldkey_identity = identities.get(root_state.coldkeys[idx], {}).get(
913
+ "name", ""
914
+ )
915
+ hotkey_identity = old_identities.get(root_state.hotkeys[idx])
916
+ validator_identity = (
917
+ coldkey_identity
918
+ if coldkey_identity
919
+ else (hotkey_identity.display if hotkey_identity else "")
920
+ )
921
+
922
+ sorted_rows.append(
923
+ (
924
+ str((pos + 1)), # Position
925
+ # f"τ {millify_tao(root_state.total_stake[idx].tao)}"
926
+ # if not verbose
927
+ # else f"{root_state.total_stake[idx]}", # Total Stake
928
+ # f"τ {root_state.alpha_stake[idx].tao:.4f}"
929
+ # if verbose
930
+ # else f"τ {millify_tao(root_state.alpha_stake[idx])}", # Alpha Stake
931
+ f"τ {root_state.tao_stake[idx].tao:.4f}"
932
+ if verbose
933
+ else f"τ {millify_tao(root_state.tao_stake[idx])}", # Tao Stake
934
+ f"{total_emission_per_block}", # Emission
935
+ f"{root_state.hotkeys[idx][:6]}"
936
+ if not verbose
937
+ else f"{root_state.hotkeys[idx]}", # Hotkey
938
+ f"{root_state.coldkeys[idx][:6]}"
939
+ if not verbose
940
+ else f"{root_state.coldkeys[idx]}", # Coldkey
941
+ validator_identity, # Identity
942
+ )
943
+ )
944
+ sorted_hks_delegation.append(root_state.hotkeys[idx])
945
+
946
+ for pos, row in enumerate(sorted_rows, 1):
947
+ table_row = []
948
+ # if delegate_selection:
949
+ # table_row.append(str(pos))
950
+ table_row.extend(row)
951
+ table.add_row(*table_row)
952
+ if delegate_selection and pos == max_rows:
953
+ break
954
+ # Print the table
955
+ console.print(table)
956
+ console.print("\n")
957
+
958
+ if not delegate_selection:
959
+ tao_pool = (
960
+ f"{millify_tao(root_info.tao_in.tao)}"
961
+ if not verbose
962
+ else f"{root_info.tao_in.tao:,.4f}"
963
+ )
964
+ stake = (
965
+ f"{millify_tao(root_info.alpha_out.tao)}"
966
+ if not verbose
967
+ else f"{root_info.alpha_out.tao:,.5f}"
968
+ )
969
+ rate = (
970
+ f"{millify_tao(root_info.price.tao)}"
971
+ if not verbose
972
+ else f"{root_info.price.tao:,.4f}"
973
+ )
974
+ console.print(
975
+ f"[{COLOR_PALETTE['GENERAL']['SUBHEADING']}]Root Network (Subnet 0)[/{COLOR_PALETTE['GENERAL']['SUBHEADING']}]"
976
+ f"\n Rate: [{COLOR_PALETTE['GENERAL']['HOTKEY']}]{rate} τ/τ[/{COLOR_PALETTE['GENERAL']['HOTKEY']}]"
977
+ f"\n Emission: [{COLOR_PALETTE['GENERAL']['HOTKEY']}]τ 0[/{COLOR_PALETTE['GENERAL']['HOTKEY']}]"
978
+ f"\n TAO Pool: [{COLOR_PALETTE['POOLS']['ALPHA_IN']}]τ {tao_pool}[/{COLOR_PALETTE['POOLS']['ALPHA_IN']}]"
979
+ f"\n Stake: [{COLOR_PALETTE['STAKE']['STAKE_ALPHA']}]τ {stake}[/{COLOR_PALETTE['STAKE']['STAKE_ALPHA']}]"
980
+ f"\n Tempo: [{COLOR_PALETTE['STAKE']['STAKE_ALPHA']}]{root_info.blocks_since_last_step}/{root_info.tempo}[/{COLOR_PALETTE['STAKE']['STAKE_ALPHA']}]"
981
+ )
982
+ console.print(
983
+ """
984
+ Description:
985
+ The table displays the root subnet participants and their metrics.
986
+ The columns are as follows:
987
+ - Position: The sorted position of the hotkey by total TAO.
988
+ - TAO: The sum of all TAO balances for this hotkey accross all subnets.
989
+ - Stake: The stake balance of this hotkey on root (measured in TAO).
990
+ - Emission: The emission accrued to this hotkey across all subnets every block measured in TAO.
991
+ - Hotkey: The hotkey ss58 address.
992
+ - Coldkey: The coldkey ss58 address.
993
+ """
994
+ )
995
+ if delegate_selection:
996
+ valid_uids = [str(row[0]) for row in sorted_rows[:max_rows]]
997
+ while True:
998
+ selection = Prompt.ask(
999
+ "\nEnter the Position of the delegate you want to stake to [dim](or press Enter to cancel)[/dim]",
1000
+ default="",
1001
+ choices=[""] + valid_uids,
1002
+ show_choices=False,
1003
+ show_default=False,
1004
+ )
1005
+
1006
+ if selection == "":
1007
+ return None
1008
+
1009
+ position = int(selection)
1010
+ idx = position - 1
1011
+ original_idx = sorted_hotkeys[idx][0]
1012
+ selected_hotkey = root_state.hotkeys[original_idx]
1013
+
1014
+ coldkey_identity = identities.get(
1015
+ root_state.coldkeys[original_idx], {}
1016
+ ).get("name", "")
1017
+ hotkey_identity = old_identities.get(selected_hotkey)
1018
+ validator_identity = (
1019
+ coldkey_identity
1020
+ if coldkey_identity
1021
+ else (hotkey_identity.display if hotkey_identity else "")
1022
+ )
1023
+ identity_str = f" ({validator_identity})" if validator_identity else ""
1024
+
1025
+ console.print(
1026
+ f"\nSelected delegate: [{COLOR_PALETTE['GENERAL']['SUBHEADING']}]{selected_hotkey}{identity_str}"
1027
+ )
1028
+ return selected_hotkey
1029
+
1030
+ async def show_subnet(netuid_: int):
1031
+ if not await subtensor.subnet_exists(netuid=netuid):
1032
+ err_console.print(f"[red]Subnet {netuid} does not exist[/red]")
1033
+ raise typer.Exit()
1034
+ (
1035
+ subnet_info,
1036
+ subnet_state,
1037
+ identities,
1038
+ old_identities,
1039
+ ) = await asyncio.gather(
1040
+ subtensor.subnet(netuid=netuid_),
1041
+ subtensor.get_subnet_state(netuid=netuid_),
1042
+ subtensor.query_all_identities(),
1043
+ subtensor.get_delegate_identities(),
1044
+ )
1045
+ if subnet_state is None:
1046
+ print_error(f"Subnet {netuid_} does not exist")
1047
+ raise typer.Exit()
1048
+
1049
+ if subnet_info is None:
1050
+ print_error(f"Subnet {netuid_} does not exist")
1051
+ raise typer.Exit()
1052
+
1053
+ if len(subnet_state.hotkeys) == 0:
1054
+ print_error(f"Subnet {netuid_} is currently empty with 0 UIDs registered.")
1055
+ raise typer.Exit()
1056
+
1057
+ # Define table properties
1058
+ table = Table(
1059
+ title=f"[{COLOR_PALETTE['GENERAL']['HEADER']}]Subnet [{COLOR_PALETTE['GENERAL']['SUBHEADING']}]{netuid_}"
1060
+ f"{': ' + get_subnet_name(subnet_info)}"
1061
+ f"\nNetwork: [{COLOR_PALETTE['GENERAL']['SUBHEADING']}]{subtensor.network}[/{COLOR_PALETTE['GENERAL']['SUBHEADING']}]\n",
1062
+ show_footer=True,
1063
+ show_edge=False,
1064
+ header_style="bold white",
1065
+ border_style="bright_black",
1066
+ style="bold",
1067
+ title_justify="center",
1068
+ show_lines=False,
1069
+ pad_edge=True,
1070
+ )
1071
+
1072
+ # For hotkey_block_emission calculation
1073
+ emission_sum = sum(
1074
+ [
1075
+ subnet_state.emission[idx].tao
1076
+ for idx in range(len(subnet_state.emission))
1077
+ ]
1078
+ )
1079
+
1080
+ # For table footers
1081
+ alpha_sum = sum(
1082
+ [
1083
+ subnet_state.alpha_stake[idx].tao
1084
+ for idx in range(len(subnet_state.alpha_stake))
1085
+ ]
1086
+ )
1087
+ stake_sum = sum(
1088
+ [
1089
+ subnet_state.total_stake[idx].tao
1090
+ for idx in range(len(subnet_state.total_stake))
1091
+ ]
1092
+ )
1093
+ tao_sum = sum(
1094
+ [
1095
+ subnet_state.tao_stake[idx].tao * TAO_WEIGHT
1096
+ for idx in range(len(subnet_state.tao_stake))
1097
+ ]
1098
+ )
1099
+ relative_emissions_sum = 0
1100
+ owner_hotkeys = await subtensor.get_owned_hotkeys(subnet_info.owner_coldkey)
1101
+ if subnet_info.owner_hotkey not in owner_hotkeys:
1102
+ owner_hotkeys.append(subnet_info.owner_hotkey)
1103
+
1104
+ owner_identity = identities.get(subnet_info.owner_coldkey, {}).get("name", "")
1105
+ if not owner_identity:
1106
+ # If no coldkey identity found, try each owner hotkey
1107
+ for hotkey in owner_hotkeys:
1108
+ if hotkey_identity := old_identities.get(hotkey):
1109
+ owner_identity = hotkey_identity.display
1110
+ break
1111
+
1112
+ sorted_indices = sorted(
1113
+ range(len(subnet_state.hotkeys)),
1114
+ key=lambda i: (
1115
+ # Sort by owner status first
1116
+ not (
1117
+ subnet_state.coldkeys[i] == subnet_info.owner_coldkey
1118
+ or subnet_state.hotkeys[i] in owner_hotkeys
1119
+ ),
1120
+ # Then sort by stake amount (higher stakes first)
1121
+ -subnet_state.total_stake[i].tao,
1122
+ ),
1123
+ )
1124
+
1125
+ rows = []
1126
+ for idx in sorted_indices:
1127
+ hotkey_block_emission = (
1128
+ subnet_state.emission[idx].tao / emission_sum
1129
+ if emission_sum != 0
1130
+ else 0
1131
+ )
1132
+ relative_emissions_sum += hotkey_block_emission
1133
+
1134
+ # Get identity for this uid
1135
+ coldkey_identity = identities.get(subnet_state.coldkeys[idx], {}).get(
1136
+ "name", ""
1137
+ )
1138
+ hotkey_identity = old_identities.get(subnet_state.hotkeys[idx])
1139
+ uid_identity = (
1140
+ coldkey_identity
1141
+ if coldkey_identity
1142
+ else (hotkey_identity.display if hotkey_identity else "~")
1143
+ )
1144
+
1145
+ if (
1146
+ subnet_state.coldkeys[idx] == subnet_info.owner_coldkey
1147
+ or subnet_state.hotkeys[idx] in owner_hotkeys
1148
+ ):
1149
+ if uid_identity == "~":
1150
+ uid_identity = (
1151
+ "[dark_sea_green3](*Owner controlled)[/dark_sea_green3]"
1152
+ )
1153
+ else:
1154
+ uid_identity = (
1155
+ f"[dark_sea_green3]{uid_identity} (*Owner)[/dark_sea_green3]"
1156
+ )
1157
+
1158
+ # Modify tao stake with TAO_WEIGHT
1159
+ tao_stake = subnet_state.tao_stake[idx] * TAO_WEIGHT
1160
+ rows.append(
1161
+ (
1162
+ str(idx), # UID
1163
+ f"{subnet_state.total_stake[idx].tao:.4f} {subnet_info.symbol}"
1164
+ if verbose
1165
+ else f"{millify_tao(subnet_state.total_stake[idx])} {subnet_info.symbol}", # Stake
1166
+ f"{subnet_state.alpha_stake[idx].tao:.4f} {subnet_info.symbol}"
1167
+ if verbose
1168
+ else f"{millify_tao(subnet_state.alpha_stake[idx])} {subnet_info.symbol}", # Alpha Stake
1169
+ f"τ {tao_stake.tao:.4f}"
1170
+ if verbose
1171
+ else f"τ {millify_tao(tao_stake)}", # Tao Stake
1172
+ # str(subnet_state.dividends[idx]),
1173
+ f"{Balance.from_tao(hotkey_block_emission).set_unit(netuid_).tao:.5f}", # Dividends
1174
+ f"{subnet_state.incentives[idx]:.4f}", # Incentive
1175
+ # f"{Balance.from_tao(hotkey_block_emission).set_unit(netuid_).tao:.5f}", # Emissions relative
1176
+ f"{Balance.from_tao(subnet_state.emission[idx].tao).set_unit(netuid_).tao:.5f} {subnet_info.symbol}", # Emissions
1177
+ f"{subnet_state.hotkeys[idx][:6]}"
1178
+ if not verbose
1179
+ else f"{subnet_state.hotkeys[idx]}", # Hotkey
1180
+ f"{subnet_state.coldkeys[idx][:6]}"
1181
+ if not verbose
1182
+ else f"{subnet_state.coldkeys[idx]}", # Coldkey
1183
+ uid_identity, # Identity
1184
+ )
1185
+ )
1186
+
1187
+ # Add columns to the table
1188
+ table.add_column("UID", style="grey89", no_wrap=True, justify="center")
1189
+ table.add_column(
1190
+ f"Stake ({Balance.get_unit(netuid_)})",
1191
+ style=COLOR_PALETTE["POOLS"]["ALPHA_IN"],
1192
+ no_wrap=True,
1193
+ justify="right",
1194
+ footer=f"{stake_sum:.4f} {subnet_info.symbol}"
1195
+ if verbose
1196
+ else f"{millify_tao(stake_sum)} {subnet_info.symbol}",
1197
+ )
1198
+ # ------- Temporary columns for testing -------
1199
+ table.add_column(
1200
+ f"Alpha ({Balance.get_unit(netuid_)})",
1201
+ style=COLOR_PALETTE["POOLS"]["EXTRA_2"],
1202
+ no_wrap=True,
1203
+ justify="right",
1204
+ footer=f"{alpha_sum:.4f} {subnet_info.symbol}"
1205
+ if verbose
1206
+ else f"{millify_tao(alpha_sum)} {subnet_info.symbol}",
1207
+ )
1208
+ table.add_column(
1209
+ "Tao (τ)",
1210
+ style=COLOR_PALETTE["POOLS"]["EXTRA_2"],
1211
+ no_wrap=True,
1212
+ justify="right",
1213
+ footer=f"{tao_sum:.4f} {subnet_info.symbol}"
1214
+ if verbose
1215
+ else f"{millify_tao(tao_sum)} {subnet_info.symbol}",
1216
+ )
1217
+ # ------- End Temporary columns for testing -------
1218
+ table.add_column(
1219
+ "Dividends",
1220
+ style=COLOR_PALETTE["POOLS"]["EMISSION"],
1221
+ no_wrap=True,
1222
+ justify="center",
1223
+ footer=f"{relative_emissions_sum:.3f}",
1224
+ )
1225
+ table.add_column("Incentive", style="#5fd7ff", no_wrap=True, justify="center")
1226
+
1227
+ # Hiding relative emissions for now
1228
+ # table.add_column(
1229
+ # "Emissions",
1230
+ # style="light_goldenrod2",
1231
+ # no_wrap=True,
1232
+ # justify="center",
1233
+ # footer=f"{relative_emissions_sum:.3f}",
1234
+ # )
1235
+ table.add_column(
1236
+ f"Emissions ({Balance.get_unit(netuid_)})",
1237
+ style=COLOR_PALETTE["POOLS"]["EMISSION"],
1238
+ no_wrap=True,
1239
+ justify="center",
1240
+ footer=str(Balance.from_tao(emission_sum).set_unit(subnet_info.netuid)),
1241
+ )
1242
+ table.add_column(
1243
+ "Hotkey",
1244
+ style=COLOR_PALETTE["GENERAL"]["HOTKEY"],
1245
+ no_wrap=True,
1246
+ justify="center",
1247
+ )
1248
+ table.add_column(
1249
+ "Coldkey",
1250
+ style=COLOR_PALETTE["GENERAL"]["COLDKEY"],
1251
+ no_wrap=True,
1252
+ justify="center",
1253
+ )
1254
+ table.add_column(
1255
+ "Identity",
1256
+ style=COLOR_PALETTE["GENERAL"]["SYMBOL"],
1257
+ no_wrap=True,
1258
+ justify="left",
1259
+ )
1260
+ for pos, row in enumerate(rows, 1):
1261
+ table_row = []
1262
+ table_row.extend(row)
1263
+ table.add_row(*table_row)
1264
+ if delegate_selection and pos == max_rows:
1265
+ break
1266
+
1267
+ # Print the table
1268
+ console.print("\n\n")
1269
+ console.print(table)
1270
+ console.print("\n")
1271
+
1272
+ if not delegate_selection:
1273
+ subnet_name_display = f": {get_subnet_name(subnet_info)}"
1274
+ tao_pool = (
1275
+ f"{millify_tao(subnet_info.tao_in.tao)}"
1276
+ if not verbose
1277
+ else f"{subnet_info.tao_in.tao:,.4f}"
1278
+ )
1279
+ alpha_pool = (
1280
+ f"{millify_tao(subnet_info.alpha_in.tao)}"
1281
+ if not verbose
1282
+ else f"{subnet_info.alpha_in.tao:,.4f}"
1283
+ )
1284
+
1285
+ console.print(
1286
+ f"[{COLOR_PALETTE['GENERAL']['SUBHEADING']}]Subnet {netuid_}{subnet_name_display}[/{COLOR_PALETTE['GENERAL']['SUBHEADING']}]"
1287
+ f"\n Owner: [{COLOR_PALETTE['GENERAL']['COLDKEY']}]{subnet_info.owner_coldkey}{' (' + owner_identity + ')' if owner_identity else ''}[/{COLOR_PALETTE['GENERAL']['COLDKEY']}]"
1288
+ f"\n Rate: [{COLOR_PALETTE['GENERAL']['HOTKEY']}]{subnet_info.price.tao:.4f} τ/{subnet_info.symbol}[/{COLOR_PALETTE['GENERAL']['HOTKEY']}]"
1289
+ f"\n Emission: [{COLOR_PALETTE['GENERAL']['HOTKEY']}]τ {subnet_info.emission.tao:,.4f}[/{COLOR_PALETTE['GENERAL']['HOTKEY']}]"
1290
+ f"\n TAO Pool: [{COLOR_PALETTE['POOLS']['ALPHA_IN']}]τ {tao_pool}[/{COLOR_PALETTE['POOLS']['ALPHA_IN']}]"
1291
+ f"\n Alpha Pool: [{COLOR_PALETTE['POOLS']['ALPHA_IN']}]{alpha_pool} {subnet_info.symbol}[/{COLOR_PALETTE['POOLS']['ALPHA_IN']}]"
1292
+ # f"\n Stake: [{COLOR_PALETTE['STAKE']['STAKE_ALPHA']}]{subnet_info.alpha_out.tao:,.5f} {subnet_info.symbol}[/{COLOR_PALETTE['STAKE']['STAKE_ALPHA']}]"
1293
+ f"\n Tempo: [{COLOR_PALETTE['STAKE']['STAKE_ALPHA']}]{subnet_info.blocks_since_last_step}/{subnet_info.tempo}[/{COLOR_PALETTE['STAKE']['STAKE_ALPHA']}]"
1294
+ )
1295
+ # console.print(
1296
+ # """
1297
+ # Description:
1298
+ # The table displays the subnet participants and their metrics.
1299
+ # The columns are as follows:
1300
+ # - UID: The hotkey index in the subnet.
1301
+ # - TAO: The sum of all TAO balances for this hotkey accross all subnets.
1302
+ # - Stake: The stake balance of this hotkey on this subnet.
1303
+ # - Weight: The stake-weight of this hotkey on this subnet. Computed as an average of the normalized TAO and Stake columns of this subnet.
1304
+ # - Dividends: Validating dividends earned by the hotkey.
1305
+ # - Incentives: Mining incentives earned by the hotkey (always zero in the RAO demo.)
1306
+ # - Emission: The emission accrued to this hokey on this subnet every block (in staking units).
1307
+ # - Hotkey: The hotkey ss58 address.
1308
+ # - Coldkey: The coldkey ss58 address.
1309
+ # """
1310
+ # )
1311
+
1312
+ if delegate_selection:
1313
+ while True:
1314
+ valid_uids = [str(row[0]) for row in rows[:max_rows]]
1315
+ selection = Prompt.ask(
1316
+ "\nEnter the UID of the delegate you want to stake to [dim](or press Enter to cancel)[/dim]",
1317
+ default="",
1318
+ choices=[""] + valid_uids,
1319
+ show_choices=False,
1320
+ show_default=False,
1321
+ )
1322
+
1323
+ if selection == "":
1324
+ return None
1325
+
1326
+ try:
1327
+ uid = int(selection)
1328
+ # Check if the UID exists in the subnet
1329
+ if uid in [int(row[0]) for row in rows]:
1330
+ row_data = next(row for row in rows if int(row[0]) == uid)
1331
+ hotkey = subnet_state.hotkeys[uid]
1332
+ identity = "" if row_data[9] == "~" else row_data[9]
1333
+ identity_str = f" ({identity})" if identity else ""
1334
+ console.print(
1335
+ f"\nSelected delegate: [{COLOR_PALETTE['GENERAL']['SUBHEADING']}]{hotkey}{identity_str}"
1336
+ )
1337
+ return hotkey
1338
+ else:
1339
+ console.print(
1340
+ f"[red]Invalid UID. Please enter a valid UID from the table above[/red]"
1341
+ )
1342
+ except ValueError:
1343
+ console.print("[red]Please enter a valid number[/red]")
1344
+
1345
+ return None
1346
+
1347
+ if netuid == 0:
1348
+ result = await show_root()
1349
+ return result
1350
+ else:
1351
+ result = await show_subnet(netuid)
1352
+ return result
1353
+
1354
+
1355
+ async def burn_cost(subtensor: "SubtensorInterface") -> Optional[Balance]:
1356
+ """View locking cost of creating a new subnetwork"""
1357
+ with console.status(
1358
+ f":satellite:Retrieving lock cost from {subtensor.network}...",
1359
+ spinner="aesthetic",
1360
+ ):
1361
+ burn_cost = await subtensor.burn_cost()
1362
+ if burn_cost:
1363
+ console.print(
1364
+ f"Subnet burn cost: [{COLOR_PALETTE['STAKE']['STAKE_AMOUNT']}]{burn_cost}"
1365
+ )
1366
+ return burn_cost
1367
+ else:
1368
+ err_console.print(
1369
+ "Subnet burn cost: [red]Failed to get subnet burn cost[/red]"
1370
+ )
1371
+ return None
1372
+
1373
+
1374
+ async def create(
1375
+ wallet: Wallet, subtensor: "SubtensorInterface", subnet_identity: dict, prompt: bool
1376
+ ):
1377
+ """Register a subnetwork"""
1378
+
1379
+ # Call register command.
1380
+ success = await register_subnetwork_extrinsic(
1381
+ subtensor, wallet, subnet_identity, prompt=prompt
1382
+ )
1383
+ if success and prompt:
1384
+ # Prompt for user to set identity.
1385
+ do_set_identity = Confirm.ask(
1386
+ "Would you like to set your own [blue]identity?[/blue]"
1387
+ )
1388
+
1389
+ if do_set_identity:
1390
+ current_identity = await get_id(
1391
+ subtensor, wallet.coldkeypub.ss58_address, "Current on-chain identity"
1392
+ )
1393
+ if prompt:
1394
+ if not Confirm.ask(
1395
+ "\nCost to register an [blue]Identity[/blue] is [blue]0.1 TAO[/blue],"
1396
+ " are you sure you wish to continue?"
1397
+ ):
1398
+ console.print(":cross_mark: Aborted!")
1399
+ raise typer.Exit()
1400
+
1401
+ identity = prompt_for_identity(
1402
+ current_identity=current_identity,
1403
+ name=None,
1404
+ web_url=None,
1405
+ image_url=None,
1406
+ discord=None,
1407
+ description=None,
1408
+ additional=None,
1409
+ github_repo=None,
1410
+ )
1411
+
1412
+ await set_id(
1413
+ wallet,
1414
+ subtensor,
1415
+ identity["name"],
1416
+ identity["url"],
1417
+ identity["image"],
1418
+ identity["discord"],
1419
+ identity["description"],
1420
+ identity["additional"],
1421
+ identity["github_repo"],
1422
+ prompt,
1423
+ )
1424
+
1425
+
1426
+ async def pow_register(
1427
+ wallet: Wallet,
1428
+ subtensor: "SubtensorInterface",
1429
+ netuid,
1430
+ processors,
1431
+ update_interval,
1432
+ output_in_place,
1433
+ verbose,
1434
+ use_cuda,
1435
+ dev_id,
1436
+ threads_per_block,
1437
+ ):
1438
+ """Register neuron."""
1439
+
1440
+ await register_extrinsic(
1441
+ subtensor,
1442
+ wallet=wallet,
1443
+ netuid=netuid,
1444
+ prompt=True,
1445
+ tpb=threads_per_block,
1446
+ update_interval=update_interval,
1447
+ num_processes=processors,
1448
+ cuda=use_cuda,
1449
+ dev_id=dev_id,
1450
+ output_in_place=output_in_place,
1451
+ log_verbose=verbose,
1452
+ )
1453
+
1454
+
1455
+ async def register(
1456
+ wallet: Wallet, subtensor: "SubtensorInterface", netuid: int, prompt: bool
1457
+ ):
1458
+ """Register neuron by recycling some TAO."""
1459
+
1460
+ # Verify subnet exists
1461
+ print_verbose("Checking subnet status")
1462
+ block_hash = await subtensor.substrate.get_chain_head()
1463
+ if not await subtensor.subnet_exists(netuid=netuid, block_hash=block_hash):
1464
+ err_console.print(f"[red]Subnet {netuid} does not exist[/red]")
1465
+ return
1466
+
1467
+ # Check current recycle amount
1468
+ print_verbose("Fetching recycle amount")
1469
+ current_recycle_, balance = await asyncio.gather(
1470
+ subtensor.get_hyperparameter(
1471
+ param_name="Burn", netuid=netuid, block_hash=block_hash
1472
+ ),
1473
+ subtensor.get_balance(wallet.coldkeypub.ss58_address, block_hash=block_hash),
1474
+ )
1475
+ current_recycle = (
1476
+ Balance.from_rao(int(current_recycle_)) if current_recycle_ else Balance(0)
1477
+ )
1478
+
1479
+ # Check balance is sufficient
1480
+ if balance < current_recycle:
1481
+ err_console.print(
1482
+ f"[red]Insufficient balance {balance} to register neuron. Current recycle is {current_recycle} TAO[/red]"
1483
+ )
1484
+ return
1485
+
1486
+ if prompt:
1487
+ # TODO make this a reusable function, also used in subnets list
1488
+ # Show creation table.
1489
+ table = Table(
1490
+ title=f"\n[{COLOR_PALETTE['GENERAL']['HEADER']}]Register to [{COLOR_PALETTE['GENERAL']['SUBHEADING']}]netuid: {netuid}[/{COLOR_PALETTE['GENERAL']['SUBHEADING']}]"
1491
+ f"\nNetwork: [{COLOR_PALETTE['GENERAL']['SUBHEADING']}]{subtensor.network}[/{COLOR_PALETTE['GENERAL']['SUBHEADING']}]\n",
1492
+ show_footer=True,
1493
+ show_edge=False,
1494
+ header_style="bold white",
1495
+ border_style="bright_black",
1496
+ style="bold",
1497
+ title_justify="center",
1498
+ show_lines=False,
1499
+ pad_edge=True,
1500
+ )
1501
+ table.add_column(
1502
+ "Netuid", style="rgb(253,246,227)", no_wrap=True, justify="center"
1503
+ )
1504
+ table.add_column(
1505
+ "Symbol",
1506
+ style=COLOR_PALETTE["GENERAL"]["SYMBOL"],
1507
+ no_wrap=True,
1508
+ justify="center",
1509
+ )
1510
+ table.add_column(
1511
+ f"Cost ({Balance.get_unit(0)})",
1512
+ style=COLOR_PALETTE["POOLS"]["TAO"],
1513
+ no_wrap=True,
1514
+ justify="center",
1515
+ )
1516
+ table.add_column(
1517
+ "Hotkey",
1518
+ style=COLOR_PALETTE["GENERAL"]["HOTKEY"],
1519
+ no_wrap=True,
1520
+ justify="center",
1521
+ )
1522
+ table.add_column(
1523
+ "Coldkey",
1524
+ style=COLOR_PALETTE["GENERAL"]["COLDKEY"],
1525
+ no_wrap=True,
1526
+ justify="center",
1527
+ )
1528
+ table.add_row(
1529
+ str(netuid),
1530
+ f"{Balance.get_unit(netuid)}",
1531
+ f"τ {current_recycle.tao:.4f}",
1532
+ f"{wallet.hotkey.ss58_address}",
1533
+ f"{wallet.coldkeypub.ss58_address}",
1534
+ )
1535
+ console.print(table)
1536
+ if not (
1537
+ Confirm.ask(
1538
+ f"Your balance is: [{COLOR_PALETTE['GENERAL']['BALANCE']}]{balance}[/{COLOR_PALETTE['GENERAL']['BALANCE']}]\nThe cost to register by recycle is "
1539
+ f"[{COLOR_PALETTE['GENERAL']['COST']}]{current_recycle}[/{COLOR_PALETTE['GENERAL']['COST']}]\nDo you want to continue?",
1540
+ default=False,
1541
+ )
1542
+ ):
1543
+ return
1544
+
1545
+ if netuid == 0:
1546
+ await root_register_extrinsic(subtensor, wallet=wallet)
1547
+ else:
1548
+ await burned_register_extrinsic(
1549
+ subtensor,
1550
+ wallet=wallet,
1551
+ netuid=netuid,
1552
+ prompt=False,
1553
+ old_balance=balance,
1554
+ )
1555
+
1556
+
1557
+ # TODO: Confirm emissions, incentive, Dividends are to be fetched from subnet_state or keep NeuronInfo
1558
+ async def metagraph_cmd(
1559
+ subtensor: Optional["SubtensorInterface"],
1560
+ netuid: Optional[int],
1561
+ reuse_last: bool,
1562
+ html_output: bool,
1563
+ no_cache: bool,
1564
+ display_cols: dict,
1565
+ ):
1566
+ """Prints an entire metagraph."""
1567
+ # TODO allow config to set certain columns
1568
+ if not reuse_last:
1569
+ cast("SubtensorInterface", subtensor)
1570
+ cast(int, netuid)
1571
+ with console.status(
1572
+ f":satellite: Syncing with chain: [white]{subtensor.network}[/white] ...",
1573
+ spinner="aesthetic",
1574
+ ) as status:
1575
+ block_hash = await subtensor.substrate.get_chain_head()
1576
+
1577
+ if not await subtensor.subnet_exists(netuid, block_hash):
1578
+ print_error(f"Subnet with netuid: {netuid} does not exist", status)
1579
+ return False
1580
+
1581
+ (
1582
+ neurons,
1583
+ difficulty_,
1584
+ total_issuance_,
1585
+ block,
1586
+ subnet_state,
1587
+ ) = await asyncio.gather(
1588
+ subtensor.neurons(netuid, block_hash=block_hash),
1589
+ subtensor.get_hyperparameter(
1590
+ param_name="Difficulty", netuid=netuid, block_hash=block_hash
1591
+ ),
1592
+ subtensor.query(
1593
+ module="SubtensorModule",
1594
+ storage_function="TotalIssuance",
1595
+ params=[],
1596
+ block_hash=block_hash,
1597
+ ),
1598
+ subtensor.substrate.get_block_number(block_hash=block_hash),
1599
+ subtensor.get_subnet_state(netuid=netuid),
1600
+ )
1601
+
1602
+ difficulty = int(difficulty_)
1603
+ total_issuance = Balance.from_rao(total_issuance_)
1604
+ metagraph = MiniGraph(
1605
+ netuid=netuid,
1606
+ neurons=neurons,
1607
+ subtensor=subtensor,
1608
+ subnet_state=subnet_state,
1609
+ block=block,
1610
+ )
1611
+ table_data = []
1612
+ db_table = []
1613
+ total_global_stake = 0.0
1614
+ total_local_stake = 0.0
1615
+ total_rank = 0.0
1616
+ total_validator_trust = 0.0
1617
+ total_trust = 0.0
1618
+ total_consensus = 0.0
1619
+ total_incentive = 0.0
1620
+ total_dividends = 0.0
1621
+ total_emission = 0
1622
+ for uid in metagraph.uids:
1623
+ neuron = metagraph.neurons[uid]
1624
+ ep = metagraph.axons[uid]
1625
+ row = [
1626
+ str(neuron.uid),
1627
+ "{:.4f}".format(metagraph.global_stake[uid]),
1628
+ "{:.4f}".format(metagraph.local_stake[uid]),
1629
+ "{:.4f}".format(metagraph.stake_weights[uid]),
1630
+ "{:.5f}".format(metagraph.ranks[uid]),
1631
+ "{:.5f}".format(metagraph.trust[uid]),
1632
+ "{:.5f}".format(metagraph.consensus[uid]),
1633
+ "{:.5f}".format(metagraph.incentive[uid]),
1634
+ "{:.5f}".format(metagraph.dividends[uid]),
1635
+ "{}".format(int(metagraph.emission[uid] * 1000000000)),
1636
+ "{:.5f}".format(metagraph.validator_trust[uid]),
1637
+ "*" if metagraph.validator_permit[uid] else "",
1638
+ str(metagraph.block.item() - metagraph.last_update[uid].item()),
1639
+ str(metagraph.active[uid].item()),
1640
+ (
1641
+ ep.ip + ":" + str(ep.port)
1642
+ if ep.is_serving
1643
+ else "[light_goldenrod2]none[/light_goldenrod2]"
1644
+ ),
1645
+ ep.hotkey[:10],
1646
+ ep.coldkey[:10],
1647
+ ]
1648
+ db_row = [
1649
+ neuron.uid,
1650
+ float(metagraph.global_stake[uid]),
1651
+ float(metagraph.local_stake[uid]),
1652
+ float(metagraph.stake_weights[uid]),
1653
+ float(metagraph.ranks[uid]),
1654
+ float(metagraph.trust[uid]),
1655
+ float(metagraph.consensus[uid]),
1656
+ float(metagraph.incentive[uid]),
1657
+ float(metagraph.dividends[uid]),
1658
+ int(metagraph.emission[uid] * 1000000000),
1659
+ float(metagraph.validator_trust[uid]),
1660
+ bool(metagraph.validator_permit[uid]),
1661
+ metagraph.block.item() - metagraph.last_update[uid].item(),
1662
+ metagraph.active[uid].item(),
1663
+ (ep.ip + ":" + str(ep.port) if ep.is_serving else "ERROR"),
1664
+ ep.hotkey[:10],
1665
+ ep.coldkey[:10],
1666
+ ]
1667
+ db_table.append(db_row)
1668
+ total_global_stake += metagraph.global_stake[uid]
1669
+ total_local_stake += metagraph.local_stake[uid]
1670
+ total_rank += metagraph.ranks[uid]
1671
+ total_validator_trust += metagraph.validator_trust[uid]
1672
+ total_trust += metagraph.trust[uid]
1673
+ total_consensus += metagraph.consensus[uid]
1674
+ total_incentive += metagraph.incentive[uid]
1675
+ total_dividends += metagraph.dividends[uid]
1676
+ total_emission += int(metagraph.emission[uid] * 1000000000)
1677
+ table_data.append(row)
1678
+ metadata_info = {
1679
+ "total_global_stake": "\u03c4 {:.5f}".format(total_global_stake),
1680
+ "total_local_stake": f"{Balance.get_unit(netuid)} "
1681
+ + "{:.5f}".format(total_local_stake),
1682
+ "rank": "{:.5f}".format(total_rank),
1683
+ "validator_trust": "{:.5f}".format(total_validator_trust),
1684
+ "trust": "{:.5f}".format(total_trust),
1685
+ "consensus": "{:.5f}".format(total_consensus),
1686
+ "incentive": "{:.5f}".format(total_incentive),
1687
+ "dividends": "{:.5f}".format(total_dividends),
1688
+ "emission": "\u03c1{}".format(int(total_emission)),
1689
+ "net": f"{subtensor.network}:{metagraph.netuid}",
1690
+ "block": str(metagraph.block.item()),
1691
+ "N": f"{sum(metagraph.active.tolist())}/{metagraph.n.item()}",
1692
+ "N0": str(sum(metagraph.active.tolist())),
1693
+ "N1": str(metagraph.n.item()),
1694
+ "issuance": str(total_issuance),
1695
+ "difficulty": str(difficulty),
1696
+ "total_neurons": str(len(metagraph.uids)),
1697
+ "table_data": json.dumps(table_data),
1698
+ }
1699
+ if not no_cache:
1700
+ update_metadata_table("metagraph", metadata_info)
1701
+ create_table(
1702
+ "metagraph",
1703
+ columns=[
1704
+ ("UID", "INTEGER"),
1705
+ ("GLOBAL_STAKE", "REAL"),
1706
+ ("LOCAL_STAKE", "REAL"),
1707
+ ("STAKE_WEIGHT", "REAL"),
1708
+ ("RANK", "REAL"),
1709
+ ("TRUST", "REAL"),
1710
+ ("CONSENSUS", "REAL"),
1711
+ ("INCENTIVE", "REAL"),
1712
+ ("DIVIDENDS", "REAL"),
1713
+ ("EMISSION", "INTEGER"),
1714
+ ("VTRUST", "REAL"),
1715
+ ("VAL", "INTEGER"),
1716
+ ("UPDATED", "INTEGER"),
1717
+ ("ACTIVE", "INTEGER"),
1718
+ ("AXON", "TEXT"),
1719
+ ("HOTKEY", "TEXT"),
1720
+ ("COLDKEY", "TEXT"),
1721
+ ],
1722
+ rows=db_table,
1723
+ )
1724
+ else:
1725
+ try:
1726
+ metadata_info = get_metadata_table("metagraph")
1727
+ table_data = json.loads(metadata_info["table_data"])
1728
+ except sqlite3.OperationalError:
1729
+ err_console.print(
1730
+ "[red]Error[/red] Unable to retrieve table data. This is usually caused by attempting to use "
1731
+ "`--reuse-last` before running the command a first time. In rare cases, this could also be due to "
1732
+ "a corrupted database. Re-run the command (do not use `--reuse-last`) and see if that resolves your "
1733
+ "issue."
1734
+ )
1735
+ return
1736
+
1737
+ if html_output:
1738
+ try:
1739
+ render_table(
1740
+ table_name="metagraph",
1741
+ table_info=f"Metagraph | "
1742
+ f"net: {metadata_info['net']}, "
1743
+ f"block: {metadata_info['block']}, "
1744
+ f"N: {metadata_info['N']}, "
1745
+ f"stake: {metadata_info['stake']}, "
1746
+ f"issuance: {metadata_info['issuance']}, "
1747
+ f"difficulty: {metadata_info['difficulty']}",
1748
+ columns=[
1749
+ {"title": "UID", "field": "UID"},
1750
+ {
1751
+ "title": "Global Stake",
1752
+ "field": "GLOBAL_STAKE",
1753
+ "formatter": "money",
1754
+ "formatterParams": {"symbol": "τ", "precision": 5},
1755
+ },
1756
+ {
1757
+ "title": "Local Stake",
1758
+ "field": "LOCAL_STAKE",
1759
+ "formatter": "money",
1760
+ "formatterParams": {
1761
+ "symbol": f"{Balance.get_unit(netuid)}",
1762
+ "precision": 5,
1763
+ },
1764
+ },
1765
+ {
1766
+ "title": "Stake Weight",
1767
+ "field": "STAKE_WEIGHT",
1768
+ "formatter": "money",
1769
+ "formatterParams": {"precision": 5},
1770
+ },
1771
+ {
1772
+ "title": "Rank",
1773
+ "field": "RANK",
1774
+ "formatter": "money",
1775
+ "formatterParams": {"precision": 5},
1776
+ },
1777
+ {
1778
+ "title": "Trust",
1779
+ "field": "TRUST",
1780
+ "formatter": "money",
1781
+ "formatterParams": {"precision": 5},
1782
+ },
1783
+ {
1784
+ "title": "Consensus",
1785
+ "field": "CONSENSUS",
1786
+ "formatter": "money",
1787
+ "formatterParams": {"precision": 5},
1788
+ },
1789
+ {
1790
+ "title": "Incentive",
1791
+ "field": "INCENTIVE",
1792
+ "formatter": "money",
1793
+ "formatterParams": {"precision": 5},
1794
+ },
1795
+ {
1796
+ "title": "Dividends",
1797
+ "field": "DIVIDENDS",
1798
+ "formatter": "money",
1799
+ "formatterParams": {"precision": 5},
1800
+ },
1801
+ {"title": "Emission", "field": "EMISSION"},
1802
+ {
1803
+ "title": "VTrust",
1804
+ "field": "VTRUST",
1805
+ "formatter": "money",
1806
+ "formatterParams": {"precision": 5},
1807
+ },
1808
+ {"title": "Validated", "field": "VAL"},
1809
+ {"title": "Updated", "field": "UPDATED"},
1810
+ {"title": "Active", "field": "ACTIVE"},
1811
+ {"title": "Axon", "field": "AXON"},
1812
+ {"title": "Hotkey", "field": "HOTKEY"},
1813
+ {"title": "Coldkey", "field": "COLDKEY"},
1814
+ ],
1815
+ )
1816
+ except sqlite3.OperationalError:
1817
+ err_console.print(
1818
+ "[red]Error[/red] Unable to retrieve table data. This may indicate that your database is corrupted, "
1819
+ "or was not able to load with the most recent data."
1820
+ )
1821
+ return
1822
+ else:
1823
+ cols: dict[str, tuple[int, Column]] = {
1824
+ "UID": (
1825
+ 0,
1826
+ Column(
1827
+ "[bold white]UID",
1828
+ footer=f"[white]{metadata_info['total_neurons']}[/white]",
1829
+ style="white",
1830
+ justify="right",
1831
+ ratio=0.75,
1832
+ ),
1833
+ ),
1834
+ "GLOBAL_STAKE": (
1835
+ 1,
1836
+ Column(
1837
+ "[bold white]GLOBAL STAKE(\u03c4)",
1838
+ footer=metadata_info["total_global_stake"],
1839
+ style="bright_cyan",
1840
+ justify="right",
1841
+ no_wrap=True,
1842
+ ratio=1.6,
1843
+ ),
1844
+ ),
1845
+ "LOCAL_STAKE": (
1846
+ 2,
1847
+ Column(
1848
+ f"[bold white]LOCAL STAKE({Balance.get_unit(netuid)})",
1849
+ footer=metadata_info["total_local_stake"],
1850
+ style="bright_green",
1851
+ justify="right",
1852
+ no_wrap=True,
1853
+ ratio=1.5,
1854
+ ),
1855
+ ),
1856
+ "STAKE_WEIGHT": (
1857
+ 3,
1858
+ Column(
1859
+ f"[bold white]WEIGHT (\u03c4x{Balance.get_unit(netuid)})",
1860
+ style="purple",
1861
+ justify="right",
1862
+ no_wrap=True,
1863
+ ratio=1.3,
1864
+ ),
1865
+ ),
1866
+ "RANK": (
1867
+ 4,
1868
+ Column(
1869
+ "[bold white]RANK",
1870
+ footer=metadata_info["rank"],
1871
+ style="medium_purple",
1872
+ justify="right",
1873
+ no_wrap=True,
1874
+ ratio=1,
1875
+ ),
1876
+ ),
1877
+ "TRUST": (
1878
+ 5,
1879
+ Column(
1880
+ "[bold white]TRUST",
1881
+ footer=metadata_info["trust"],
1882
+ style="dark_sea_green",
1883
+ justify="right",
1884
+ no_wrap=True,
1885
+ ratio=1,
1886
+ ),
1887
+ ),
1888
+ "CONSENSUS": (
1889
+ 6,
1890
+ Column(
1891
+ "[bold white]CONSENSUS",
1892
+ footer=metadata_info["consensus"],
1893
+ style="rgb(42,161,152)",
1894
+ justify="right",
1895
+ no_wrap=True,
1896
+ ratio=1,
1897
+ ),
1898
+ ),
1899
+ "INCENTIVE": (
1900
+ 7,
1901
+ Column(
1902
+ "[bold white]INCENTIVE",
1903
+ footer=metadata_info["incentive"],
1904
+ style="#5fd7ff",
1905
+ justify="right",
1906
+ no_wrap=True,
1907
+ ratio=1,
1908
+ ),
1909
+ ),
1910
+ "DIVIDENDS": (
1911
+ 8,
1912
+ Column(
1913
+ "[bold white]DIVIDENDS",
1914
+ footer=metadata_info["dividends"],
1915
+ style="#8787d7",
1916
+ justify="right",
1917
+ no_wrap=True,
1918
+ ratio=1,
1919
+ ),
1920
+ ),
1921
+ "EMISSION": (
1922
+ 9,
1923
+ Column(
1924
+ "[bold white]EMISSION(\u03c1)",
1925
+ footer=metadata_info["emission"],
1926
+ style="#d7d7ff",
1927
+ justify="right",
1928
+ no_wrap=True,
1929
+ ratio=1.5,
1930
+ ),
1931
+ ),
1932
+ "VTRUST": (
1933
+ 10,
1934
+ Column(
1935
+ "[bold white]VTRUST",
1936
+ footer=metadata_info["validator_trust"],
1937
+ style="magenta",
1938
+ justify="right",
1939
+ no_wrap=True,
1940
+ ratio=1,
1941
+ ),
1942
+ ),
1943
+ "VAL": (
1944
+ 11,
1945
+ Column(
1946
+ "[bold white]VAL",
1947
+ justify="center",
1948
+ style="bright_white",
1949
+ no_wrap=True,
1950
+ ratio=0.7,
1951
+ ),
1952
+ ),
1953
+ "UPDATED": (
1954
+ 12,
1955
+ Column("[bold white]UPDATED", justify="right", no_wrap=True, ratio=1),
1956
+ ),
1957
+ "ACTIVE": (
1958
+ 13,
1959
+ Column(
1960
+ "[bold white]ACTIVE",
1961
+ justify="center",
1962
+ style="#8787ff",
1963
+ no_wrap=True,
1964
+ ratio=1,
1965
+ ),
1966
+ ),
1967
+ "AXON": (
1968
+ 14,
1969
+ Column(
1970
+ "[bold white]AXON",
1971
+ justify="left",
1972
+ style="dark_orange",
1973
+ overflow="fold",
1974
+ ratio=2,
1975
+ ),
1976
+ ),
1977
+ "HOTKEY": (
1978
+ 15,
1979
+ Column(
1980
+ "[bold white]HOTKEY",
1981
+ justify="center",
1982
+ style="bright_magenta",
1983
+ overflow="fold",
1984
+ ratio=1.5,
1985
+ ),
1986
+ ),
1987
+ "COLDKEY": (
1988
+ 16,
1989
+ Column(
1990
+ "[bold white]COLDKEY",
1991
+ justify="center",
1992
+ style="bright_magenta",
1993
+ overflow="fold",
1994
+ ratio=1.5,
1995
+ ),
1996
+ ),
1997
+ }
1998
+ table_cols: list[Column] = []
1999
+ table_cols_indices: list[int] = []
2000
+ for k, (idx, v) in cols.items():
2001
+ if display_cols[k] is True:
2002
+ table_cols_indices.append(idx)
2003
+ table_cols.append(v)
2004
+
2005
+ table = Table(
2006
+ *table_cols,
2007
+ show_footer=True,
2008
+ show_edge=False,
2009
+ header_style="bold white",
2010
+ border_style="bright_black",
2011
+ style="bold",
2012
+ title_style="bold white",
2013
+ title_justify="center",
2014
+ show_lines=False,
2015
+ expand=True,
2016
+ title=(
2017
+ f"[underline dark_orange]Metagraph[/underline dark_orange]\n\n"
2018
+ f"Net: [bright_cyan]{metadata_info['net']}[/bright_cyan], "
2019
+ f"Block: [bright_cyan]{metadata_info['block']}[/bright_cyan], "
2020
+ f"N: [bright_green]{metadata_info['N0']}[/bright_green]/[bright_red]{metadata_info['N1']}[/bright_red], "
2021
+ f"Total Local Stake: [dark_orange]{metadata_info['total_local_stake']}[/dark_orange], "
2022
+ f"Issuance: [bright_blue]{metadata_info['issuance']}[/bright_blue], "
2023
+ f"Difficulty: [bright_cyan]{metadata_info['difficulty']}[/bright_cyan]\n"
2024
+ ),
2025
+ pad_edge=True,
2026
+ )
2027
+
2028
+ if all(x is False for x in display_cols.values()):
2029
+ console.print("You have selected no columns to display in your config.")
2030
+ table.add_row(" " * 256) # allows title to be printed
2031
+ elif any(x is False for x in display_cols.values()):
2032
+ console.print(
2033
+ "Limiting column display output based on your config settings. Hiding columns "
2034
+ f"{', '.join([k for (k, v) in display_cols.items() if v is False])}"
2035
+ )
2036
+ for row in table_data:
2037
+ new_row = [row[idx] for idx in table_cols_indices]
2038
+ table.add_row(*new_row)
2039
+ else:
2040
+ for row in table_data:
2041
+ table.add_row(*row)
2042
+
2043
+ console.print(table)