Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

HTML Additions: Stake Show and general Improvements #20

Merged
merged 6 commits into from
Aug 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ class Options:
)
reuse_last = typer.Option(
False,
"--reuse-last",
help="Reuse the metagraph data you last retrieved. Only use this if you have already retrieved metagraph"
"data",
)
Expand Down Expand Up @@ -2357,6 +2358,8 @@ def stake_show(
wallet_name: Optional[str] = Options.wallet_name,
wallet_hotkey: Optional[str] = Options.wallet_hotkey,
wallet_path: Optional[str] = Options.wallet_path,
reuse_last: bool = Options.reuse_last,
html_output: bool = Options.html_output,
):
"""
# stake show
Expand Down Expand Up @@ -2393,9 +2396,14 @@ def stake_show(
This command is essential for users who wish to monitor their stake distribution and returns across various
accounts on the Bittensor network. It provides a clear and detailed overview of the user's staking activities.
"""
wallet = self.wallet_ask(wallet_name, wallet_path, wallet_hotkey)
if not reuse_last:
subtensor = self.initialize_chain(network, chain)
wallet = Wallet()
else:
subtensor = None
wallet = self.wallet_ask(wallet_name, wallet_path, wallet_hotkey)
return self._run_command(
stake.show(wallet, self.initialize_chain(network, chain), all_wallets)
stake.show(wallet, subtensor, all_wallets, reuse_last, html_output)
)

def stake_add(
Expand Down
212 changes: 157 additions & 55 deletions src/commands/stake.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import asyncio
import copy
import json
import sqlite3
from contextlib import suppress
from math import floor
from typing import TYPE_CHECKING, Union, Optional, Sequence, cast
Expand All @@ -20,6 +22,11 @@
is_valid_ss58_address,
float_to_u64,
u16_normalized_float,
get_metadata_table,
update_metadata_table,
create_table,
render_table,
render_tree,
)

