Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • hive/clive
1 result
Show changes
Commits on Source (4)
......@@ -23,6 +23,7 @@ from clive.__private.ui.operations.hive_power_management.delegate_hive_power.del
)
from clive.__private.ui.operations.hive_power_management.power_down.power_down import PowerDown
from clive.__private.ui.operations.hive_power_management.power_up.power_up import PowerUp
from clive.__private.ui.operations.hive_power_management.withdraw_routes.withdraw_routes import WithdrawRoutes
from clive.__private.ui.operations.operation_base_screen import OperationBaseScreen
from clive.__private.ui.widgets.big_title import BigTitle
from clive.__private.ui.widgets.clive_data_table import CliveDataTable
......@@ -33,6 +34,7 @@ if TYPE_CHECKING:
POWER_UP_TAB_LABEL: Final[str] = "Power up"
POWER_DOWN_TAB_LABEL: Final[str] = "Power down"
WITHDRAW_ROUTES_TAB_LABEL: Final[str] = "Withdraw routes"
DELEGATE_HIVE_POWER_LABEL: Final[str] = "Delegate"
......@@ -59,4 +61,5 @@ class HivePowerManagement(OperationBaseScreen):
with CliveTabbedContent():
yield PowerUp(POWER_UP_TAB_LABEL)
yield PowerDown(POWER_DOWN_TAB_LABEL)
yield WithdrawRoutes(WITHDRAW_ROUTES_TAB_LABEL)
yield DelegateHivePower(DELEGATE_HIVE_POWER_LABEL)
from __future__ import annotations
from datetime import datetime
from typing import TYPE_CHECKING
from textual.widgets import TabPane
from textual import on
from textual.containers import Horizontal
from textual.widgets import Input, Pretty, Static, TabPane
from clive.__private.ui.widgets.clive_widget import CliveWidget
from clive.__private.core.formatters.humanize import humanize_datetime
from clive.__private.core.hive_to_vests import hive_to_vests
from clive.__private.ui.data_providers.hive_power_data_provider import HivePowerDataProvider
from clive.__private.ui.get_css import get_css_from_relative_path
from clive.__private.ui.operations.bindings.operation_action_bindings import OperationActionBindings
from clive.__private.ui.operations.hive_power_management.common_hive_power.hp_vests_factor import HpVestsFactor
from clive.__private.ui.operations.operation_summary.cancel_power_down import CancelPowerDown
from clive.__private.ui.widgets.clive_button import CliveButton
from clive.__private.ui.widgets.clive_checkerboard_table import (
EVEN_STYLE,
ODD_STYLE,
CliveCheckerboardTable,
CliveCheckerBoardTableCell,
CliveCheckerboardTableRow,
)
from clive.__private.ui.widgets.currency_selector.currency_selector_hp_vests import CurrencySelectorHpVests
from clive.__private.ui.widgets.generous_button import GenerousButton
from clive.__private.ui.widgets.inputs.hp_vests_amount_input import HPVestsAmountInput
from clive.models import Asset
from schemas.operations import WithdrawVestingOperation
if TYPE_CHECKING:
from rich.text import TextType
from textual.app import ComposeResult
from clive.__private.core.commands.data_retrieval.hive_power_data import HivePowerData
class PowerDown(TabPane, CliveWidget):
class PlaceTaker(Static):
pass
class WithdrawRoutesDisplay(Pretty):
"""Widget used just to inform user to which account has withdrawal route and how much % it is."""
class PendingPowerDownHeader(Horizontal):
def compose(self) -> ComposeResult:
yield Static("Next power down", classes=EVEN_STYLE)
yield Static("Power down(HP)", classes=ODD_STYLE)
yield Static("Power down(VESTS)", classes=EVEN_STYLE)
yield PlaceTaker()
class PendingPowerDown(CliveCheckerboardTable):
def __init__(self) -> None:
super().__init__(
Static("Pending Power down", id="pending-power-down-title"), PendingPowerDownHeader(), dynamic=True
)
self._next_power_down_date: datetime = datetime.min
"""Used to check whether the power down data has changed since the last refresh."""
self._is_after_first_sync = False
def _mount_new_rows(self, content: HivePowerData) -> None: # type: ignore[override]
if content.next_vesting_withdrawal != self._next_power_down_date or not self._is_after_first_sync:
self._next_power_down_date = content.next_vesting_withdrawal
self._is_after_first_sync = True
with self.app.batch_update():
rows_container = self.query_one(f"#{self.ROWS_CONTAINER_ID}")
rows_container.query("*").remove()
if humanize_datetime(content.next_vesting_withdrawal) == "never":
rows_container.mount(Static("No pending power down", id="no-pending-power-down-info"))
return
rows_container.mount(
CliveCheckerboardTableRow(
CliveCheckerBoardTableCell(humanize_datetime(content.next_vesting_withdrawal), evenness="odd"),
CliveCheckerBoardTableCell(
Asset.pretty_amount(content.next_power_down.hp_balance), evenness="even"
),
CliveCheckerBoardTableCell(
Asset.pretty_amount(content.next_power_down.vests_balance), evenness="odd"
),
CliveButton("Cancel", variant="error"),
)
)
@on(CliveButton.Pressed)
def push_operation_summary_screen(self) -> None:
self.app.push_screen(
CancelPowerDown(self.provider.content.next_vesting_withdrawal, self.provider.content.next_power_down)
)
@property
def provider(self) -> HivePowerDataProvider:
return self.app.query_one(HivePowerDataProvider)
class PowerDown(TabPane, OperationActionBindings):
"""TabPane with all content about power down."""
def __init__(self, title: TextType):
DEFAULT_CSS = get_css_from_relative_path(__file__)
def __init__(self, title: TextType) -> None:
"""
Initialize a TabPane.
Initialize the PowerDown tab-pane.
Args:
----
title: Title of the TabPane (will be displayed in a tab label).
"""
super().__init__(title=title)
self._shares_input = HPVestsAmountInput()
self._instalment_display = Static("", id="instalment-display")
self._instalment_display.display = False
def compose(self) -> ComposeResult:
yield Static("Power down corresponds to a `withdraw vesting` operation", id="operation-name-info")
yield HpVestsFactor(self.provider)
with Horizontal(id="input-with-button"):
yield self._shares_input
yield GenerousButton(self._shares_input, self._get_shares_balance) # type: ignore[arg-type]
yield self._instalment_display
yield Static("Your withdraw routes", id="withdraw-routes-title")
yield WithdrawRoutesDisplay({})
yield PendingPowerDown()
def on_mount(self) -> None:
self.watch(self.provider, "_content", self._update_withdraw_routes, init=False)
def _get_shares_balance(self) -> Asset.Hive | Asset.Vests:
if self._shares_input.selected_asset_type is Asset.Hive:
return self.provider.content.owned_balance.hp_balance
return self.provider.content.owned_balance.vests_balance
@on(Input.Changed)
def calculate_one_withdrawal(self) -> None:
"""The withdrawal is divided into 13 parts - calculate and inform the user of the amount of one of them."""
shares_input = self._shares_input.value_or_none()
if shares_input is None:
self._instalment_display.display = False
self._instalment_display.update("")
return
one_withdrawal = shares_input / 13
self._instalment_display.update(
f"The withdrawal will be divided into 13 parts, one of which is: {Asset.pretty_amount(one_withdrawal)}"
)
self._instalment_display.display = True
@on(CurrencySelectorHpVests.Changed)
def shares_type_changed(self) -> None:
"""Clear input when shares type was changed and hide factor display when vests selected."""
self._shares_input.input.value = ""
if self._shares_input.selected_asset_type is Asset.Vests:
self.query_one(HpVestsFactor).display = False
return
self.query_one(HpVestsFactor).display = True
def _create_operation(self) -> WithdrawVestingOperation | None:
asset = self._shares_input.value_or_none()
if asset is None:
return None
if isinstance(asset, Asset.Vests):
return WithdrawVestingOperation(account=self.working_account, vesting_shares=asset)
hp_to_vests = hive_to_vests(asset, self.provider.content.gdpo)
# If the user has passed an amount in `HP` - convert it to `VESTS`. The operation is performed using VESTS.
return WithdrawVestingOperation(account=self.working_account, vesting_shares=hp_to_vests)
def _update_withdraw_routes(self, content: HivePowerData) -> None:
"""Update withdraw routes pretty widget."""
if not content.withdraw_routes:
self.query_one(WithdrawRoutesDisplay).update("You have no withdraw routes")
return
withdraw_routes = {}
for withdraw_route in content.withdraw_routes:
withdraw_routes[withdraw_route.to_account] = f"{withdraw_route.percent / 100}%"
self.query_one(WithdrawRoutesDisplay).update(withdraw_routes)
@property
def provider(self) -> HivePowerDataProvider:
return self.app.query_one(HivePowerDataProvider)
@property
def working_account(self) -> str:
return self.app.world.profile_data.working_account.name
$info-color: $accent;
CliveButton {
width: 1fr;
}
WithdrawRoutesDisplay {
content-align: center middle;
width: 1fr;
}
#withdraw-routes-title {
text-style: bold;
margin-top: 2;
background: $info-color;
width: 1fr;
text-align: center;
}
HPVestsAmountInput {
width: 5fr;
}
#input-with-button {
background: $panel;
padding: 2 4;
height: auto;
}
#instalment-display {
text-style: bold;
background: $info-color;
height: 1;
text-align: center;
}
#operation-name-info {
text-style: bold;
margin-bottom: 1;
background: $info-color;
width: 1fr;
height: 1;
text-align: center;
}
/* Pending power down */
#pending-power-down-title {
text-style: bold;
margin-top: 2;
background: $primary;
width: 1fr;
height: 1;
text-align: center;
}
#no-pending-power-down-info {
text-style: bold;
background: $info-color;
width: 1fr;
height: 1;
text-align: center;
}
PendingPowerDown {
height: auto;
}
PendingPowerDownHeader {
height: 1;
}
PendingPowerDownHeader Static {
text-style: bold;
width: 1fr;
text-align: center;
}
from __future__ import annotations
from typing import TYPE_CHECKING
from textual.widgets import TabPane
from clive.__private.ui.widgets.clive_widget import CliveWidget
if TYPE_CHECKING:
from rich.text import TextType
class WithdrawRoutes(TabPane, CliveWidget):
"""TabPane with all content about setting withdraw routes."""
def __init__(self, title: TextType):
"""
Initialize a TabPane.
Args:
----
title: Title of the TabPane (will be displayed in a tab label).
"""
super().__init__(title=title)
from __future__ import annotations
from typing import TYPE_CHECKING, ClassVar
from clive.__private.core.formatters.humanize import humanize_datetime
from clive.__private.ui.operations.operation_summary.operation_summary import OperationSummary
from clive.__private.ui.widgets.inputs.labelized_input import LabelizedInput
from clive.models import Asset
from schemas.operations import WithdrawVestingOperation
if TYPE_CHECKING:
from datetime import datetime
from textual.app import ComposeResult
from clive.__private.core.commands.data_retrieval.hive_power_data import SharesBalance
class CancelPowerDown(OperationSummary):
BIG_TITLE: ClassVar[str] = "Cancel power down"
def __init__(self, next_power_down_date: datetime, next_power_down: SharesBalance) -> None:
super().__init__()
self._next_power_down_date = next_power_down_date
self._next_power_down = next_power_down
def content(self) -> ComposeResult:
yield LabelizedInput("Next power down", humanize_datetime(self._next_power_down_date))
yield LabelizedInput("Power down(HP)", Asset.pretty_amount(self._next_power_down.hp_balance))
yield LabelizedInput("Power down(VESTS)", Asset.pretty_amount(self._next_power_down.vests_balance))
def _create_operation(self) -> WithdrawVestingOperation:
return WithdrawVestingOperation(
account=self.working_account,
vesting_shares=Asset.vests(0),
)
@property
def working_account(self) -> str:
return self.app.world.profile_data.working_account.name
from __future__ import annotations
from typing import TYPE_CHECKING, Any, ClassVar, Final
from textual.containers import Vertical
from textual.widgets import Static
from clive.__private.ui.widgets.clive_widget import CliveWidget
from clive.exceptions import CliveError
if TYPE_CHECKING:
from textual.app import ComposeResult
from textual.widget import Widget
from clive.__private.ui.widgets.clive_button import CliveButton
ODD_STYLE: Final[str] = "OddColumn"
EVEN_STYLE: Final[str] = "EvenColumn"
class CliveCheckerboardTableError(CliveError):
pass
class InvalidDynamicDefinedError(CliveCheckerboardTableError):
MESSAGE = """
You are trying to create a dynamic checkerboard table without overriding the `provider` property.
Replace it or set the `dynamic` parameter to False if you want to create a static table.
"""
def __init__(self) -> None:
super().__init__(self.MESSAGE)
class PlaceTaker(Static):
pass
class CliveCheckerBoardTableCell(Vertical):
"""3 - row cell of the table. Use `Static` instead if you only want single row."""
DEFAULT_CSS = """
CliveCheckerBoardTableCell {
width: 1fr;
}
CliveCheckerBoardTableCell Static {
text-style: bold;
text-align: center;
}
"""
def __init__(self, text: str, evenness: str = "odd", id_: str | None = None, classes: str | None = None) -> None:
"""
Initialise the checkerboard table cell.
Args:
----
text: Text to be displayed in the cell.
evenness: Evenness of the cell.
id_: The ID of the widget in the DOM.
classes: The CSS classes for the widget.
"""
super().__init__(id=id_, classes=f"{classes} {ODD_STYLE if evenness == 'odd' else EVEN_STYLE}".lstrip())
self._text = text
def compose(self) -> ComposeResult:
yield PlaceTaker()
yield Static(self._text)
yield PlaceTaker()
class CliveCheckerboardTableRow(CliveWidget):
"""Row with checkerboard columns."""
DEFAULT_CSS = """
CliveCheckerboardTableRow {
layout: horizontal;
height: auto;
}
"""
def __init__(self, *cells: CliveCheckerBoardTableCell | Static | CliveButton):
super().__init__()
self._cells = cells
def compose(self) -> ComposeResult:
yield from self._cells
class CliveCheckerboardTable(CliveWidget):
DEFAULT_CSS = """
CliveCheckerboardTable {
layout: vertical;
}
CliveCheckerboardTable Vertical {
height: auto;
}
CliveCheckerboardTable .OddColumn {
background: $primary-background-darken-2;
}
CliveCheckerboardTable .EvenColumn {
background: $primary-background-darken-1;
}
CliveCheckerboardTable #loading-static {
text-align: center;
text-style: bold;
}
"""
ROWS_CONTAINER_ID: ClassVar[str] = "container-with-rows"
"""Id of the container in which the `_mount_new_rows` method should mount the rows."""
def __init__(self, title: Widget, header: Widget, dynamic: bool = False):
super().__init__()
self._title = title
self._header = header
self._dynamic = dynamic
def compose(self) -> ComposeResult:
yield self._title
yield self._header
with Vertical(id=self.ROWS_CONTAINER_ID):
if self._dynamic:
yield Static("Loading...", id="loading-static")
else:
self._mount_new_rows()
def on_mount(self) -> None:
if self._dynamic:
self.watch(self.provider, "_content", self._mount_new_rows, init=False)
def _mount_new_rows(self, content: Any | None = None) -> None:
"""Must be overridden by the inheritance class."""
@property
def provider(self) -> Any:
"""
Must be overridden by the inheritance class.
Raises
------
InvalidDynamicDefinedError: When dynamic has been set to `True` without overriding the provider.
"""
if self._dynamic:
raise InvalidDynamicDefinedError