quantus-cli 1.0.0

Command line interface and library for interacting with the Quantus Network
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
# Quantus CLI

A modern command line interface for interacting with the Quantus Network, featuring built-in quantum-safe wallet management and real blockchain operations using SubXT.

## 🌟 Features

- **Quantum-Safe Wallets**: Built with Dilithium post-quantum cryptography
- **SubXT Integration**: Modern Substrate client with type-safe API
- **Generic Pallet Calls**: Call ANY blockchain function using metadata-driven parsing
- **Real Chain Operations**: Send tokens, query balances, explore metadata
- **Smart Type Detection**: Automatic parsing of addresses, balances, and data types
- **Developer Tools**: Pre-built test wallets and utilities
- **Modern CLI**: Built with Rust and Clap for excellent UX
- **Cross-Platform**: Runs on macOS, Linux, and Windows
- **Beautiful UI**: Colorized output with emoji indicators and progress spinners
- **Smart Balance Display**: Automatic formatting with proper decimals and token symbols
- **Password Convenience**: Multiple authentication options including environment variables
- **Fresh Nonce Management**: Automatic nonce handling to avoid transaction conflicts

## 🚀 Quick Start

### Installation

#### From crates.io

```bash
# Install the CLI tool
cargo install quantus-cli

# The binary will be available as `quantus`
quantus --help
```

#### From source

```bash
# Clone and build
git clone https://github.com/Quantus-Network/quantus-cli
cd quantus-cli
cargo build --release

# The binary will be available as `quantus`
```

#### As a library

Add to your `Cargo.toml`:

```toml
[dependencies]
# Full functionality (CLI + library)
quantus-cli = "0.1.0"

# Library only (smaller dependencies)
quantus-cli = { version = "0.1.0", default-features = false }
```

### First Steps

Start by exploring the available commands:

```bash
# Get help to see all available commands
quantus --help

# Explore specific command groups
quantus wallet --help
quantus send --help
quantus tech-collective --help
```

The CLI provides comprehensive help at every level, allowing you to discover functionality step by step.

## 📋 CLI Navigation

### Help System
The CLI provides comprehensive help at every level. Every command and subcommand supports `--help`:

- **Main level**: `quantus --help` shows all available top-level commands
- **Command level**: `quantus <command> --help` shows options for specific commands
- **Subcommand level**: `quantus <command> <subcommand> --help` shows options for subcommands
- **Deep nesting**: Help is available at any depth of command nesting

This hierarchical help system allows you to discover available functionality step by step, starting from the main help and drilling down to specific command options.

### Verbose Mode
Every command supports `--verbose` for detailed debugging information:

- **Standard output**: Commands show essential information by default
- **Verbose output**: Adding `--verbose` provides detailed execution logs, network calls, and internal state information
- **Universal support**: Verbose mode works on any command level and any subcommand
- **Debugging aid**: Use verbose mode to troubleshoot issues or understand command execution flow

### Global Options
These options work on every command:
- `--verbose` / `-v`: Enable debug logging with detailed output
- `--node-url <URL>`: Specify node endpoint (default: `ws://127.0.0.1:9944`)
- `--help` / `-h`: Show help for any command or subcommand

### Command Structure
The CLI uses a hierarchical structure:

```
quantus [GLOBAL_OPTIONS] <COMMAND> [COMMAND_OPTIONS] <SUBCOMMAND> [SUBCOMMAND_OPTIONS]
```

**Structure:**
The CLI follows a consistent pattern where global options can be combined with any command and subcommand at any level of nesting.

### Discovering Commands
Start with the main help and drill down to explore available functionality. The CLI provides helpful error messages and suggestions when you make mistakes, guiding you to the correct command syntax.

### Quick Reference
Common navigation patterns:
- Start with `quantus --help` to see all available commands
- Use `quantus <command> --help` to explore specific command options
- Add `--verbose` to any command for detailed debugging information
- Use `--node-url` to connect to different nodes (defaults to localhost)



