# StreamRift Refactor Base 0

> Architectural snapshot of Galactus One at the start of the StreamRift refactor.
> All future refactoring work is measured against this baseline.

- **Branch:** `streamrift-0`
- **Staging:** `dev.g1.newbx.com` (verified)
- **Production:** `g1.newbx.com` (untouched)
- **Date:** 2026-02-17

---

## Architecture Overview

**Monorepo (npm workspaces):**

| Workspace             | Path              | Description                                          |
| --------------------- | ----------------- | ---------------------------------------------------- |
| `@galactus/dashboard` | `apps/dashboard`  | React 18 + Vite SPA — trading terminal               |
| `@galactus/relay`     | `apps/relay`      | Express + WebSocket — transport-only CORS bypass     |
| `@galactus/guides`    | `apps/guides`     | React 18 + Vite SPA — educational content with KaTeX |
| `@galactus/shared`    | `packages/shared` | Shared TypeScript types and utilities                |

**Frontend-backend split:** API keys live in the browser. The relay is transport-only — it forwards signed requests and proxies WebSocket connections but never sees credentials. RSA-PSS signing via WebCrypto; node-forge handles PEM conversions.

**Data flow:**

```
App.tsx (orchestrator)
  ├── 6 custom hooks (state + side effects)
  │     ├── useKalshiConnection     → relayHttp → Relay :8787 → Kalshi REST
  │     ├── useStreamManagement     → relayWs   → Relay :8787 → Kalshi WS
  │     ├── usePolymarketIntegration → Polymarket CLOB (direct)
  │     ├── usePositionTracking     → polls positions via relayHttp
  │     ├── useOrderManagement      → order placement via relayHttp
  │     └── useDisplayPreferences   → localStorage (local only)
  └── Components (pages, organisms, molecules, atoms)
```

---

## Dashboard Inventory

### App.tsx — 391 lines

Lean orchestrator that composes 6 custom hooks and routes to 10 page views. Contains no business logic — all state management and side effects are delegated to hooks.

### Custom Hooks (9 files, 2,224 lines)

| Hook                       | Lines | Description                                               |
| -------------------------- | ----: | --------------------------------------------------------- |
| `useDisplayPreferences`    |    60 | POV, odds format, data mode toggles                       |
| `useFlash`                 |   226 | Flash animations for live price changes                   |
| `useKalshiConnection`      |   353 | Kalshi API lifecycle, credentials, auto-connect, profiles |
| `useLocalStorageSetting`   |   105 | Generic localStorage-backed state                         |
| `useOrderManagement`       |   362 | Order ticket, placement, kill-all, fills, cancel/decrease |
| `usePolymarketIntegration` |   291 | Polymarket CLOB client, open orders, place/cancel         |
| `usePositionTracking`      |   329 | Position loading, P&L tracking, portfolio polling         |
| `useStreamManagement`      |   405 | Market stream lifecycle, chart periods, feed status       |
| `useTableSort`             |    93 | Shared sorting logic for sports tables                    |

### Components (188 files)

| Tier                | Count | Directory                         |
| ------------------- | ----: | --------------------------------- |
| Atoms               |    28 | `components/atoms/`               |
| Molecules           |    49 | `components/molecules/`           |
| Organisms           |    65 | `components/organisms/`           |
| Pages               |    10 | `components/pages/`               |
| Sports              |     8 | `components/sports/`              |
| NBA Value Dashboard |     8 | `components/nba-value-dashboard/` |
| Market Explorer     |     5 | `components/market-explorer/`     |
| Layout              |     4 | `components/layout/`              |
| Hotkeys             |     1 | `components/hotkeys/`             |
| Root (legacy)       |    10 | `components/` (root level)        |

**Atoms (28):** AlertBanner, Avatar, Badge, ChangeIndicator, DateDisplay, Dropdown, EmptyState, GlossaryTooltip, LiquidityBar, LoadingState, Modal, Money, MoneyText, Odds, PriceText, PriceWithOdds, ProbabilityBar, SecretCredentialField, SentimentGauge, SideBadge, SortableTh, Sparkline, StatusDot, TableCells, ThemeToggle, TickerDisplay, Toggle, Tooltip

**Pages (10):** GateView, LoginView, ExploreView, MarketDetailView, NBAView, NbaValueDashboardView, ValueDashboardView, PositionsView, OrdersView, SettingsView

**Root-level legacy (10):** CredentialsPanel, Dashboard, DashboardHeader, ErrorBoundary, FillNotification, MarketsTable, OrderTicket, OrdersTable, PositionsTable, StatusBar

### Library Modules (59 files)

| Group                     | Count | Key Files                                                                                                                                      |
| ------------------------- | ----: | ---------------------------------------------------------------------------------------------------------------------------------------------- |
| Core API & connectivity   |     8 | `kalshiApi`, `kalshiAuth`, `relayHttp`, `relayWs`, `marketStream`, `userStream`, `smartRelayAdapter`, `smartRelayStream`                       |
| State & data management   |     9 | `marketState`, `positionTracker`, `orderMonitor`, `candlestickAggregator`, `timeSeriesStore`, `state`, `stream`, `dataMode`, `marketTransform` |
| Formatting & utilities    |     8 | `formatters`, `dateUtils`, `oddsConversion`, `price`, `pricingPOV`, `sizeClasses`, `typeCoercers`, `utils`                                     |
| Sports & market discovery |     7 | `nba`, `kalshiProfiles`, `kalshiTicker/*` (3), `sportsDiscovery/*` (4)                                                                         |
| NBA consolidated          |    10 | `nbaConsolidated/*` — pricing, tickers, team names, volume, view modes                                                                         |
| Charts & theme            |     3 | `chartManager`, `themeManager`, `sportsStream/*` (4)                                                                                           |
| Polymarket                |     7 | `polymarket/*` — client, gamma, streams, normalize, types                                                                                      |
| Hotkeys                   |     4 | `hotkeys/*` — provider, hook, types, index                                                                                                     |

