diff --git a/.claude/commands/lint.md b/.claude/commands/lint.md
new file mode 100644
index 0000000000000000000000000000000000000000..dc7ec8202625c688b1813bd01c405bee41495b7c
--- /dev/null
+++ b/.claude/commands/lint.md
@@ -0,0 +1,13 @@
+Run all linting and formatting checks on the codebase.
+
+Execute this command:
+
+```bash
+pre-commit run --all-files
+```
+
+Report the results:
+
+- If all checks pass, confirm success
+- If checks fail, summarize which hooks failed and the key issues found
+- For auto-fixable issues (like formatting), mention if files were modified
diff --git a/.claude/commands/reflection.md b/.claude/commands/reflection.md
new file mode 100644
index 0000000000000000000000000000000000000000..5368d98e52c039fa6a601cfecedf49e2df1f613d
--- /dev/null
+++ b/.claude/commands/reflection.md
@@ -0,0 +1,48 @@
+You are an expert in prompt engineering, specializing in optimizing AI code assistant instructions. Your task is to
+analyze and improve the instructions for Claude Code. Follow these steps carefully:
+
+1. Analysis Phase: Review the chat history in your context window.
+
+Then, examine the current Claude instructions, commands and config /CLAUDE.md /.claude/commands/\*
+\*\*/CLAUDE.md .claude/settings.json .claude/settings.local.json
+
+Analyze the chat history, instructions, commands and config to identify areas that could be improved. Look for:
+
+- Inconsistencies in Claude's responses
+- Misunderstandings of user requests
+- Areas where Claude could provide more detailed or accurate information
+- Opportunities to enhance Claude's ability to handle specific types of queries or tasks
+- New commands or improvements to a commands name, function or response
+- MCPs we've approved locally that we should add to the config, especially if we've added new tools or require them
+ for the command to work
+
+2. Interaction Phase: Present your findings and improvement ideas to the human. For each suggestion: a) Explain the
+ current issue you've identified b) Propose a specific change or addition to the instructions c) Describe how this
+ change would improve Claude's performance
+
+Wait for feedback from the human on each suggestion before proceeding. If the human approves a change, move it to the
+implementation phase. If not, refine your suggestion or move on to the next idea.
+
+3. Implementation Phase: For each approved change: a) Clearly state the section of the instructions you're modifying b)
+ Present the new or modified text for that section c) Explain how this change addresses the issue identified in the
+ analysis phase
+
+4. Output Format: Present your final output in the following structure:
+
+
+[List the issues identified and potential improvements]
+
+
+
+[For each approved improvement:
+1. Section being modified
+2. New or modified instruction text
+3. Explanation of how this addresses the identified issue]
+
+
+ [Present the complete, updated set of instructions for Claude, incorporating all approved changes]
+
+
+Remember, your goal is to enhance Claude's performance and consistency while maintaining the core functionality and
+purpose of the AI assistant. Be thorough in your analysis, clear in your explanations, and precise in your
+implementations.
diff --git a/.claude/commands/smoke.md b/.claude/commands/smoke.md
new file mode 100644
index 0000000000000000000000000000000000000000..10230b31e84ca9917a4fb5fe629e9fe5b025ab97
--- /dev/null
+++ b/.claude/commands/smoke.md
@@ -0,0 +1,9 @@
+Run the smoke test to quickly verify basic CLI functionality.
+
+Execute this command:
+
+```bash
+pytest -n 2 tests/functional/cli/show/test_show_account.py::test_show_account tests/functional/cli/process/test_process_transfer.py::test_process_transfer
+```
+
+Report the results concisely - whether tests passed or failed, and any errors encountered.
diff --git a/.claude/commands/test.md b/.claude/commands/test.md
new file mode 100644
index 0000000000000000000000000000000000000000..0ec397fc322fe41ef2ed883c773e5f06b8b88889
--- /dev/null
+++ b/.claude/commands/test.md
@@ -0,0 +1,28 @@
+Run pytest with the provided arguments.
+
+Arguments: $ARGUMENTS
+
+First, expand any shortcuts in the arguments:
+
+- `unit` → `tests/unit/`
+- `cli` → `tests/functional/cli/`
+- `tui` → `tests/functional/tui/`
+- `functional` → `tests/functional/`
+
+Then execute pytest with the expanded path. Examples:
+
+- `/test unit` runs `pytest tests/unit/`
+- `/test cli` runs `pytest tests/functional/cli/`
+- `/test tests/unit/test_date_utils.py -v` runs as-is (full path provided)
+
+If no arguments provided, run all tests with parallel execution:
+
+```bash
+pytest -n 16
+```
+
+Report results concisely:
+
+- Number of tests passed/failed/skipped
+- For failures, show the test name and a brief summary of the error
+- Suggest next steps if tests fail
diff --git a/CLAUDE.md b/CLAUDE.md
new file mode 100644
index 0000000000000000000000000000000000000000..707610c7924d480a86aacc6ad7b400868c28500d
--- /dev/null
+++ b/CLAUDE.md
@@ -0,0 +1,311 @@
+# CLAUDE.md
+
+This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
+
+## Project Overview
+
+**Clive** is a CLI and TUI (Terminal User Interface) application for interacting with the Hive blockchain. It's written
+in Python and designed to replace the original Hive CLI for power users and testing. The TUI features mouse-based
+navigation inspired by midnight commander.
+
+- **Main entry point**: `clive` - automatically launches TUI when run without arguments, or CLI mode when arguments
+ are provided like `clive` for TUI and `clive --help` for CLI
+- **Development entry point**: `clive-dev` - includes extra debugging information
+- **Python version**: (see `requires-python` in `pyproject.toml`, restricted due to wax dependency)
+- **Build system**: Poetry
+- **Main branch**: `develop` (use this for PRs, not `main`)
+
+## GitLab Instance
+
+This project uses **gitlab.syncad.com**, NOT gitlab.com.
+
+- Repository: https://gitlab.syncad.com/hive/clive
+- Use `glab api "projects/hive%2Fclive/..."` for API calls
+
+## Claude Code Commands
+
+Available slash commands for development workflows:
+
+| Command | Description |
+| -------------- | ------------------------------------------------------------- |
+| `/smoke` | Run smoke test |
+| `/lint` | Run all pre-commit hooks |
+| `/test ` | Run pytest with shortcuts: `unit`, `cli`, `tui`, `functional` |
+| `/reflection` | Analyze and improve Claude Code configuration |
+
+## Essential Commands
+
+### Installation and Setup
+
+```bash
+# Install dependencies (must be run from repository root)
+poetry install
+
+# When updating dependencies and hive submodule is updated also, test-tools should be forced to uninstall first
+pip uninstall -y test-tools && poetry install
+```
+
+### Running Clive
+
+```bash
+# Launch TUI (default)
+clive
+
+# Use CLI mode
+clive --help
+clive show profile
+clive configure profile create
+
+# Development mode with debug info (useful for presenting full stack-trace instead of pretty errors in CLI)
+clive-dev
+```
+
+### Linting and Formatting
+
+```bash
+# Run all pre-commit hooks (include tools like ruff, mypy and additional hooks)
+pre-commit run --all-files
+
+# Lint with Ruff
+ruff check clive/ tests/
+
+# Format code
+ruff format clive/ tests/
+
+# Type checking
+mypy clive/ tests/
+```
+
+### Testing
+
+Use `/smoke`, `/lint`, and `/test` slash commands for common workflows (see
+[Claude Code Commands](#claude-code-commands)).
+
+```bash
+# Run a specific test (example)
+pytest tests/unit/test_date_utils.py::test_specific_function -v
+
+# Run with timeout (important for tests that may hang)
+pytest --timeout=600
+
+# Run without parallelization (for debugging)
+pytest -n 0
+```
+
+**Note**: Tests require the embedded testnet dependencies. Some tests spawn local Hive nodes using `test-tools`.
+
+## Architecture
+
+### Configuration
+
+**Global settings** can be configured via:
+
+1. **Settings files** (in order of precedence):
+
+ - `~/.clive/settings.toml` (user settings, higher priority)
+ - `{project_root}/settings.toml` (project defaults)
+
+2. **Environment variables** override settings files using the format:
+
+ ```bash
+ CLIVE_{GROUP}__{KEY}=value
+ ```
+
+ Example: `CLIVE_NODE__CHAIN_ID=abc123` overrides `[NODE] CHAIN_ID` in settings.toml
+
+3. **Special environment variable**: `CLIVE_DATA_PATH` controls the Clive data directory (default: `~/.clive`). This
+ also determines where user settings are loaded from (`$CLIVE_DATA_PATH/settings.toml`).
+
+**Per-profile settings** are stored separately for each profile and configured via `clive configure`:
+
+- Tracked accounts (working account + watched accounts)
+- Known accounts (and enable/disable feature)
+- Key aliases
+- Node address
+- Chain ID
+
+See `clive configure --help` for all available options.
+
+### Core Architecture Pattern: Command Pattern
+
+Clive uses a **Command Pattern** for all operations that interact with the blockchain or beekeeper:
+
+- **Commands location**: `clive/__private/core/commands/`
+- **Base classes**: All commands inherit from `Command` (in `abc/command.py`)
+- **Execution**: Commands are async and executed via `await command.execute()`
+- **Command hierarchy**:
+ - `Command` - Base class with `_execute()` method
+ - `CommandWithResult` - Commands that return a value
+ - `CommandRestricted` - Base for commands with execution preconditions
+ - `CommandInUnlocked` - Commands requiring unlocked user wallet
+ - `CommandEncryption` - Commands requiring both unlocked user wallet and encryption wallet
+ - `CommandPasswordSecured` - Commands requiring a password
+ - `CommandDataRetrieval` - Commands that fetch data from the node
+ - `CommandCachedDataRetrieval` - Data retrieval with caching support
+
+### World Object - Application Container
+
+`World` (`clive/__private/core/world.py`) is the top-level container and single source of truth:
+
+- `world.profile` - Current user profile (settings, accounts, keys)
+- `world.node` - Hive node connection for API calls
+- `world.commands` - Access to all command instances
+- `world.beekeeper_manager` - Manages beekeeper (key storage) lifecycle
+- `world.app_state` - Application state (locked/unlocked, etc.)
+
+**Important**: Direct `world.node` API calls should be avoided in CLI/TUI. Use `world.commands` instead, which handles
+errors properly.
+
+### Profile System
+
+Profiles (`clive/__private/core/profile.py`) store user configuration:
+
+- **Working account**: The currently active Hive account
+- **Watched accounts**: Accounts being monitored
+- **Known accounts**: Accounts approved for transactions. CLI requires explicit addition before broadcasting
+ operations (configurable via `enable`/`disable`). TUI automatically adds accounts when operations are added to cart
+ (also configurable). Managed via `clive configure known-account`
+- **Key aliases**: Named public keys
+- **Transaction**: Pending transaction operations
+- **Node address**: Hive node endpoint
+- **Chain ID**: Blockchain identifier (like a mainnet/mirrornet/testnet)
+
+Profiles are persisted to disk via `PersistentStorageService` with encryption support.
+
+**Note**: Tracked accounts is a combination of working account and watched accounts.
+
+### Dual Interface Architecture
+
+**CLI Mode** (`clive/__private/cli/`):
+
+- Built with **Typer** for command-line interface
+- Main command groups: `configure`, `show`, `process`, `beekeeper`, `generate`, `unlock`, `lock`
+- For complete CLI command structure, see `docs/cli_commands_structure.md`
+- CLI implementation in `clive/__private/cli/`
+- Most of the commands —especially those that interact with profile— require Beekeeper (via the
+ `CLIVE_BEEKEEPER__REMOTE_ADDRESS` and `CLIVE_BEEKEEPER__SESSION_TOKEN` environment variables) for profile encryption
+ and decryption.
+- Commands `clive beekeeper spawn` and `clive beekeeper create-session` can be used for preparing the CLI environment.
+
+**TUI Mode** (`clive/__private/ui/`):
+
+- Built with **Textual** (Python TUI framework)
+- Main app: `clive/__private/ui/app.py` (Clive class)
+- Screens in `clive/__private/ui/screens/`
+- Widgets in `clive/__private/ui/widgets/`
+- Styling: TCSS (a Textual variation of CSS) files stored as .scss due to better syntax highlighting
+- TUI can be used in environment where Beekeeper is already running (`CLIVE_BEEKEEPER__REMOTE_ADDRESS` and
+ `CLIVE_BEEKEEPER__SESSION_TOKEN` env vars are set), but without them, beekeeper will be automatically spawned and
+ session will be created when starting TUI.
+
+### Beekeeper Integration
+
+Clive uses **beekeepy** (async Python wrapper) to communicate with Hive's beekeeper for key management:
+
+- **BeekeeperManager**: `clive/__private/core/beekeeper_manager.py`
+- Beekeeper stores keys in encrypted wallets
+- Beekeeper wallets are stored in the `~/.clive/beekeeper` directory (or `$CLIVE_DATA_PATH/beekeeper` if customized)
+- Two wallet types: user wallets (for signing) and encryption wallets (for encrypting profile data)
+- Wallets must be unlocked before use
+- Beekeeper address and session token can be pointed with respective setting in the `settings.toml` file or via env
+ var that would have higher precedence
+
+### Blockchain Communication
+
+- **Node interaction**: `clive/__private/core/node/node.py`
+- **API wrapper**: `clive/__private/core/node/async_hived/` - async wrapper around Hive node APIs
+- **Wax integration**: Uses `hiveio-wax` for transaction building and signing
+- **Operation models**: `clive/__private/models/schemas.py` - Pydantic models for Hive operations
+
+### Storage and Migrations
+
+- **Storage service**: `clive/__private/storage/service/service.py`
+- **Converters**: Runtime models ↔ Storage models
+- **Migrations**: `clive/__private/storage/migrations/` - versioned profile schema migrations
+- Profiles are stored as encrypted files (location can controlled by `CLIVE_DATA_PATH` environment variable, default:
+ `~/.clive/data/`)
+
+## Test Organization
+
+Tests are organized into two main categories:
+
+- **`tests/unit/`** - Unit tests for individual components (keys, storage, commands, etc.)
+- **`tests/functional/`** - Functional tests split by interface:
+ - `functional/cli/` - CLI command tests
+ - `functional/tui/` - TUI interaction tests
+
+**Test fixtures and patterns**:
+
+Common fixtures (`tests/conftest.py`):
+
+- `world` - Async World instance
+- `beekeeper` - Async beekeeper instance from beekeepy (spawned automatically)
+- `node` - Local testnet node (spawned automatically via test-tools)
+
+CLI test patterns (`tests/functional/cli/`):
+
+- Uses `CLITester` from `clive-local-tools` package
+- `cli_tester` fixture - Provides typed CLI testing interface with command invocation and output checking
+
+TUI test patterns (`tests/functional/tui/`):
+
+- Uses `ClivePilot` (Textual's async test driver)
+- `prepared_env` fixture - Returns `(node, wallet, pilot)` tuple with TUI ready on Unlock screen
+- `prepared_tui_on_dashboard` fixture - TUI already authenticated and on Dashboard screen
+- `node_with_wallet` fixture - Test node with initialized wallet
+- Tests interact with TUI via pilot (e.g., `pilot.click()`, `pilot.press()`)
+
+## Development Guidelines
+
+### Code Style
+
+- **Strict mypy**: Type hints are required and strictly enforced
+- **Ruff**: Comprehensive linting with "ALL" rules (see `pyproject.toml` for ignored rules)
+- **Future imports**: All files must have `from __future__ import annotations` (enforced by ruff)
+- **Docstrings**: Google style, checked by pydoclint (no redundant type hints in docstrings)
+- **Line length**: See `line-length` in `pyproject.toml` (currently 120 characters)
+
+### Important Conventions
+
+1. **Private modules**: Implementation details are in `__private/` directories
+2. **No direct initialization**: Some classes (like `Profile`) use factory methods instead of `__init__`
+3. **Command pattern**: Always use commands for blockchain operations, not direct API calls
+4. **Async context managers**: Many resources (World, Node) require async context manager usage
+5. **Settings**: Use `safe_settings` from `clive/__private/settings` for reading configuration
+
+### When Working With Tests
+
+- Pytest tests use `test-tools` from the Hive submodule for spawning local nodes
+- For manual tests, local testnet node can be started manually via `testnet_node.py`
+- Both `testnet_node.py` and `test-tools` based tests require executables from the `hive` submodule pointed by the
+ `HIVE_BUILD_ROOT_PATH` environment variable
+- Beekeeper is spawned automatically by test fixtures when needed
+- Tests modify settings to use test directories, not user's actual Clive data
+- The `clive-local-tools` package provides test helpers and checkers
+
+### Useful Commands
+
+#### GitLab CLI (glab)
+
+```bash
+# Find MR for a branch
+glab mr list --source-branch=
+
+# Add comment to MR
+glab mr note --message "..."
+
+# Get pipeline job details
+glab api "projects/hive%2Fclive/pipelines//jobs"
+
+# Get job logs
+glab api "projects/hive%2Fclive/jobs//trace"
+```
+
+### CI Environment
+
+Tests run in CI with:
+
+- Parallel processes configurable via `PYTEST_NUMBER_OF_PROCESSES` (see `.gitlab-ci.yml`, default: 16)
+- Timeout configurable via `PYTEST_TIMEOUT_MINUTES` (typically 10 minutes for most test suites)
+- Separate jobs for unit tests, CLI tests, and TUI tests
+- Tests run against installed wheel (not editable install)
diff --git a/clive/__private/cli/commands/process/process_transfer_schedule.py b/clive/__private/cli/commands/process/process_transfer_schedule.py
index 1e8ea257cc0dba4de6c69577914a9acfc1e7d0d3..d0c09ed266fbb1f886e57970c3d327cde8dd40b6 100644
--- a/clive/__private/cli/commands/process/process_transfer_schedule.py
+++ b/clive/__private/cli/commands/process/process_transfer_schedule.py
@@ -65,8 +65,20 @@ class _ProcessTransferScheduleCommon(OperationCommand, ABC):
def _identity_check(self, scheduled_transfer: ScheduledTransfer) -> bool:
"""Determine if a scheduled transfer matches destination and the specified pair ID."""
- pair_id = 0 if self.pair_id is None else self.pair_id
- return scheduled_transfer.to == self.to and scheduled_transfer.pair_id == pair_id
+ if scheduled_transfer.to != self.to:
+ return False
+
+ if self.pair_id is not None:
+ return scheduled_transfer.pair_id == self.pair_id
+
+ # pair_id not specified - check if we can auto-select
+ transfers_to_receiver = self.account_scheduled_transfers_data.filter_by_receiver(self.to)
+ if len(transfers_to_receiver) == 1 and transfers_to_receiver[0].pair_id == 0:
+ # Single transfer with pair_id=0, auto-select it
+ return scheduled_transfer.pair_id == 0
+
+ # Default behavior: treat None as 0
+ return scheduled_transfer.pair_id == 0
async def fetch_data(self) -> None:
self.account_scheduled_transfers_data = await self.fetch_scheduled_transfers_for_current_account()
@@ -86,12 +98,30 @@ class _ProcessTransferScheduleCommon(OperationCommand, ABC):
raise ProcessTransferScheduleDoesNotExistsError(self.to, pair_id)
def validate_pair_id_should_be_given(self) -> None:
- """Validate if pair_id is set, when there is more than one recurrent transfers."""
- if (
- self.account_scheduled_transfers_data.has_mutiple_scheduled_transfers_to_receiver(self.to)
- and self.pair_id is None
- ):
- raise ProcessTransferScheduleNullPairIdError
+ """
+ Validate if pair_id should be specified explicitly.
+
+ Rules:
+ - If pair_id is specified, OK
+ - If there's exactly one transfer to receiver with pair_id=0, auto-select OK
+ - Otherwise (multiple transfers OR single transfer with pair_id != 0), error
+ """
+ if self.pair_id is not None:
+ return
+
+ transfers_to_receiver = self.account_scheduled_transfers_data.filter_by_receiver(self.to)
+
+ if len(transfers_to_receiver) == 0:
+ return # No transfers, will fail on existence check
+
+ if len(transfers_to_receiver) == 1:
+ if transfers_to_receiver[0].pair_id == 0:
+ return # Single transfer with pair_id=0, auto-select OK
+ # Single transfer with pair_id != 0
+ raise ProcessTransferScheduleNullPairIdError(self.to, existing_pair_id=transfers_to_receiver[0].pair_id)
+
+ # Multiple transfers
+ raise ProcessTransferScheduleNullPairIdError(self.to)
@dataclass(kw_only=True)
@@ -158,6 +188,8 @@ class ProcessTransferScheduleCreate(_ProcessTransferScheduleCreateModifyCommon):
class ProcessTransferScheduleModify(_ProcessTransferScheduleCreateModifyCommon):
async def fetch_data(self) -> None:
self.account_scheduled_transfers_data = await self.fetch_scheduled_transfers_for_current_account()
+ self.validate_pair_id_should_be_given()
+ self.validate_existence(should_exists=True)
if self.scheduled_transfer:
self.amount = self.amount if self.amount is not None else self.scheduled_transfer.amount
self.repeat = self.repeat if self.repeat is not None else self.scheduled_transfer.remaining_executions
@@ -167,8 +199,6 @@ class ProcessTransferScheduleModify(_ProcessTransferScheduleCreateModifyCommon):
self.memo = self.memo if self.memo is not None else self.scheduled_transfer.memo
async def validate_inside_context_manager(self) -> None:
- self.validate_existence(should_exists=True)
- self.validate_pair_id_should_be_given()
self.validate_existence_lifetime()
await super().validate_inside_context_manager()
@@ -182,6 +212,11 @@ class ProcessTransferScheduleModify(_ProcessTransferScheduleCreateModifyCommon):
@dataclass(kw_only=True)
class ProcessTransferScheduleRemove(_ProcessTransferScheduleCommon):
+ async def fetch_data(self) -> None:
+ self.account_scheduled_transfers_data = await self.fetch_scheduled_transfers_for_current_account()
+ self.validate_pair_id_should_be_given()
+ self.validate_existence(should_exists=True)
+
async def _create_operations(self) -> ComposeTransaction:
yield RecurrentTransferOperation(
from_=self.from_account,
@@ -197,6 +232,4 @@ class ProcessTransferScheduleRemove(_ProcessTransferScheduleCommon):
)
async def validate_inside_context_manager(self) -> None:
- self.validate_existence(should_exists=True)
- self.validate_pair_id_should_be_given()
await super().validate_inside_context_manager()
diff --git a/clive/__private/cli/exceptions.py b/clive/__private/cli/exceptions.py
index 72942aa03bc4c6a96bc5ca6ff1eaf86d3a923937..6eb263aa42e49d2259ccabaa4985ce06ff5c7d4c 100644
--- a/clive/__private/cli/exceptions.py
+++ b/clive/__private/cli/exceptions.py
@@ -117,9 +117,11 @@ class ProcessTransferScheduleAlreadyExistsError(CLIPrettyError):
self.to = to
self.pair_id = pair_id
message = (
- f"Scheduled transfer to `{self.to}` with pair_id `{self.pair_id}` already exists.\n"
- "Please use command `clive process transfer-schedule modify` to change it, "
- "or command `clive process transfer-schedule remove` to delete it."
+ f"A scheduled transfer to `{self.to}` with pair_id `{self.pair_id}` already exists.\n"
+ f"If you want to create a new recurrent transfer to `{self.to}`, "
+ "use `clive process transfer-schedule create` and specify the --pair-id.\n"
+ "If you want to modify an existing one, use `clive process transfer-schedule modify`.\n"
+ "If you want to list existing recurrent transfers, use `clive show transfer-schedule`."
)
super().__init__(message, errno.EPERM)
@@ -150,8 +152,23 @@ class ProcessTransferScheduleInvalidAmountError(CLIPrettyError):
class ProcessTransferScheduleNullPairIdError(CLIPrettyError):
- def __init__(self) -> None:
- message = "Pair id must be set explicit, when there are multiple scheduled transfers defined."
+ def __init__(self, to: str, *, existing_pair_id: int | None = None) -> None:
+ self.to = to
+ self.existing_pair_id = existing_pair_id
+ if existing_pair_id is not None:
+ # Single transfer with pair_id != 0
+ message = (
+ f"The scheduled transfer to `{self.to}` has pair_id=`{existing_pair_id}`, not 0.\n"
+ f"Please specify --pair-id {existing_pair_id} explicitly.\n"
+ "Use `clive show transfer-schedule` to list existing transfers and their pair IDs."
+ )
+ else:
+ # Multiple transfers
+ message = (
+ f"Cannot determine which scheduled transfer to `{self.to}` to modify/remove.\n"
+ "Please specify --pair-id explicitly.\n"
+ "Use `clive show transfer-schedule` to list existing transfers and their pair IDs."
+ )
super().__init__(message, errno.EPERM)
diff --git a/clive/__private/cli/process/transfer_schedule.py b/clive/__private/cli/process/transfer_schedule.py
index 26bde632a20c761bb92add40a4144e20b9cb8b65..df989074ad3c73721b7a674bc615faca6362cf8d 100644
--- a/clive/__private/cli/process/transfer_schedule.py
+++ b/clive/__private/cli/process/transfer_schedule.py
@@ -32,10 +32,7 @@ _pair_id_value = typer.Option(
0,
"--pair-id",
min=SCHEDULED_TRANSFER_MINIMUM_PAIR_ID_VALUE,
- help=(
- "Unique pair id used to differentiate between multiple transfers to the same account \n"
- "(will be mandatory since HF28)."
- ),
+ help="Unique pair id used to differentiate between multiple transfers to the same account.",
)
_pair_id_value_none = modified_param(_pair_id_value, default=None)
@@ -106,6 +103,9 @@ async def process_transfer_schedule_modify( # noqa: PLR0913
Modify an existing recurrent transfer.
If you change the frequency, the first execution after modification is update date + frequency.
+
+ If --pair-id is not specified and there is exactly one transfer to the recipient with pair_id=0,
+ it will be modified automatically. Otherwise, --pair-id is required.
"""
from clive.__private.cli.commands.process.process_transfer_schedule import ( # noqa: PLC0415
ProcessTransferScheduleModify,
@@ -137,7 +137,12 @@ async def process_transfer_schedule_remove( # noqa: PLR0913
broadcast: bool | None = options.broadcast, # noqa: FBT001
save_file: str | None = options.save_file,
) -> None:
- """Remove an existing recurrent transfer."""
+ """
+ Remove an existing recurrent transfer.
+
+ If --pair-id is not specified and there is exactly one transfer to the recipient with pair_id=0,
+ it will be removed automatically. Otherwise, --pair-id is required.
+ """
from clive.__private.cli.commands.process.process_transfer_schedule import ( # noqa: PLC0415
ProcessTransferScheduleRemove,
)
diff --git a/clive/__private/settings/_settings.py b/clive/__private/settings/_settings.py
index 553652c6a817c3213f434d453514e06339178274..63a4239ce2781fb657e26548d6eb6d5194e9f49b 100644
--- a/clive/__private/settings/_settings.py
+++ b/clive/__private/settings/_settings.py
@@ -50,7 +50,7 @@ class Settings:
The environment variable
```bash
- CLIVE__FIRST_GROUP__NESTED_GROUP__SOME_KEY=124
+ CLIVE_FIRST_GROUP__NESTED_GROUP__SOME_KEY=124
```
would override the setting in the file.
diff --git a/tests/clive-local-tools/clive_local_tools/cli/cli_tester.py b/tests/clive-local-tools/clive_local_tools/cli/cli_tester.py
index 0efa11963501d1a2aa94eaf198fe031448fb8984..7843f035f5540c6a036bb1c8085b4165dd6be7c9 100644
--- a/tests/clive-local-tools/clive_local_tools/cli/cli_tester.py
+++ b/tests/clive-local-tools/clive_local_tools/cli/cli_tester.py
@@ -512,7 +512,7 @@ class CLITester:
repeat: int,
frequency: str,
amount: tt.Asset.HiveT | tt.Asset.HbdT,
- pair_id: int = 0,
+ pair_id: int | None = None,
from_: str | None = None,
sign_with: str | None = None,
broadcast: bool | None = None,
@@ -550,7 +550,7 @@ class CLITester:
*,
to: str,
from_: str | None = None,
- pair_id: int = 0,
+ pair_id: int | None = None,
sign_with: str | None = None,
broadcast: bool | None = None,
save_file: Path | None = None,
diff --git a/tests/unit/cli/__init__.py b/tests/unit/cli/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..4b1e6da70d9b9e65aa808cdf86d8ec133bd6ad10
--- /dev/null
+++ b/tests/unit/cli/__init__.py
@@ -0,0 +1 @@
+# Unit tests for CLI
diff --git a/tests/unit/cli/test_process_transfer_schedule_validation.py b/tests/unit/cli/test_process_transfer_schedule_validation.py
new file mode 100644
index 0000000000000000000000000000000000000000..d6e44b63b28fe5bc5fdd4064ecc1f6908fd146a9
--- /dev/null
+++ b/tests/unit/cli/test_process_transfer_schedule_validation.py
@@ -0,0 +1,244 @@
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from datetime import UTC, datetime
+
+import pytest
+
+from clive.__private.cli.exceptions import ProcessTransferScheduleNullPairIdError
+from clive.__private.models.asset import Asset
+
+
+def _default_amount() -> Asset.LiquidT:
+ return Asset.hive(1)
+
+
+def _default_datetime() -> datetime:
+ return datetime.now(tz=UTC)
+
+
+def _default_hive() -> Asset.Hive:
+ return Asset.hive(100)
+
+
+def _default_hbd() -> Asset.Hbd:
+ return Asset.hbd(100)
+
+
+@dataclass
+class MockScheduledTransfer:
+ """Mock ScheduledTransfer for testing."""
+
+ to: str
+ pair_id: int
+ amount: Asset.LiquidT = field(default_factory=_default_amount)
+ consecutive_failures: int = 0
+ from_: str = "alice"
+ memo: str = ""
+ recurrence: int = 24
+ remaining_executions: int = 2
+ trigger_date: datetime = field(default_factory=_default_datetime)
+
+
+@dataclass
+class MockAccountScheduledTransferData:
+ """Mock AccountScheduledTransferData for testing."""
+
+ scheduled_transfers: list[MockScheduledTransfer]
+ account_hive_balance: Asset.Hive = field(default_factory=_default_hive)
+ account_hbd_balance: Asset.Hbd = field(default_factory=_default_hbd)
+
+ def filter_by_receiver(self, receiver: str) -> list[MockScheduledTransfer]:
+ return [st for st in self.scheduled_transfers if st.to == receiver]
+
+ def has_any_scheduled_transfers(self) -> bool:
+ return bool(self.scheduled_transfers)
+
+
+class ValidationLogicTester:
+ """Helper class to test validation logic from _ProcessTransferScheduleCommon."""
+
+ def __init__(
+ self,
+ to: str,
+ pair_id: int | None,
+ account_scheduled_transfers_data: MockAccountScheduledTransferData,
+ ) -> None:
+ self.to = to
+ self.pair_id = pair_id
+ self.account_scheduled_transfers_data = account_scheduled_transfers_data
+
+ def validate_pair_id_should_be_given(self) -> None:
+ """
+ Validate if pair_id should be specified explicitly.
+
+ Rules:
+ - If pair_id is specified, OK
+ - If there's exactly one transfer to receiver with pair_id=0, auto-select OK
+ - Otherwise (multiple transfers OR single transfer with pair_id != 0), error
+ """
+ if self.pair_id is not None:
+ return
+
+ transfers_to_receiver = self.account_scheduled_transfers_data.filter_by_receiver(self.to)
+
+ if len(transfers_to_receiver) == 0:
+ return # No transfers, will fail on existence check
+
+ if len(transfers_to_receiver) == 1:
+ if transfers_to_receiver[0].pair_id == 0:
+ return # Single transfer with pair_id=0, auto-select OK
+ # Single transfer with pair_id != 0
+ raise ProcessTransferScheduleNullPairIdError(self.to, existing_pair_id=transfers_to_receiver[0].pair_id)
+
+ # Multiple transfers
+ raise ProcessTransferScheduleNullPairIdError(self.to)
+
+ def identity_check(self, scheduled_transfer: MockScheduledTransfer) -> bool:
+ """Determine if a scheduled transfer matches destination and the specified pair ID."""
+ if scheduled_transfer.to != self.to:
+ return False
+
+ if self.pair_id is not None:
+ return scheduled_transfer.pair_id == self.pair_id
+
+ # pair_id not specified - check if we can auto-select
+ transfers_to_receiver = self.account_scheduled_transfers_data.filter_by_receiver(self.to)
+ if len(transfers_to_receiver) == 1 and transfers_to_receiver[0].pair_id == 0:
+ # Single transfer with pair_id=0, auto-select it
+ return scheduled_transfer.pair_id == 0
+
+ # Default behavior: treat None as 0
+ return scheduled_transfer.pair_id == 0
+
+
+# Tests for validate_pair_id_should_be_given
+
+
+def test_validate_pair_id_given_explicitly_passes() -> None:
+ # Arrange
+ transfers = [MockScheduledTransfer(to="bob", pair_id=5)]
+ data = MockAccountScheduledTransferData(scheduled_transfers=transfers)
+ tester = ValidationLogicTester(to="bob", pair_id=5, account_scheduled_transfers_data=data)
+
+ # Act & Assert - should not raise
+ tester.validate_pair_id_should_be_given()
+
+
+def test_validate_single_transfer_with_pair_id_0_auto_selects() -> None:
+ # Arrange
+ transfers = [MockScheduledTransfer(to="bob", pair_id=0)]
+ data = MockAccountScheduledTransferData(scheduled_transfers=transfers)
+ tester = ValidationLogicTester(to="bob", pair_id=None, account_scheduled_transfers_data=data)
+
+ # Act & Assert - should not raise (auto-select)
+ tester.validate_pair_id_should_be_given()
+
+
+def test_validate_single_transfer_with_nonzero_pair_id_requires_explicit() -> None:
+ # Arrange
+ transfers = [MockScheduledTransfer(to="bob", pair_id=5)]
+ data = MockAccountScheduledTransferData(scheduled_transfers=transfers)
+ tester = ValidationLogicTester(to="bob", pair_id=None, account_scheduled_transfers_data=data)
+
+ # Act & Assert
+ with pytest.raises(ProcessTransferScheduleNullPairIdError) as exc_info:
+ tester.validate_pair_id_should_be_given()
+ assert "bob" in str(exc_info.value)
+ assert "pair_id=`5`" in str(exc_info.value) # Should show existing pair_id
+
+
+def test_validate_multiple_transfers_requires_explicit_pair_id() -> None:
+ # Arrange
+ transfers = [
+ MockScheduledTransfer(to="bob", pair_id=0),
+ MockScheduledTransfer(to="bob", pair_id=1),
+ ]
+ data = MockAccountScheduledTransferData(scheduled_transfers=transfers)
+ tester = ValidationLogicTester(to="bob", pair_id=None, account_scheduled_transfers_data=data)
+
+ # Act & Assert
+ with pytest.raises(ProcessTransferScheduleNullPairIdError) as exc_info:
+ tester.validate_pair_id_should_be_given()
+ assert "bob" in str(exc_info.value)
+ assert "Cannot determine" in str(exc_info.value) # Multiple transfers message
+
+
+def test_validate_no_transfers_passes() -> None:
+ # Arrange
+ data = MockAccountScheduledTransferData(scheduled_transfers=[])
+ tester = ValidationLogicTester(to="bob", pair_id=None, account_scheduled_transfers_data=data)
+
+ # Act & Assert - should not raise (existence check handles this)
+ tester.validate_pair_id_should_be_given()
+
+
+# Tests for identity_check
+
+
+def test_identity_check_with_explicit_pair_id_matches() -> None:
+ # Arrange
+ transfer = MockScheduledTransfer(to="bob", pair_id=5)
+ data = MockAccountScheduledTransferData(scheduled_transfers=[transfer])
+ tester = ValidationLogicTester(to="bob", pair_id=5, account_scheduled_transfers_data=data)
+
+ # Act
+ result = tester.identity_check(transfer)
+
+ # Assert
+ assert result is True
+
+
+def test_identity_check_with_explicit_pair_id_no_match() -> None:
+ # Arrange
+ transfer = MockScheduledTransfer(to="bob", pair_id=5)
+ data = MockAccountScheduledTransferData(scheduled_transfers=[transfer])
+ tester = ValidationLogicTester(to="bob", pair_id=3, account_scheduled_transfers_data=data)
+
+ # Act
+ result = tester.identity_check(transfer)
+
+ # Assert
+ assert result is False
+
+
+def test_identity_check_auto_selects_single_transfer_with_pair_id_0() -> None:
+ # Arrange
+ transfer = MockScheduledTransfer(to="bob", pair_id=0)
+ data = MockAccountScheduledTransferData(scheduled_transfers=[transfer])
+ tester = ValidationLogicTester(to="bob", pair_id=None, account_scheduled_transfers_data=data)
+
+ # Act
+ result = tester.identity_check(transfer)
+
+ # Assert
+ assert result is True
+
+
+def test_identity_check_wrong_receiver_returns_false() -> None:
+ # Arrange
+ transfer = MockScheduledTransfer(to="charlie", pair_id=0)
+ data = MockAccountScheduledTransferData(scheduled_transfers=[transfer])
+ tester = ValidationLogicTester(to="bob", pair_id=None, account_scheduled_transfers_data=data)
+
+ # Act
+ result = tester.identity_check(transfer)
+
+ # Assert
+ assert result is False
+
+
+def test_identity_check_multiple_transfers_defaults_to_pair_id_0() -> None:
+ # Arrange
+ transfer_0 = MockScheduledTransfer(to="bob", pair_id=0)
+ transfer_1 = MockScheduledTransfer(to="bob", pair_id=1)
+ data = MockAccountScheduledTransferData(scheduled_transfers=[transfer_0, transfer_1])
+ tester = ValidationLogicTester(to="bob", pair_id=None, account_scheduled_transfers_data=data)
+
+ # Act
+ result_0 = tester.identity_check(transfer_0)
+ result_1 = tester.identity_check(transfer_1)
+
+ # Assert
+ assert result_0 is True # pair_id=0 matches default
+ assert result_1 is False # pair_id=1 does not match default