## Command Reference

### Wormhole (Privacy-Preserving Transfers)

The `wormhole` commands implement a ZK-proof-based privacy layer. Funds are sent to an unspendable account derived from a secret, a zero-knowledge proof is generated to prove ownership, and the proof is verified on-chain to mint equivalent tokens to an exit account -- breaking the on-chain link between sender and receiver.

#### `quantus wormhole address`

Derive the unspendable wormhole address from a secret. This is step one of a private transfer -- it shows the address you need to send funds to.

```bash
quantus wormhole address --secret 0x<64-hex-chars>
```

Output:
```
Wormhole Address
  SS58:  qDx...
  Hex:   0x...

To fund this address:
  quantus send --from <wallet> --to qDx... --amount <amount>
```

Then send funds using a standard transfer (the chain's `WormholeProofRecorderExtension` automatically records a transfer proof for any balance transfer):

```bash
quantus send --from crystal_alice --to qDx... --amount 100
```

#### `quantus wormhole prove`

Generate a ZK proof for an existing wormhole transfer. The proof demonstrates knowledge of the secret without revealing it.

```bash
quantus wormhole prove \
  --secret 0x<secret> \
  --amount 100000000000000 \
  --exit-account <SS58-or-hex> \
  --block 0x<block-hash> \
  --transfer-count <count> \
  --funding-account 0x<funding-account> \
  --output proof.hex
```

- `--exit-account`: The destination address that will receive funds after on-chain verification (SS58 or `0x`-prefixed hex).
- `--block`: Block hash where the transfer was included.
- `--transfer-count`: Transfer count from the `NativeTransferred` event.
- `--output`: Output file path for the hex-encoded proof (default: `proof.hex`).

#### `quantus wormhole aggregate`

Aggregate multiple leaf proofs into a single recursive proof. The aggregation circuit pads with dummy proofs and shuffles to hide which slots are real.

```bash
quantus wormhole aggregate \
  --proofs proof_1.hex proof_2.hex \
  --output aggregated_proof.hex
```

- `--proofs`: One or more hex-encoded proof files. The number must not exceed `num_leaf_proofs` from the circuit config.
- Before aggregation, the CLI verifies binary hashes from `generated-bins/config.json` to detect stale circuit binaries.
- Displays timing for dummy proof generation and aggregation separately.

#### `quantus wormhole verify-aggregated`

Submit an aggregated proof to the chain for on-chain verification. This is an unsigned extrinsic -- no wallet is needed.

```bash
quantus wormhole verify-aggregated --proof aggregated_proof.hex
```

- On success, the chain mints tokens to each exit account listed in the proof.
- The command checks for `ProofVerified` and `ExtrinsicFailed` events and reports the result.

#### `quantus wormhole parse-proof`

Inspect the public inputs of a proof file for debugging.

```bash
# Parse a leaf proof
quantus wormhole parse-proof --proof proof.hex

# Parse an aggregated proof
quantus wormhole parse-proof --proof aggregated_proof.hex --aggregated

# Parse and cryptographically verify locally
quantus wormhole parse-proof --proof aggregated_proof.hex --aggregated --verify
```

#### `quantus wormhole multiround`

Run an automated multi-round wormhole flow: fund -> prove -> aggregate -> verify on-chain, repeated over multiple rounds. This is the primary integration test for the wormhole system.

```bash
quantus wormhole multiround \
  --num-proofs 4 \
  --rounds 2 \
  --amount 100000000000000 \
  --wallet crystal_alice \
  --password "" \
  --keep-files \
  --output-dir /tmp/wormhole_test
```

- `--num-proofs`: Number of proofs per round (1 to `num_leaf_proofs` from circuit config, default: 2).
- `--rounds`: Number of rounds (default: 2). In intermediate rounds, exit accounts are the next round's wormhole addresses; in the final round, funds exit back to the wallet.
- `--amount`: Total amount in planck to randomly partition across proofs (default: 100 DEV).
- `--wallet`: Wallet name for funding (round 1) and final exit.
- `--keep-files`: Preserve proof files after completion (default: cleaned up).
- `--output-dir`: Directory for intermediate proof files (default: `/tmp/wormhole_multiround`).
- `--dry-run`: Show configuration and derived addresses without executing.

Each round performs:
1. **Transfer** (round 1 only): Randomly partition the total amount and send to wormhole addresses derived via HD path `m/44'/189189189'/0'/<round>'/<index>'`.
2. **Generate proofs**: Create a ZK proof for each transfer with randomized dual-output assignments.
3. **Aggregate**: Combine all leaf proofs into a single recursive proof.
4. **Verify on-chain**: Submit the aggregated proof; the chain mints tokens to exit accounts.

After all rounds, the command verifies the wallet balance matches expectations (initial - fees).

---

### Developer Tools

#### `quantus developer build-circuits`

Build ZK circuit binaries from the `qp-zk-circuits` repository, then copy them to the CLI and chain directories. This is required whenever the circuit logic changes.

```bash
quantus developer build-circuits \
  --branching-factor 2 \
  --depth 1 \
  --circuits-path ../qp-zk-circuits \
  --chain-path ../chain
```

- `--branching-factor`: Number of proofs aggregated at each tree level.
- `--depth`: Depth of the aggregation tree. Total leaf proofs = `branching_factor ^ depth`.
- `--circuits-path`: Path to the `qp-zk-circuits` repo (default: `../qp-zk-circuits`).
- `--chain-path`: Path to the chain repo (default: `../chain`).
- `--skip-chain`: Skip copying binaries to the chain directory.

**What it does (4 steps):**
1. Builds the `qp-wormhole-circuit-builder` binary.
2. Runs the circuit builder to generate binary files in `generated-bins/` (includes `prover.bin`, `verifier.bin`, `common.bin`, `aggregated_verifier.bin`, `aggregated_common.bin`, `config.json` with SHA256 hashes).
3. Copies binaries to the CLI's `generated-bins/` directory and touches the aggregator source to force recompilation.
4. Copies chain-relevant binaries (`aggregated_common.bin`, `aggregated_verifier.bin`, `config.json`) to `chain/pallets/wormhole/` and touches the pallet source.

After running, rebuild the chain (`cargo build --release` in the chain directory) so `include_bytes!()` picks up the new binaries.

#### `quantus developer create-test-wallets`

Create standard test wallets (`crystal_alice`, `crystal_bob`, `crystal_charlie`) with developer passwords for local testing.

```bash
quantus developer create-test-wallets
```

---

### Wallet Management

```bash
# Create a new quantum-safe wallet
quantus wallet create --name my_wallet

# Create with explicit derivation path
quantus wallet create --name my_wallet --derivation-path "m/44'/189189'/0'/0/0"

# Import from mnemonic
quantus wallet import --name recovered_wallet --mnemonic "word1 word2 ... word24"

# Create from raw 32-byte seed
quantus wallet from-seed --name raw_wallet --seed <64-hex-chars>

# List wallets
quantus wallet list

# View wallet details
quantus wallet view --name my_wallet

# Export mnemonic
quantus wallet export --name my_wallet --format mnemonic
```

---

### Sending Tokens

```bash
# Simple transfer
quantus send --from crystal_alice --to <address> --amount 10.5

# With tip for priority
quantus send --from crystal_alice --to <address> --amount 10 --tip 0.1

# With manual nonce
quantus send --from crystal_alice --to <address> --amount 10 --nonce 42
```

---

### Batch Transfers

```bash
# From a JSON file
quantus batch send --from crystal_alice --batch-file transfers.json

# Generate identical test transfers
quantus batch send --from crystal_alice --count 10 --to <address> --amount 1.0

# Check batch limits
quantus batch config --limits
```

---

### Reversible Transfers

Schedule transfers with a time delay, allowing cancellation before execution.

```bash
# Schedule with default delay
quantus reversible schedule-transfer --from alice --to bob --amount 10

# Schedule with custom delay
quantus reversible schedule-transfer-with-delay --from alice --to bob --amount 10 --delay 3600

# Cancel a pending transfer
quantus reversible cancel --tx-id 0x<hash> --from alice
```

---

### High-Security Mode

Configure reversibility settings for an account (interceptor + delay).

```bash
# Check status
quantus high-security status --account <address>

# Enable high-security with an interceptor
quantus high-security set --interceptor <address> --delay-seconds 3600 --from alice

# Show accounts you guard
quantus high-security entrusted --from alice
```

---

### Account Recovery

Social recovery using trusted friends.

```bash
# Initiate recovery
quantus recovery initiate --rescuer bob --lost alice

# Friend vouches
quantus recovery vouch --friend charlie --lost alice --rescuer bob

# Claim after threshold met
quantus recovery claim --rescuer bob --lost alice
```

---

### Treasury

```bash
# Check treasury balance
quantus treasury balance

# Submit a spend proposal
quantus treasury submit-spend --beneficiary <address> --amount 100.0 --track small --from alice

# Payout an approved spend
quantus treasury payout --index 0 --from alice
```

---

### Privacy-Preserving Transfer Queries

Query transfers via a Subsquid indexer using hash-prefix queries that hide your exact address.

```bash
quantus transfers query \
  --subsquid-url https://indexer.quantus.com/graphql \
  --prefix-len 4 \
  --wallet my_wallet
```

---

### Block Analysis

```bash
# Analyze a specific block
quantus block analyze --number 1234 --all

# Analyze latest block
quantus block analyze --latest --extrinsics --events

# List blocks in a range
quantus block list --start 100 --end 110
```

---

### Generic Pallet Calls

Call any pallet function using metadata-driven parsing:

```bash
quantus call \
  --pallet Balances \
  --call transfer_allow_death \
  --args '["5GrwvaEF...", "1000000000000"]' \
  --from crystal_alice
```

---

### Other Commands

| Command | Description |
|---------|-------------|
| `quantus balance --address <addr>` | Query account balance |
| `quantus events --block 123` | Query events from a block |
| `quantus events --finalized` | Events from the latest finalized block |
| `quantus system` | System information |
| `quantus system --runtime` | Runtime version details |
| `quantus metadata --pallet Balances` | Explore chain metadata |
| `quantus version` | CLI version |
| `quantus compatibility-check` | Check CLI/node compatibility |

---

## 🔧 Environment Variables

### Password Management
- `QUANTUS_WALLET_PASSWORD`: Global password for all wallets
- `QUANTUS_WALLET_PASSWORD_<WALLET_NAME>`: Wallet-specific password (e.g., `QUANTUS_WALLET_PASSWORD_CRYSTAL_ALICE`)

### Node Configuration  
- Set via `--node-url` flag or default to `ws://127.0.0.1:9944`

## 💡 Getting Started

The CLI provides a comprehensive set of commands for blockchain interaction. Start by exploring the help system to discover available functionality:

1. **Explore commands**: Use `quantus --help` to see all available commands
2. **Discover options**: Use `quantus <command> --help` to see command-specific options
3. **Get details**: Add `--verbose` to any command for detailed execution information
4. **Connect to nodes**: Use `--node-url` to connect to different blockchain nodes

The CLI supports both simple commands and complex workflows, with built-in help and error recovery at every level.

## 🏗️ Architecture

### Quantum-Safe Cryptography
- **Dilithium (ML-DSA-87)**: Post-quantum digital signatures
- **Secure Storage**: AES-256-GCM + Argon2 encryption for wallet files
- **Future-Proof**: Ready for ML-KEM key encapsulation

### SubXT Integration
- **Type-Safe API**: Compile-time type checking for all blockchain operations
- **Metadata-Driven**: Discovers available functionality from chain metadata
- **Fresh Nonce Management**: Automatic nonce handling to avoid transaction conflicts
- **Progress Indicators**: Real-time transaction confirmation with spinners

### Smart Features
- **Dynamic Balance Formatting**: Automatically fetches chain decimals and token symbol
- **Progress Indicators**: Spinners during network operations
- **Error Recovery**: Comprehensive error handling with helpful messages
- **Development Mode**: Empty password detection for test wallets
- **Event Decoding**: Automatic SS58 address formatting in event output
- **Fresh Nonce Management**: Automatic nonce handling to avoid transaction conflicts
- **Transaction Retry Logic**: Exponential backoff for failed transactions
- **Latest Block Reading**: Consistent reading from latest (not finalized) blocks

### Real Blockchain Integration
- **Substrate Integration**: Direct connection to Quantus node via WebSocket
- **Metadata-Driven**: Discovers available functionality from chain metadata
- **Transaction Monitoring**: Real-time transaction confirmation and fee calculation
- **Extensible Architecture**: Macro-based extrinsic submission supports any pallet
- **Event System**: Query events by block number, hash, or finalized status
- **Storage Operations**: Direct storage queries and sudo-based storage modifications
- **Reversible Transfers**: Schedule and cancel reversible transactions
- **Scheduler Integration**: Query and manage scheduled operations

## 🛠️ Current Status

**✅ Fully Implemented:**
- Quantum-safe wallet management with Dilithium cryptography
- Real blockchain operations (send, balance, storage, events)
- Tech Collective governance (add/remove members, voting)
- Generic pallet calls via metadata-driven parsing
- Reversible transfers with scheduling and cancellation
- Scheduler integration for automated operations
- System information and runtime management
- Event querying with SS58 address formatting
- Fresh nonce management and transaction retry logic

## 🎯 Real-World Ready

The Quantus CLI is a **production-ready** tool that:

✅ **Handles Real Money**: All transactions are real and irreversible  
✅ **Quantum-Safe**: Uses post-quantum cryptography for future security  
✅ **Developer-Friendly**: Rich tooling and clear error messages  
✅ **Scriptable**: Environment variables and flags for automation  
✅ **Extensible**: Clean architecture for adding new blockchain features  
✅ **SubXT-Powered**: Modern, type-safe blockchain integration

**⚠️ Security Note**: This tool handles real cryptocurrency. Always:
- Back up your wallet files and mnemonic phrases
- Use strong passwords for production wallets
- Test with small amounts first
- Keep your private keys secure

## 🔧 Development Tools

### Metadata Regeneration

The project includes a script to regenerate SubXT types and metadata when the blockchain runtime changes:

```bash
# Regenerate metadata and types from the running node
./regenerate_metadata.sh
```

**What this script does:**
1. **Updates metadata**: Downloads the latest chain metadata to `src/quantus_metadata.scale`
2. **Generates types**: Creates type-safe Rust code in `src/chain/quantus_subxt.rs`
3. **Formats code**: Automatically formats the generated code with `cargo fmt`

**When to use:**
- After updating the Quantus runtime
- When new pallets are added to the chain
- When existing pallet APIs change
- To ensure CLI compatibility with the latest chain version

**Requirements:**
- `subxt-cli` must be installed: `cargo install subxt-cli`
- Node must be fully synced and ready

**Usage:**
```bash
# Use default node URL (ws://127.0.0.1:9944)
./regenerate_metadata.sh

# Use custom node URL
./regenerate_metadata.sh --node-url ws://other-node:9944

# Show help
./regenerate_metadata.sh --help
```

**Output:**
```
Using node URL: ws://127.0.0.1:9944
Updating metadata file at src/quantus_metadata.scale...
Generating SubXT types to src/chain/quantus_subxt.rs...
Formatting generated code...
Done!
```

This ensures the CLI always has the latest type definitions and can interact with new chain features.