Skip to content

Commit fa03943

Browse files
committed
docs: docs: Add comprehensive developer documentation for AI-assisted development
1 parent b77d5bd commit fa03943

11 files changed

+660
-0
lines changed

docs/CODING_STANDARDS.md

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
# Coding Standards
2+
3+
This document outlines the coding standards and best practices for the Mostro CLI project. These guidelines ensure code quality, maintainability, and consistency across the codebase.
4+
5+
## Core Principles
6+
7+
### 1. Readability and Reuse
8+
**Priority**: Code should be written for humans first, machines second.
9+
- **Clear naming**: Use descriptive names for functions, variables, and modules (e.g., `parse_dm_events` vs `pde`).
10+
- **Function reuse**: Extract common logic into reusable functions. Place shared utilities in appropriate modules (`src/util/`, `src/parser/`, etc.).
11+
- **Module organization**: Group related functionality together (CLI commands in `src/cli/`, Protocol parsing in `src/parser/`, Utilities in `src/util/`).
12+
13+
### 2. Avoid Code Duplication (DRY Principle)
14+
**Don't Repeat Yourself**: If the same logic appears in multiple places, extract it.
15+
- **Extract common patterns**: Create helper functions for repeated operations like DM sending.
16+
- **Centralize constants**: Import from `mostro-core::prelude` instead of hardcoding values.
17+
18+
### 3. Simplicity
19+
**Keep It Simple**: Prefer straightforward solutions over clever ones.
20+
- **Avoid premature optimization**: Write clear code first, optimize only when needed.
21+
- **Prefer explicit over implicit**: Use `Option` and `Result` types explicitly rather than hiding errors with `unwrap()`.
22+
23+
### 4. Function Length Limit
24+
**Maximum 300 lines per function**: If a function exceeds this limit, split it into smaller, single-responsibility functions.
25+
26+
## Rust-Specific Guidelines
27+
28+
### Error Handling
29+
- **Use `Result<T, E>`**: Functions that can fail should return `Result`.
30+
- **Use `anyhow::Result`**: For application-level errors, use `anyhow::Result<T>`.
31+
- **Propagate errors**: Use the `?` operator to propagate errors up the call stack.
32+
- **Add context**: Use `.context("...")` from `anyhow` to add meaningful error messages.
33+
34+
### Type Safety
35+
- **Use strong types**: Prefer newtypes or enums (`Action`, `Status`) over primitive types.
36+
- **Leverage enums**: Use enums for state machines and role management.
37+
38+
### Async/Await
39+
- **Prefer async/await**: Use `async fn` for I/O and network operations.
40+
- **Handle timeouts**: Use `tokio::time::timeout` for network operations.
41+
42+
### Documentation
43+
- **Document public APIs**: Use `///` doc comments for public functions and types.
44+
- **Explain "why"**: Document the reasoning behind complex logic, not just "what".
45+
46+
## Nostr and Mostro-Specific Guidelines
47+
48+
### Event Kinds
49+
- **Use constants**: Always use constants from `mostro-core::prelude` (e.g., `NOSTR_ORDER_EVENT_KIND`).
50+
- **Never hardcode**: Avoid hardcoding event kind numbers like 38383.
51+
52+
### Message Handling
53+
- **Parse DMs consistently**: Use `parse_dm_events` for all DM parsing.
54+
- **Support multiple message types**: Handle both GiftWrap (NIP-59) and PrivateDirectMessage (NIP-17).
55+
56+
### Key Management
57+
- **Identity vs Trade Keys**:
58+
- **Identity keys** (index 0): User's main identity, used for signing.
59+
- **Trade keys** (index 1+): Ephemeral keys for each trade, ensuring privacy.
60+
61+
## Code Organization Patterns
62+
63+
### Module Structure
64+
```text
65+
src/
66+
├── main.rs # Entry point
67+
├── cli.rs # CLI definitions and Context
68+
├── db.rs # Database models (User, Order)
69+
├── cli/ # CLI command implementations
70+
├── parser/ # Event parsing and display
71+
└── util/ # Core utilities (events, messaging, net)
72+
```
73+
74+
### Re-export Pattern
75+
Use `mod.rs` files to re-export commonly used items from submodules to keep imports clean.
76+
77+
## Database Patterns
78+
- **User Model**: Use chainable setters and the `.save()` pattern.
79+
- **Order Management**: Use `Order::new()` to handle both insertion and updates.
80+
81+
## CLI Command Pattern
82+
All CLI commands follow a standard flow:
83+
1. Validate inputs.
84+
2. Get required keys (Identity/Trade).
85+
3. Build the Mostro message.
86+
4. Send to Mostro (NIP-59).
87+
5. Wait for response (Subscription).
88+
6. Parse and display results.
89+
90+
## Summary Checklist
91+
- [ ] Code is readable and well-named.
92+
- [ ] No code duplication (DRY).
93+
- [ ] Functions are under 300 lines.
94+
- [ ] Errors are handled properly (`Result`, `?`).
95+
- [ ] Event kinds use constants from `mostro-core`.
96+
- [ ] Both GiftWrap and PrivateDirectMessage are supported.
97+
- [ ] Public APIs are documented.
98+
- [ ] Code passes `cargo fmt` and `cargo clippy`.
99+
- [ ] Tests pass (`cargo test`).

