# AUDIT PROTOCOL: FRONTEND NEXT.JS

**Target Stack:** TypeScript, Next.js (App Router), React
**Context:** Lean Code Philosophy — production-grade, 10/10 quality
**Executor:** AI Agent / LLM

---

## 1. PRIME DIRECTIVE: LEAN CODE

Every line of code must verify its existence against:

1. **Value**: Does this add direct user or business value?
2. **Necessity**: Can this be done simpler? (KISS)
3. **Uniqueness**: Is this logic repeated? (DRY)
4. **Relevance**: Is this "Just in Case" code? (YAGNI) -> **DELETE IT**.

---

## 2. NORMALIZATION & CONSISTENCY

### 2.1 Single Source of Truth

- **Rule**: Every concept has ONE authoritative location. Data transformations happen once.
- **Violation**: Same API call built manually in 3 different files with different field subsets.
- **Violation**: Same calculation (rounding, unit conversion, fee computation) written inline in multiple places.
- **Fix**: Extract to a shared service or utility. Callers pass context, the service builds the payload/performs the logic.

### 2.2 Consistent Patterns Across Peers

- **Rule**: Functions that serve the same role MUST follow the same pattern.
- **Violation**: Three executors where one sends full diagnostics data, another sends partial, third sends nothing — to the same API endpoint.
- **Violation**: Error handling differs between sibling functions (one catches + reports, another throws, third swallows).
- **Fix**: Define the pattern ONCE (e.g. a session, a builder, a base class), then all peers use it identically.

### 2.3 Naming Conventions

- **Rule**: Same concept = same name everywhere. No synonyms across layers.
- **Violation**: `tokenAmount` in one file, `quantity` in another, `broAmount` in a third — all meaning the same thing.
- **Violation**: `totalSats` vs `amount` vs `btcAmount` for the same BTC value.
- **Fix**: Define a glossary in types. Use it everywhere. Conversion happens at boundaries, not inline.

### 2.4 Constants & Magic Numbers

- **Rule**: No magic numbers. All domain values in named constants.
- **Violation**: `Math.ceil(amount * 50 / 10000)` scattered across files — what is 50? What is 10000?
- **Fix**: `TAKER_FEE_BPS = 50`, `BPS_DENOMINATOR = 10_000`, used from a shared constants file.

---

## 3. REUSABILITY & ISOLATION

### 3.1 Service Isolation

- **Rule**: Services own their domain. Callers should not assemble service internals.
- **Violation**: An executor manually building a review payload with 10 fields, deciding which to include.
- **Fix**: The review service exposes a high-level API (`session.start()`, `session.error(msg)`). It decides what data to include based on what's been accumulated.

### 3.2 Cross-Cutting Concerns

- **Rule**: Logging, error reporting, telemetry — handled by dedicated services, not sprinkled in business logic.
- **Violation**: `reportError({...12 fields...})` inlined in a catch block alongside business error handling.
- **Fix**: The executor does its job. A wrapper or session handles reporting as a side effect.

### 3.3 Shared Utilities

- **Rule**: If 2+ files need the same logic, it belongs in `utils/` or a shared service.
- **Violation**: Three spell builders each computing `Math.ceil(a * b / c)` with slightly different variable names.
- **Fix**: `utils/price.ts` exports `calcAmount()`, `calcQuantity()`, `calcFee()` — tested, documented, used everywhere.

### 3.4 Type Reuse

- **Rule**: Define types at the boundary where data enters; reuse downstream.
- **Violation**: Same UTXO shape defined as inline types in 5 different files.
- **Fix**: `types/utxo.ts` exports `BtcUtxo`, `TokenUtxo` — imported everywhere.

---

## 4. MODULARIZATION

### 4.1 File Size Limits

| Threshold   | Severity | Action                                  |
| ----------- | -------- | --------------------------------------- |
| > 150 lines | Info     | Review for extraction opportunities     |
| > 200 lines | Warning  | Evaluate if split improves architecture |
| > 300 lines | Critical | Requires justification or refactor      |

**IMPORTANT: Refactoring must be justified.**

A file stays large if:

- It's mostly JSX/HTML that can't be meaningfully split
- Splitting would create artificial boundaries
- The file is cohesive and single-purpose

A file MUST be split if:

- Contains mixed concerns (UI + business logic)
- Has reusable logic that benefits other components
- Would be cleaner/faster with proper hooks/helpers
- Demonstrates better professional architecture

**Fix strategies (when justified):**

- Extract helper functions to `utils/`
- Create custom hooks in `hooks/`
- Split components into smaller leaf components
- Move business logic to `services/`

**Goal:** Professional, maintainable code—not arbitrary line counts.

### 4.2 External API Providers

When calling external APIs (QuickNode, Mempool, Stripe, etc.):

**Single provider:**

- Direct service file is acceptable
- Example: `services/stripe.ts`

**Multiple providers (same domain):**

- **MUST use Provider Pattern:**

```
services/
├── providers/           # Raw API clients
│   ├── types.ts         # Common interface
│   ├── provider-a.ts    # Implements interface
│   ├── provider-b.ts    # Implements interface
│   └── router.ts        # Unified access with fallback
├── domain/              # High-level services (use router)
│   └── service.ts
```

**Violation:** Multiple API clients at same level without abstraction.

---

## 5. APP ROUTER ARCHITECTURE

### 5.1 Server vs Client Components

- **Rule**: Default to **Server Components**. Use `"use client"` only when interactivity is strictly needed.
- **Violation**: Adding `"use client"` to a page that only fetches/displays data.

### 5.2 Data Fetching