---

## Relay Inventory (17 modules)

### Core (7)

| Module             | Description                                                 |
| ------------------ | ----------------------------------------------------------- |
| `index.ts`         | `RelayServer` class — wires middleware, routes, WS servers  |
| `config.ts`        | Server configuration from env vars                          |
| `logger.ts`        | Logger factory                                              |
| `httpRelay.ts`     | `forwardHttpRequest()` — axios-based HTTP proxy             |
| `wsRelay.ts`       | `WebSocketRelay` — multiplexed WS proxy with reconnect/ping |
| `responseCache.ts` | TTL cache for GET relay responses                           |
| `types.ts`         | Internal types                                              |

### Middleware (4)

| Module                | Description                        |
| --------------------- | ---------------------------------- |
| `cors.ts`             | CORS header configuration          |
| `errorHandler.ts`     | Express error handler              |
| `requestValidator.ts` | Validates relay request shape      |
| `adminAuth.ts`        | Bearer token gate for admin routes |

### Smart Relay (6)

| Module                 | Description                                           |
| ---------------------- | ----------------------------------------------------- |
| `index.ts`             | `SmartRelay` orchestrator — wires sub-components      |
| `ApiKeyStore.ts`       | Kalshi API key pool (add/remove/enable, round-robin)  |
| `KalshiFetcher.ts`     | Polls Kalshi REST/WS for market + orderbook data      |
| `PolymarketFetcher.ts` | Polls Polymarket CLOB for market data                 |
| `MarketCache.ts`       | In-memory TTL cache for markets and orderbooks        |
| `StreamBroadcaster.ts` | Manages `/stream/markets` subscriptions, pushes diffs |

### Endpoints (9)

| Method   | Path                     | Description                                             |
| -------- | ------------------------ | ------------------------------------------------------- |
| `GET`    | `/health`                | Health check — uptime, WS count, cache stats            |
| `POST`   | `/relay/http`            | Core HTTP proxy — forwards signed requests              |
| `WS`     | `/relay/ws`              | Multiplexed WS proxy (connect, subscribe, send, close)  |
| `WS`     | `/stream/markets`        | Smart relay push stream (markets + orderbooks channels) |
| `GET`    | `/stream/status`         | Smart relay detailed status (admin)                     |
| `GET`    | `/admin/keys`            | List API keys, redacted (admin)                         |
| `POST`   | `/admin/keys`            | Add API key (admin)                                     |
| `DELETE` | `/admin/keys/:id`        | Remove API key (admin)                                  |
| `POST`   | `/admin/keys/:id/enable` | Re-enable API key (admin)                               |

---

## Shared Package (6 files)

| File                         | Contents                                                                                                                                                                               |
| ---------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `types/relay.ts`             | HTTP/WS relay types, smart relay stream protocol, cached market types                                                                                                                  |
| `types/kalshi.ts`            | Kalshi REST and WebSocket types                                                                                                                                                        |
| `types/errors.ts`            | Error hierarchy: `RelayError`, `KalshiApiError`, `NetworkError`, `TimeoutError`, `ValidationError`, `AuthenticationError`, `UpstreamError`, `ConnectionError`, `InvalidOperationError` |
| `utils/pathNormalization.ts` | Path canonicalization for RSA-PSS signing                                                                                                                                              |
| `utils/requestId.ts`         | Request ID generation and validation                                                                                                                                                   |
| `index.ts`                   | Public barrel re-export                                                                                                                                                                |

---

## Key Metrics

| Metric               | Count |
| -------------------- | ----: |
| Dashboard components |   188 |
| Custom hooks         |     9 |
| Library modules      |    59 |
| Relay modules        |    17 |
| Page views           |    10 |
| Relay endpoints      |     9 |
| Shared types/utils   |     6 |
| Barrel files         |    11 |

---

## What's Already Done (Pre-Refactor Improvements)

These improvements were completed before this baseline was established:

- **Hook extraction:** App.tsx reduced from 1,769 → 391 lines (6 hooks extracted)
- **Column sorting** on all sports tables
- **Kalshi API deep audit** — status filter, pagination, field mapping corrections
- **Smart relay caching** infrastructure (built, disabled by default)
- **Polymarket hydration** fixes
- **Relay crash protection** — unhandled async error handling
- **Response cache** for GET requests (TTL-based)
- **Staging deploy pipeline** — `dev.g1.newbx.com` via tar+ssh

---

## Architectural Strengths

1. **Clean orchestrator pattern** — App.tsx is pure composition, no business logic
2. **Atomic design hierarchy** — consistent component organization (atoms → molecules → organisms → pages)
3. **Transport-only relay** — private keys never leave the browser
4. **Type safety** — shared types enforce contract across monorepo boundary
5. **Hook isolation** — each hook owns one domain of concern (connection, orders, positions, streams, preferences, Polymarket)

---

## Known Areas for Future Work

1. **Component count (188)** — many organisms appear scaffolded but unused; consolidation opportunity
2. **Single JS bundle (~2.9MB)** — no code splitting; route-based lazy loading would help
3. **Root-level legacy components (10)** — not yet migrated into atomic structure
4. **Smart relay disabled** — built but not active in production
5. **Barrel files (11)** — some may not justify their existence per project conventions (5+ import threshold)
6. **Hook sizes** — `useStreamManagement` (405 lines) and `useOrderManagement` (362 lines) are candidates for further decomposition