docs/CREATING_ORDERS.md

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
# Creating Orders in Mostro CLI
2+
3+
This document explains how to create new buy and sell orders using Mostro CLI.
4+
5+
## Overview
6+
7+
Creating an order involves:
8+
1. Specifying order parameters (type, amount, currency, etc.)
9+
2. Building a Mostro message
10+
3. Sending it to the Mostro coordinator via Nostr
11+
4. Receiving confirmation
12+
5. Waiting for someone to take the order
13+
14+
## Order Types
15+
16+
### Sell Order (Maker sells Bitcoin)
17+
User wants to **sell Bitcoin** for fiat currency.
18+
```bash
19+
mostro-cli neworder -k sell -c USD -f 100 -a 50000 -m "PayPal"
20+
```
21+
22+
### Buy Order (Maker buys Bitcoin)
23+
User wants to **buy Bitcoin** with fiat currency.
24+
```bash
25+
mostro-cli neworder -k buy -c EUR -f 200 -m "Bank Transfer" -i lnbc...
26+
```
27+
28+
## Order Parameters
29+
30+
### Required Parameters
31+
| Parameter | Flag | Description | Example |
32+
|-----------|------|-------------|---------|
33+
| Kind | `-k`, `--kind` | "buy" or "sell" | `sell` |
34+
| Fiat Code | `-c`, `--fiat-code` | Currency code | `USD`, `EUR`, `ARS` |
35+
| Fiat Amount | `-f`, `--fiat-amount` | Amount in fiat | `100` or `100-500` (range) |
36+
| Payment Method | `-m`, `--payment-method` | How to pay | `"PayPal"`, `"Bank Transfer"` |
37+
38+
### Optional Parameters
39+
| Parameter | Flag | Description | Default |
40+
|-----------|------|-------------|---------|
41+
| Amount | `-a`, `--amount` | Bitcoin in sats | 0 (market price) |
42+
| Premium | `-p`, `--premium` | Price premium % | 0 |
43+
| Invoice | `-i`, `--invoice` | Lightning invoice (buy orders) | None |
44+
| Expiration Days | `-e`, `--expiration-days` | Days until expired | 0 |
45+
46+
## Order Examples
47+
48+
### 1. Simple Sell Order (Market Price)
49+
```bash
50+
mostro-cli neworder -k sell -c USD -f 100 -m "PayPal"
51+
```
52+
53+
### 2. Range Order (Flexible Amount)
54+
```bash
55+
mostro-cli neworder -k sell -c USD -f 100-500 -m "PayPal,Venmo"
56+
```
57+
58+
### 3. Buy Order with Lightning Invoice
59+
```bash
60+
mostro-cli neworder -k buy -c USD -f 50 -i lnbc500u1p3.... -m "Cash App"
61+
```
62+
63+
For technical details on the code flow and message structures, see [ORDER_FLOW_TECHNICAL.md](./ORDER_FLOW_TECHNICAL.md).

docs/DATABASE_SCHEMA.md

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# Database Schema
2+
3+
Mostro CLI uses a local SQLite database (`mcli.db`) to store user identity and trade history.
4+
5+
## Table: `users`
6+
Stores the BIP-39 mnemonic and identity information.
7+
8+
| Column | Type | Description |
9+
|--------|------|-------------|
10+
| `i0_pubkey` | `CHAR(64)` | Primary Key. The user's identity pubkey. |
11+
| `mnemonic` | `TEXT` | The 12-word seed phrase. |
12+
| `last_trade_index` | `INTEGER` | The last derived trade key index. |
13+
| `created_at` | `INTEGER` | Timestamp of creation. |
14+
15+
## Table: `orders`
16+
Stores details of orders created or taken by the user.
17+
18+
| Column | Type | Description |
19+
|--------|------|-------------|
20+
| `id` | `TEXT` | Primary Key. Order UUID. |
21+
| `kind` | `TEXT` | "buy" or "sell". |
22+
| `status` | `TEXT` | Current status (pending, active, etc.). |
23+
| `amount` | `INTEGER` | Satoshis. |
24+
| `fiat_code` | `TEXT` | e.g., "USD". |
25+
| `fiat_amount` | `INTEGER` | Fiat units. |
26+
| `trade_keys` | `TEXT` | Hex-encoded private key for this trade. |
27+
| `is_mine` | `BOOLEAN` | True if the user created the order. |
28+
| `created_at` | `INTEGER` | Creation timestamp. |
29+
30+
## Implementation Reference
31+
- `src/db.rs`: Contains the `User` and `Order` structs and SQL queries.
32+
- `src/util/storage.rs`: Helper functions for database interaction.