if TYPE_CHECKING:
Expand Down Expand Up @@ -937,16 +944,14 @@ def normalize_children_and_proportions(
# Commands


async def show(wallet: Wallet, subtensor: "SubtensorInterface", all_wallets: bool):
async def show(
wallet: Wallet,
subtensor: Optional["SubtensorInterface"],
all_wallets: bool,
reuse_last: bool,
html_output: bool,
):
"""Show all stake accounts."""
if all_wallets:
wallets = get_coldkey_wallets_for_path(wallet.path)
else:
wallets = [wallet]

registered_delegate_info = await get_delegates_details_from_github(
Constants.delegates_detail_url
)

async def get_stake_accounts(
wallet_, block_hash: str
Expand Down Expand Up @@ -1087,53 +1092,150 @@ async def get_all_wallet_accounts(
)
return accounts_

with console.status(":satellite:Retrieving account data..."):
block_hash_ = await subtensor.substrate.get_chain_head()
accounts = await get_all_wallet_accounts(block_hash=block_hash_)

total_stake: float = 0.0
total_balance: float = 0.0
total_rate: float = 0.0
for acc in accounts:
total_balance += cast(Balance, acc["balance"]).tao
for key, value in cast(dict, acc["accounts"]).items():
total_stake += cast(Balance, value["stake"]).tao
total_rate += float(value["rate"])
table = Table(
Column(
"[overline white]Coldkey", footer_style="overline white", style="bold white"
),
Column(
"[overline white]Balance",
"\u03c4{:.5f}".format(total_balance),
footer_style="overline white",
style="green",
),
Column("[overline white]Account", footer_style="overline white", style="blue"),
Column(
"[overline white]Stake",
"\u03c4{:.5f}".format(total_stake),
footer_style="overline white",
style="green",
),
Column(
"[overline white]Rate",
"\u03c4{:.5f}/d".format(total_rate),
footer_style="overline white",
style="green",
),
show_footer=True,
pad_edge=False,
box=None,
expand=False,
)
for acc in accounts:
table.add_row(cast(str, acc["name"]), cast(Balance, acc["balance"]), "", "")
for key, value in cast(dict, acc["accounts"]).items():
table.add_row(
"", "", value["name"], value["stake"], str(value["rate"]) + "/d"
if not reuse_last:
cast(subtensor, "SubtensorInterface")
if all_wallets:
wallets = get_coldkey_wallets_for_path(wallet.path)
else:
wallets = [wallet]

registered_delegate_info = await get_delegates_details_from_github(
Constants.delegates_detail_url
)

with console.status(":satellite:Retrieving account data..."):
block_hash_ = await subtensor.substrate.get_chain_head()
accounts = await get_all_wallet_accounts(block_hash=block_hash_)

total_stake: float = 0.0
total_balance: float = 0.0
total_rate: float = 0.0
rows = []
db_rows = []
for acc in accounts:
cast(str, acc["name"])
cast(Balance, acc["balance"])
rows.append([acc["name"], str(acc["balance"]), "", "", ""])
db_rows.append([acc["name"], float(acc["balance"]), None, None, None, 0])
total_balance += cast(Balance, acc["balance"]).tao
for key, value in cast(dict, acc["accounts"]).items():
rows.append(
[
"",
"",
value["name"],
str(value["stake"]),
str(value["rate"]) + "/d",
]
)
db_rows.append(
[
acc["name"],
None,
value["name"],
float(value["stake"]),
float(value["rate"]),
1,
]
)
total_stake += cast(Balance, value["stake"]).tao
total_rate += float(value["rate"])
create_table(
"stakeshow",
[
("COLDKEY", "TEXT"),
("BALANCE", "REAL"),
("ACCOUNT", "TEXT"),
("STAKE", "REAL"),
("RATE", "REAL"),
("CHILD", "INTEGER"),
],
db_rows,
)
metadata = {
"total_stake": "\u03c4{:.5f}".format(total_stake),
"total_balance": "\u03c4{:.5f}".format(total_balance),
"total_rate": "\u03c4{:.5f}/d".format(total_rate),
"rows": json.dumps(rows),
}
update_metadata_table("stakeshow", metadata)
else:
try:
metadata = get_metadata_table("stakeshow")
rows = json.loads(metadata["rows"])
except sqlite3.OperationalError:
err_console.print(
"[red]Error[/red] Unable to retrieve table data. This is usually caused by attempting to use "
"`--reuse-last` before running the command a first time. In rare cases, this could also be due to "
"a corrupted database. Re-run the command (do not use `--reuse-last`) and see if that resolves your "
"issue."
)
console.print(table)
return
if not html_output:
table = Table(
Column(
"[overline white]Coldkey",
footer_style="overline white",
style="bold white",
),
Column(
"[overline white]Balance",
metadata["total_balance"],
footer_style="overline white",
style="green",
),
Column(
"[overline white]Account", footer_style="overline white", style="blue"
),
Column(
"[overline white]Stake",
metadata["total_stake"],
footer_style="overline white",
style="green",
),
Column(
"[overline white]Rate",
metadata["total_rate"],
footer_style="overline white",
style="green",
),
show_footer=True,
pad_edge=False,
box=None,
expand=False,
)
for row in rows:
table.add_row(*row)
console.print(table)
else:
render_tree(
"stakeshow",
f"Stakes | Total Balance: {metadata['total_balance']} - Total Stake: {metadata['total_stake']} "
f"Total Rate: {metadata['total_rate']}",
[
{"title": "Coldkey", "field": "COLDKEY"},
{
"title": "Balance",
"field": "BALANCE",
"formatter": "money",
"formatterParams": {"symbol": "τ", "precision": 5},
},
{"title": "Account", "field": "ACCOUNT"},
{
"title": "Stake",
"field": "STAKE",
"formatter": "money",
"formatterParams": {"symbol": "τ", "precision": 5},
},
{
"title": "Daily Rate",
"field": "RATE",
"formatter": "money",
"formatterParams": {"symbol": "τ", "precision": 5},
},
],
0,
)


async def stake_add(
Expand Down
8 changes: 6 additions & 2 deletions src/commands/subnets.py
Original file line number Diff line number Diff line change
Expand Up @@ -309,14 +309,18 @@ async def _get_all_subnets_info():
"title": "EMISSION",
"field": "EMISSION",
"formatter": "money",
"formatterParams": {"symbolAfter": "%", "precision": 2},
"formatterParams": {
"symbolAfter": "p",
"symbol": "%",
"precision": 2,
},
},
{"title": "Tempo", "field": "TEMPO"},
{
"title": "Recycle",
"field": "RECYCLE",
"formatter": "money",
"formatterParams": {"symbol": "", "precision": 5},
"formatterParams": {"symbol": "τ", "precision": 5},
},
{
"title": "Difficulty",
Expand Down
3 changes: 2 additions & 1 deletion src/templates/table.j2
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@
delete column.customFormatter;
}
});

const None = null;
const table = new Tabulator("#my-table",
{
columns: columns,
Expand All @@ -119,6 +119,7 @@
movableColumns: true,
paginationCounter: "rows",
layout: "fitColumns",
{% if tree %} dataTree:true, {% endif %}
}
)
//Define variables for input elements
Expand Down
Loading
Loading