- **Rule**: Fetch data directly in Server Components using `async/await`.
- **Violation**: Using `fetch` inside `useEffect` for initial data load.

### 5.3 Metadata

- **Rule**: Use the Metadata API (`export const metadata`).

---

## 6. COMPONENT & STATE

### 6.1 Hooks Usage

- **Rule**: Custom hooks must be logically sound and reusable.
- **Violation**: Huge `useEffect` blocks with missing dependencies.
- **Fix**: Break down logic, use `useCallback`/`useMemo` correctly.

### 6.2 Derived State

- **Rule**: If a value can be computed from existing state, compute it — don't store it.
- **Violation**: A `useState` that mirrors filtered/transformed version of another state.
- **Fix**: `useMemo` or inline computation.

### 6.3 Context Boundaries

- **Rule**: Context provides state. Business logic lives in services.
- **Violation**: A React context with 200 lines of async executor logic inside the provider.
- **Fix**: Context orchestrates (calls services, dispatches state). Services execute.

---

## 7. CODE QUALITY

### 7.1 Styling

- **Rule**: Enforce Tailwind CSS (if standard) or CSS Modules.

### 7.2 Images

- **Rule**: Use `next/image` for asset optimization.

### 7.3 Zombie Code

- **Rule**: No commented-out code. **Delete it.**
- **Rule**: No unused imports, variables, or functions. If the linter flags it, fix it.

### 7.4 Logging

- **Rule**: No `console.log` in production code.
- **Exception:** Services can use structured, conditional logging with clear prefixes.

### 7.5 Health Endpoint

- **Rule**: `/api/health` with dynamic version from package.json.

### 7.6 Error Handling

- **Rule**: Errors are handled at the right level. Don't catch-and-ignore unless explicitly justified.
- **Rule**: Error messages must be actionable — include what failed, why, and what data was involved.
- **Violation**: `catch (e) { console.warn(e); }` hiding real failures.
- **Violation**: Generic `"Operation failed"` with no context about which step or what input caused it.

### 7.7 Type Safety

- **Rule**: Minimize `any`. Use `unknown` + type guards when the type is truly dynamic.
- **Rule**: No unsafe casts (`as any`) to bypass type checking — fix the types instead.
- **Violation**: `order: apiOrder as any` hiding a type mismatch between what's built and what's expected.

---

## 8. ELEGANCE & SIMPLIFICATION

### 8.1 Complexity Budget

- **Rule**: Every function should do ONE thing. If it needs a comment explaining a section, that section is a function.
- **Rule**: Cyclomatic complexity > 10 per function = refactor.
- **Violation**: A 100-line function with 5 nested if/else blocks and 3 try/catch levels.

### 8.2 Guard Clauses Over Nesting

- **Rule**: Return early for invalid states. Don't wrap the happy path in an if block.
- **Violation**: `if (data) { if (data.items) { if (data.items.length > 0) { ... } } }`
- **Fix**: `if (!data?.items?.length) return;`

### 8.3 Declarative Over Imperative

- **Rule**: Prefer `.map()`, `.filter()`, `.reduce()` over manual loops with push/accumulate.
- **Rule**: Prefer object spread over manual field-by-field assignment.
- **Exception**: Performance-critical paths where imperative is measurably faster.

### 8.4 Self-Documenting Code

- **Rule**: Code should read like prose. Variable and function names should make comments unnecessary.
- **Violation**: `const x = a * b / c;` — what is x? what are a, b, c?
- **Fix**: `const totalTakenSats = Math.ceil(priceNum * quantity / priceDen);`

### 8.5 No Redundant Wrappers

- **Rule**: Don't create a function that just calls another function with the same arguments.
- **Violation**: `function broadcastTx(hex) { return router.broadcastTransaction(hex); }`
- **Exception**: When the wrapper adds value (logging, retry, transformation, abstraction layer).

---

## 9. SECURITY & ROBUSTNESS

### 9.1 Input Validation

- **Rule**: Validate at system boundaries (user input, API responses, external data).
- **Rule**: Internal function calls between trusted modules do NOT need redundant validation.
- **Violation**: Validating the same field in the component, the hook, the service, and the API call.

### 9.2 Arithmetic Safety

- **Rule**: Bitcoin/financial arithmetic must use integer math (satoshis, raw token units). Never floating point for final values.
- **Rule**: Rounding strategy (ceil/floor/round) must match the on-chain contract exactly.
- **Violation**: Using `Math.round()` where the contract uses `Math.ceil()` — causes 1-sat mismatches.

### 9.3 Secrets & Sensitive Data

- **Rule**: No API keys, private keys, or secrets in client-side code.
- **Rule**: `.env` files with secrets must be in `.gitignore`.
- **Rule**: Review payloads must strip sensitive data (WASM binaries, full tx hex in non-error paths).

---

## 10. AUDIT EXECUTION

1. **Scan** `app/`, `components/`, `services/`, `hooks/`, `contexts/`, `utils/`, `types/`
2. **Check** each section of this protocol (1-9) against the codebase
3. **Identify** violations by severity:
   - **Critical**: Will cause bugs, data loss, or security issues in production
   - **High**: Architectural violation that degrades maintainability significantly
   - **Medium**: Pattern inconsistency or missed optimization
   - **Low**: Style/naming issue
4. **Score** the codebase:
   - 90-100: Excellent — production-ready, elegant, consistent
   - 80-89: Good — minor issues, no architectural gaps
   - 70-79: Needs improvement — inconsistencies, some missing patterns
   - < 70: **FAILED** — structural issues that must be addressed before shipping
5. **Report** findings with file:line references and before/after examples
6. **Prioritize** fixes: Critical first, then High, skip Low unless trivial