docs/DISPUTE_MANAGEMENT.md

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# Dispute Management
2+
3+
This document covers how disputes are handled in Mostro CLI by both users and administrators.
4+
5+
## User Dispute Flow
6+
7+
When a trade goes wrong (e.g., fiat sent but Bitcoin not released), either party can initiate a dispute.
8+
9+
### Initiate a Dispute
10+
```bash
11+
mostro-cli dispute -o <order-id>
12+
```
13+
Mostro changes the order status to `Dispute`. This prevents any further automated transitions and flags the trade for manual intervention.
14+
15+
## Admin/Solver Flow
16+
17+
Admins or designated solvers use special commands to resolve conflicts. These commands require the `ADMIN_NSEC` environment variable to be set.
18+
19+
### 1. List Active Disputes
20+
```bash
21+
mostro-cli listdisputes
22+
```
23+
24+
### 2. Take a Dispute
25+
Before resolving, an admin must "take" the dispute to indicate they are handling it.
26+
```bash
27+
mostro-cli admtakedispute -d <dispute-id>
28+
```
29+
30+
### 3. Settle (Pay Buyer)
31+
If the buyer proved they sent fiat, the admin settles the hold invoice to pay the buyer.
32+
```bash
33+
mostro-cli admsettle -o <order-id>
34+
```
35+
36+
### 4. Cancel (Refund Seller)
37+
If the buyer failed to pay, the admin cancels the order to refund the locked Bitcoin to the seller.
38+
```bash
39+
mostro-cli admcancel -o <order-id>
40+
```
41+
42+
## Security
43+
Admin commands are gated by public key verification on the Mostro coordinator side. The CLI must sign these messages with the private key corresponding to a registered admin pubkey.

docs/KEY_IMPLEMENTATION.md

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
# Key Management Implementation
2+
3+
This document provides technical details, code examples, and security practices for Mostro CLI key management.
4+
5+
## Database Storage
6+
7+
### User Table
8+
Stores the root secret and identity info.
9+
10+
```sql
11+
CREATE TABLE users (
12+
i0_pubkey char(64) PRIMARY KEY, -- Identity public key (hex)
13+
mnemonic TEXT, -- BIP-39 mnemonic
14+
last_trade_index INTEGER, -- Last used trade index
15+
created_at INTEGER
16+
);
17+
```
18+
19+
### Order Table
20+
Stores trade-specific keys.
21+
22+
```sql
23+
CREATE TABLE orders (
24+
id TEXT PRIMARY KEY,
25+
trade_keys TEXT, -- Private key for this trade (hex)
26+
-- ... other fields
27+
);
28+
```
29+
30+
## Implementation Details
31+
32+
### Deriving Identity Keys
33+
```rust
34+
pub async fn get_identity_keys(pool: &SqlitePool) -> Result<Keys> {
35+
let user = User::get(pool).await?;
36+
let account = NOSTR_ORDER_EVENT_KIND as u32; // 38383
37+
38+
Keys::from_mnemonic_advanced(
39+
&user.mnemonic,
40+
None,
41+
Some(account),
42+
Some(0),
43+
Some(0) // Identity is always index 0
44+
)
45+
}
46+
```
47+
48+
### Deriving Trade Keys
49+
```rust
50+
pub async fn get_trade_keys(pool: &SqlitePool, index: i64) -> Result<Keys> {
51+
let user = User::get(pool).await?;
52+
let account = NOSTR_ORDER_EVENT_KIND as u32;
53+
54+
Keys::from_mnemonic_advanced(
55+
&user.mnemonic,
56+
None,
57+
Some(account),
58+
Some(0),
59+
Some(index as u32) // Incremental index 1, 2, 3...
60+
)
61+
}
62+
```
63+
64+
## Security Best Practices
65+
66+
### DO ✅
67+
- **Use unique keys**: Always use `get_next_trade_keys()` for new orders.
68+
- **Sign with identity**: Prove authenticity while maintaining sender privacy.
69+
- **Update indices**: Ensure `last_trade_index` is updated after successful creation.
70+
71+
### DON'T ❌
72+
- **Reuse keys**: Never use the same trade key for two different orders.
73+
- **Author with identity**: Never set the `pubkey` of a public event to your identity key.
74+
- **Lose mnemonic**: Keys cannot be recovered without the seed phrase.
75+
76+
## Key Recovery
77+
78+
If the local database is lost but the mnemonic is saved:
79+
1. **Identity**: Re-deriving index 0 restores the original `npub`.
80+
2. **Trade History**: Re-deriving indices 1, 2, 3... restores access to trade messages.
81+
3. **Session Sync**: Use `mostro-cli restore` to fetch active orders and their associated trade indices from the Mostro coordinator.
82+
83+
## Troubleshooting
84+
85+
### "Cannot decrypt message"
86+
Usually means the CLI is trying to use the wrong trade key. Ensure you are loading the key associated with the specific `order_id` from the database.
87+
88+
### "Trade index mismatch"
89+
Occurs when the local database index is behind Mostro's records. Run `mostro-cli restore` to synchronize.

0 commit comments

Comments
 (0)