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 (9)
Showing
with 725 additions and 10 deletions
......@@ -123,7 +123,10 @@ testing_clive:
extends: .testing
script:
- echo -e "${TXT_BLUE}Launching clive concurrent tests...${TXT_CLEAR}"
- python3 -m pytest --ignore "tests/functional/beekeeper" --ignore "tests/tui" -k "not test_autocompletion_time" -n auto --durations 0 --junitxml=report.xml tests/
- python3 -m pytest
--ignore "tests/functional/beekeeper" --ignore "tests/tui" --ignore "tests/functional/cli"
-k "not test_autocompletion_time"
-n auto --durations 0 --junitxml=report.xml tests/
testing_clive_import_times_during_autocompletion:
extends: .testing
......@@ -137,6 +140,12 @@ testing_tui:
- echo -e "${TXT_BLUE}Launching tui tests...${TXT_CLEAR}"
- python3 -m pytest -n auto --durations 0 --junitxml=report.xml tests/tui
testing_cli:
extends: .testing
script:
- echo -e "${TXT_BLUE}Launching cli commands tests...${TXT_CLEAR}"
- python3 -m pytest -n auto --durations 0 --junitxml=report.xml tests/functional/cli
testing_password_private_key_logging:
stage: tests
needs:
......
......@@ -290,9 +290,9 @@ class UpdateNodeData(CommandDataRetrieval[HarvestedDataRaw, SanitizedData, Dynam
def __check_is_governance_is_expiring(self, data: _AccountSanitizedData) -> bool:
warning_period_in_days: Final[int] = 31
return data.core.governance_vote_expiration_ts - timedelta(
days=warning_period_in_days
) > self.__normalize_datetime(datetime.utcnow())
expiration: datetime = data.core.governance_vote_expiration_ts
current_time = self.__normalize_datetime(datetime.utcnow())
return (expiration - current_time).days <= warning_period_in_days
def __get_account_reputation(self, data: Reputation | None) -> int:
return 0 if data is None else int(data.reputation)
......
from __future__ import annotations
from typing import TYPE_CHECKING
from clive.models import Asset
if TYPE_CHECKING:
from clive.models.aliased import DynamicGlobalProperties
def hive_to_vests(amount: int | Asset.Hive, gdpo: DynamicGlobalProperties) -> Asset.Vests:
if isinstance(amount, Asset.Hive):
amount = int(amount.amount)
return Asset.Vests(
amount=int(amount * int(gdpo.total_vesting_shares.amount) / int(gdpo.total_vesting_fund_hive.amount))
)
from __future__ import annotations
from typing import TYPE_CHECKING
from clive.__private.core.hive_to_vests import hive_to_vests
from clive.__private.ui.widgets.dynamic_label import DynamicLabel
from clive.models import Asset
if TYPE_CHECKING:
from clive.__private.core.commands.data_retrieval.hive_power_data import HivePowerData
from clive.__private.ui.data_providers.hive_power_data_provider import HivePowerDataProvider
class HpVestsFactor(DynamicLabel):
DEFAULT_CSS = """
HpVestsFactor {
width: 1fr;
height: 1;
margin-bottom: 1;
align: center middle;
background: $warning;
color: $text;
}
"""
def __init__(self, provider: HivePowerDataProvider):
super().__init__(
obj_to_watch=provider, attribute_name="_content", callback=self._get_hp_vests_factor, init=False
)
def _get_hp_vests_factor(self, content: HivePowerData) -> str:
factor = hive_to_vests(1000, content.gdpo)
return f"HP is calculated to VESTS with the factor: 1.000 HP -> {Asset.pretty_amount(factor)} VESTS"
......@@ -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)
......@@ -2,23 +2,122 @@ from __future__ import annotations
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.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.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 WithdrawRoutesDisplay(Pretty):
"""Widget used just to inform user to which account has withdrawal route and how much % it is."""
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({})
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;
}
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, Any, ClassVar, Final
from textual.containers import Vertical
from textual.widgets import Label, 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;
}
"""
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 Label(self._text)
yield PlaceTaker()
class CliveCheckerboardTableRow(CliveWidget):
"""Row with checkerboard columns."""
DEFAULT_CSS = """
CliveCheckerboardTableRow {
layout: horizontal;
}
"""
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"
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
from __future__ import annotations
from clive.__private.ui.widgets.currency_selector.currency_selector_base import CurrencySelectorBase
from clive.models import Asset
from clive.models.asset import AssetFactoryHolder
class CurrencySelectorHpVests(CurrencySelectorBase[Asset.Hive | Asset.Vests]):
@staticmethod
def _create_selectable() -> dict[str, AssetFactoryHolder[Asset.Hive | Asset.Vests]]:
return {
"HP": AssetFactoryHolder(asset_cls=Asset.Hive, asset_factory=Asset.hive),
"VESTS": AssetFactoryHolder(asset_cls=Asset.Vests, asset_factory=Asset.vests),
}
from __future__ import annotations
from typing import TYPE_CHECKING
from textual import on
from textual.containers import Horizontal, Vertical
from clive.__private.ui.widgets.currency_selector.currency_selector_hp_vests import CurrencySelectorHpVests
from clive.__private.ui.widgets.inputs.clive_validated_input import (
CliveValidatedInput,
)
from clive.__private.validators.asset_amount_validator import AssetAmountValidator
from clive.models import Asset
if TYPE_CHECKING:
from collections.abc import Iterable
from textual.app import ComposeResult
from textual.widgets._input import InputValidationOn
class HPVestsAmountInput(CliveValidatedInput[Asset.VotingT]):
"""An input for HP/VESTS amount."""
DEFAULT_CSS = """
HPVestsAmountInput {
height: auto;
Vertical {
height: auto;
Horizontal {
height: auto;
CliveInput {
width: 1fr;
}
CurrencySelectorHpVests {
width: 14;
}
}
}
}
"""
def __init__(
self,
title: str = "Amount",
value: str | float | None = None,
placeholder: str | None = None,
*,
always_show_title: bool = False,
include_title_in_placeholder_when_blurred: bool = True,
show_invalid_reasons: bool = True,
required: bool = True,
validate_on: Iterable[InputValidationOn] | None = None,
valid_empty: bool = False,
id: str | None = None, # noqa: A002
classes: str | None = None,
disabled: bool = False,
) -> None:
"""
Initialize the widget.
Args difference from `CliveValidatedInput`:
----
placeholder: If not provided, placeholder will be dynamically generated based on the asset type.
"""
self._currency_selector = CurrencySelectorHpVests()
default_asset_type = self._currency_selector.default_asset_cls
default_asset_precision = default_asset_type.get_asset_information().precision
super().__init__(
title=title,
value=str(value) if value is not None else None,
placeholder=self._get_dynamic_placeholder(default_asset_precision),
always_show_title=always_show_title,
include_title_in_placeholder_when_blurred=include_title_in_placeholder_when_blurred,
show_invalid_reasons=show_invalid_reasons,
required=required,
restrict=self._create_restriction(default_asset_precision),
type="number",
validators=[AssetAmountValidator(default_asset_type)],
validate_on=validate_on,
valid_empty=valid_empty,
id=id,
classes=classes,
disabled=disabled,
)
self._dynamic_placeholder = placeholder is None
@property
def _value(self) -> Asset.Hive | Asset.Vests:
"""
Return the value of the input as a HIVE(HP)/VESTS asset.
Probably you want to use other `value_` properties instead.
Raises
------
AssetAmountInvalidFormatError: Raised when given amount is in invalid format.
"""
return self._currency_selector.create_asset(self.value_raw)
@property
def selected_asset_type(self) -> type[Asset.Hive | Asset.Vests]:
return self._currency_selector.asset_cls
@property
def selected_asset_precision(self) -> int:
return self.selected_asset_type.get_asset_information().precision
def compose(self) -> ComposeResult:
with Vertical():
with Horizontal():
yield self.input
yield self._currency_selector
yield self.pretty
@on(CurrencySelectorHpVests.Changed)
def _asset_changed(self) -> None:
# update placeholder
if self._dynamic_placeholder:
self.input.set_unmodified_placeholder(self._get_dynamic_placeholder(self.selected_asset_precision))
# update input restrict
self.input.restrict = self._create_restriction(self.selected_asset_precision)
# update asset amount validator
self.input.validators = [
validator for validator in self.input.validators if not isinstance(validator, AssetAmountValidator)
]
self.input.validators.append(AssetAmountValidator(self.selected_asset_type))
# need to revalidate the input (possible to switch from higher precision to lower precision)
self.input.validate(self.input.value)
def _create_restriction(self, precision: int) -> str:
precision_digits = f"{{0,{precision}}}"
return rf"\d*\.?\d{precision_digits}"
def _get_dynamic_placeholder(self, precision: int) -> str:
max_allowed_precision = 9
assert precision >= 0, f"Precision must be non-negative, got {precision}"
assert precision <= max_allowed_precision, f"Precision must be at most {max_allowed_precision}, got {precision}"
numbers = "123456789"
return f"e.g.: 1.{numbers[:precision]}"
......@@ -48,6 +48,7 @@ class Asset:
Hbd: TypeAlias = AssetHbdHF26
Vests: TypeAlias = AssetVestsHF26
LiquidT: TypeAlias = Hive | Hbd
VotingT: TypeAlias = Hive | Vests
AnyT: TypeAlias = Hive | Hbd | Vests
@classmethod
......
......@@ -17,6 +17,7 @@ from clive.__private.core.world import World
from clive.__private.storage.accounts import Account as WatchedAccount
from clive.__private.storage.accounts import WorkingAccount
from clive.main import _main as clive_main
from clive_local_tools.constants import TESTNET_CHAIN_ID
from clive_local_tools.testnet_block_log import (
get_alternate_chain_spec_path,
get_block_log,
......@@ -71,7 +72,7 @@ def prepare_node() -> tt.RawNode:
async def prepare_profile(node: tt.RawNode) -> None:
tt.logger.info("Configuring ProfileData for clive")
settings["secrets.node_address"] = node.http_endpoint.as_string()
settings["node.chain_id"] = "18dcf0a285365fc58b71f18b3d3fec954aa0c141c44e4e5cb4cf777b9eab274e"
settings["node.chain_id"] = TESTNET_CHAIN_ID
ProfileData(
WORKING_ACCOUNT.name,
......
from __future__ import annotations
from typing import TYPE_CHECKING
from .show import balances as show_balances
if TYPE_CHECKING:
from typing import Literal
import test_tools as tt
from click.testing import Result
from typer.testing import CliRunner
from clive.__private.cli.clive_typer import CliveTyper
def assert_no_exit_code_error(result: Result) -> None:
exit_code = 0
message = f"Exit code '{result.exit_code}' is different than expected '{exit_code}'. Output:\n{result.output}"
assert result.exit_code == exit_code, message
def assert_exit_code(result: Result, expected_code: int) -> None:
message = f"Exit code '{result.exit_code}' is different than expected '{expected_code}'. Output:\n{result.output}"
assert result.exit_code == expected_code, message
def assert_balances(
runner: CliRunner,
cli: CliveTyper,
account_name: str,
asset_amount: tt.Asset.AnyT,
balance: Literal["Liquid", "Savings", "Unclaimed"],
) -> None:
result = show_balances(runner, cli, account_name=account_name)
output = result.output
assert_no_exit_code_error(result)
assert account_name in output, f"no balances of {account_name} account in balances output: {output}"
assert any(
asset_amount.token() in line and asset_amount.pretty_amount() in line and balance in line
for line in output.split("\n")
), f"no {asset_amount.pretty_amount()} {asset_amount.token()} in balances output:\n{output}"
def assert_pending_withrawals(output: str, *, account_name: str, asset_amount: tt.Asset.AnyT) -> None:
assert any(
account_name in line and asset_amount.pretty_amount() in line and asset_amount.token() in line.upper()
for line in output.split("\n")
), f"no {asset_amount.pretty_amount()} {asset_amount.token()} in pending withdrawals output:\n{output}"
from __future__ import annotations
from typing import TYPE_CHECKING
import test_tools as tt
if TYPE_CHECKING:
from click.testing import Result
from typer.testing import CliRunner
from clive.__private.cli.clive_typer import CliveTyper
def balances(
runner: CliRunner, cli: CliveTyper, profile_name: str | None = None, account_name: str | None = None
) -> Result:
"""If profile_name or account_name is None then default value is used."""
command = ["show", "balances"]
if profile_name is not None:
command.append(f"--profile-name={profile_name}")
if account_name is not None:
command.append(f"--account-name={account_name}")
tt.logger.info(f"executing command {command}")
return runner.invoke(cli, command)
......@@ -2,4 +2,16 @@ from __future__ import annotations
from typing import Final
import test_tools as tt
TESTNET_CHAIN_ID: Final[str] = "18dcf0a285365fc58b71f18b3d3fec954aa0c141c44e4e5cb4cf777b9eab274e"
CREATOR_ACCOUNT: Final[tt.Account] = tt.Account("initminer")
WORKING_ACCOUNT: Final[tt.Account] = tt.Account("alice")
WATCHED_ACCOUNTS: Final[list[tt.Account]] = [tt.Account(name) for name in ("bob", "timmy", "john")]
WORKING_ACCOUNT_KEY_ALIAS: Final[str] = f"{WORKING_ACCOUNT.name}_key"
WORKING_ACCOUNT_HIVE_LIQUID_BALANCE: Final[tt.Asset.TestT] = tt.Asset.Test(1234)
WORKING_ACCOUNT_HBD_LIQUID_BALANCE: Final[tt.Asset.TbdT] = tt.Asset.Tbd(2345)
WORKING_ACCOUNT_VEST_BALANCE: Final[tt.Asset.TestT] = tt.Asset.Test(3456)
from __future__ import annotations
from typing import TYPE_CHECKING
import pytest
import test_tools as tt
from typer.testing import CliRunner
from clive.__private.core.commands.create_wallet import CreateWallet
from clive.__private.core.keys.keys import PrivateKeyAliased
from clive.__private.core.profile_data import ProfileData
from clive.__private.core.world import World
from clive.__private.storage.accounts import Account as WatchedAccount
from clive.__private.storage.accounts import WorkingAccount
from clive.core.url import Url
from clive_local_tools.constants import (
CREATOR_ACCOUNT,
WATCHED_ACCOUNTS,
WORKING_ACCOUNT,
WORKING_ACCOUNT_HBD_LIQUID_BALANCE,
WORKING_ACCOUNT_HIVE_LIQUID_BALANCE,
WORKING_ACCOUNT_KEY_ALIAS,
WORKING_ACCOUNT_VEST_BALANCE,
)
if TYPE_CHECKING:
from clive.__private.cli.clive_typer import CliveTyper
@pytest.fixture()
async def cli_with_runner() -> tuple[CliveTyper, CliRunner]:
"""Will run init node, configure profile and return CliRunner from typer.testing module."""
init_node = tt.InitNode()
init_node.config.plugin.append("transaction_status_api")
init_node.config.plugin.append("account_history_api")
init_node.config.plugin.append("account_history_rocksdb")
init_node.config.plugin.append("reputation_api")
init_node.run()
cli_wallet = tt.Wallet(attach_to=init_node, additional_arguments=["--transaction-serialization", "hf26"])
cli_wallet.api.import_key(init_node.config.private_key[0])
with cli_wallet.in_single_transaction():
creator_account_name = CREATOR_ACCOUNT.name
for account in [WORKING_ACCOUNT, *WATCHED_ACCOUNTS]:
key = tt.PublicKey(account.name)
cli_wallet.api.create_account_with_keys(
creator_account_name,
account.name,
"{}",
key,
key,
key,
key,
)
cli_wallet.api.transfer(
creator_account_name, account.name, WORKING_ACCOUNT_HIVE_LIQUID_BALANCE.as_nai(), "memo"
)
cli_wallet.api.transfer_to_vesting(
creator_account_name, account.name, WORKING_ACCOUNT_VEST_BALANCE.as_nai()
)
cli_wallet.api.transfer(
creator_account_name, account.name, WORKING_ACCOUNT_HBD_LIQUID_BALANCE.as_nai(), "memo"
)
ProfileData(
WORKING_ACCOUNT.name,
working_account=WorkingAccount(name=WORKING_ACCOUNT.name),
watched_accounts=[WatchedAccount(acc.name) for acc in WATCHED_ACCOUNTS],
).save()
async with World(WORKING_ACCOUNT.name) as world:
await CreateWallet(
app_state=world.app_state,
beekeeper=world.beekeeper,
wallet=WORKING_ACCOUNT.name,
password=WORKING_ACCOUNT.name,
).execute_with_result()
await world.node.set_address(Url.parse(init_node.http_endpoint.as_string()))
world.profile_data.working_account.keys.add_to_import(
PrivateKeyAliased(value=WORKING_ACCOUNT.private_key, alias=f"{WORKING_ACCOUNT_KEY_ALIAS}")
)
await world.commands.sync_data_with_beekeeper()
runner = CliRunner()
# import cli after default profile is set, default values for --profile-name option are set during loading
from clive.__private.cli.main import cli
return cli, runner