> For the complete documentation index, see [llms.txt](https://suigar.gitbook.io/suigar-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://suigar.gitbook.io/suigar-docs/end-to-end-ai-map/frontend.md).

# Frontend

> Reference sheet for Codex to work effectively inside the Vite + React client. Update whenever you change tooling or project conventions.

## TL;DR

* Web Sui gaming hub: dashboards for Coinflip, Dice, Plinko, Limbo, Lootbox, quests, VIP, referrals, and chat.
* `pnpm run dev` (Vite on port 5173 with `--host`) backed by `APP_CFG.API_URL` and a Socket.IO connection pointing at the Nest API origin.
* Primary data comes from REST endpoints under `/api/*`, websocket events over `chat:message:new`/`chat:message:update`/`chat:message:delete` plus `chat:reaction:add`/`chat:reaction:remove`, and on-chain state via Mysten Sui SDK.

## Tech Stack Snapshot

* Vite 8.0.13 + React 19.2.6 + TypeScript 5.9.3 with `@vitejs/plugin-react` 6.0.2. Production builds now run on Rolldown/Oxc via `build.rolldownOptions` and Oxc minification.
* TanStack Router 1.170.2 / Query 5.100.10 / Form 1.32.0 / Virtual 3.13.24 drive routing, server-state, forms, and virtualized views; Zustand 5.0.13 handles client state.
* Tailwind CSS 4.3.0 with CSS variables, `tailwind-merge` 3.6.0, `tw-animate-css` 1.4.0, sonner 2.0.7 toasts, and shadcn/ui primitives with lucide-react 1.16.0 icons.
* Mysten Dapp Kit Core 1.3.2 / Dapp Kit React 2.0.3 with `@mysten/sui` 2.16.3, `@mysten/enoki` 1.0.8, and `@mysten/wallet-standard` 0.20.3 power zkLogin-aware wallet flows; `@pythnetwork/hermes-client` 3.1.0 supplies price feeds.
* GSAP 3.15.0 and motion 12.38.0 handle animation. Asset/build tooling includes `vite-imagetools` 10.0.0, the local shared-env watch plugin, Sui request mirror dev plugin, and custom Rolldown chunk groups for heavy wallet, motion, MUI, lottie, and Suifrens vendor bundles.

## Project Layout

* Entry: `src/main.tsx` wires React root, providers (`HelmetProvider`, `QueryClientProvider`, `SuiClientProvider`, `WalletProvider`, theme, auth, tooltip, AnimatePresence) and mounts TanStack Router.
* Routing: filesystem routes under `src/routes`, generated types in `src/routeTree.gen.ts` via `tanstack-router generate` (see `package.json` script).
* Major directories: `components/` (UI primitives, modals, shadcn under `components/ui`), `contexts/`, `hooks/` (page-specific hooks + auth/wallet helpers), `stores/` (Zustand state), `services/` & `repositories`/`configs/` etc.
* Socket bootstrap in `src/lib/socket.ts` includes the current JWT in the handshake, reconnects when silent auth state changes, enables credentials for Traefik affinity, and attaches listeners as soon as modules load to keep unread counters in sync.

## Styling & Design System

* Tailwind config (`tailwind.config.js`) customizes breakpoints (`xs`, `max-*` variants), container padding, and extensive CSS variable driven palette. Animation utilities come from `tw-animate-css`.
* Global styles live in `src/css/global.css` (imports Tailwind, defines theme tokens, typography, shadows) with additional partials in `src/css/animations.css`.
* shadcn setup controlled by `components.json` with aliases (`@/components`, `@/components/ui`, `@/lib`, etc.); new components are added via `pnpm dlx shadcn@latest add <component>` or equivalent and should land in `src/components/ui`.
* Theme switching powered by `ThemeProvider` (`src/components/theme-provider.tsx`) and tokens consumed through CSS variables.

## State, Data & APIs

* Data fetching via TanStack Query; queries typically originate inside hooks under `src/hooks` or services under `src/services`/`src/repositories` wrapping Axios.
* Global auth lives in `src/hooks/use-auth.tsx` and centralizes wallet connections, profile hydration, JWT management, and signature flows. Slot-specific helpers such as ensuring/disconnecting secondary wallets now live in `src/hooks/auth/hooks/useWalletSlots.ts` instead of the auth context.
* Wallet connectivity runs through Mysten Dapp Kit providers with Enoki zkLogin helpers (`src/use-sui-zk-login`) and Coinbase CDP helpers (`use-coinbase-cdp-token.ts`).
* Realtime chat uses Socket.IO client pointed at `new URL(APP_CFG.API_URL).origin`; authenticated reconnects keep backend per-wallet admission state accurate while unread tracking stays in the store.
* `questRepository.checkQuestStatus` returns enriched metadata: `{ claimable, managedExternally, state, period }`. Quest UI (`GameQuests`) consumes these flags to disable partner-managed rewards, show "upcoming"/"expired" banners, and only offer claim actions during an active window.

## Commands & Tooling

* Scripts (`package.json`): `pnpm run dev`, `pnpm run build` (type check + bundle), `pnpm run lint`, `pnpm run format`, `pnpm run preview`, `pnpm run generate` (TanStack router codegen).
* Vite config (`vite.config.ts`) injects shared envs, auto-watches the development shared env files (`.env.local.shared` preferred, `.env.shared` legacy fallback) via `vite/env-plugin.ts`, aliases `@` to `src`, and enables compression + imagetools plugins.
* Tailwind/Prettier integration via `prettier-plugin-tailwindcss`; ESLint configured for React + hooks with TypeScript.
* Package manager is pnpm from the repo root, with shared versions managed through `pnpm-workspace.yaml` catalogs. Run `pnpm run check:toolchain` after changing Node, pnpm, CI setup, or shared action metadata.
* Bundle size tracking uses `node scripts/check-bundle-budget.mjs --report-only` in frontend CI to publish a non-blocking summary. `pnpm run check:bundle-budget` stays strict and should be used when ratcheting size budgets or validating performance cleanup.

## Testing & QA

* Vitest covers frontend units/integration behavior and Playwright covers browser flows. Use targeted specs while iterating, then `pnpm test`, `pnpm typecheck`, and a production build for cross-cutting runtime changes.
* Linting enforced via `pnpm run lint`; formatting via `pnpm run format`.
* Accessibility/visual regression testing not automated; rely on design QA checklists.

## React Doctor Cleanup Playbook

Retrospective from the May 2026 warning cleanup pass:

* Start with a fresh `pnpm exec react-doctor --json --no-score --blocking warning` snapshot and keep the exact warning list visible. Re-run after each isolated fix; do not wait until several large refactors have accumulated.
* For `no-giant-component`, inspect top-level declarations first with `rg -n "^(export )?(function|const|type|interface)|^function [A-Z]"`. If the file already contains helper components, plan the extraction before wrapping the giant component. A simple wrapper can clear `no-giant-component` but expose `no-multi-comp`.
* Prefer this split order for large pages: move small reusable helper components to one-component-per-file modules, move shared formatters/types into plain `.ts` helpers, then turn the exported route/component into a small composition wrapper or a small hook caller.
* For highly visual game surfaces such as Candy Rush, preserve the existing DOM and classes while extracting. Split into adjacent scene parts and a state hook, then verify screenshots before claiming success.
* Keep route files as orchestration/composition layers. Heavy state machines can live in `use*State` hooks; repeated visual shells should live in focused component files.
* In a dirty worktree, run `git status --short` before and after the slice and keep validation commands scoped to files touched by the cleanup. Do not format unrelated dirty files.
* Use the validation ladder for each meaningful slice: `tsc --noEmit`, targeted Prettier check, `react-doctor --json --no-score --blocking warning`, `git diff --check`, then rendered smoke.
* Try the in-app Browser path first for local frontend QA. If Browser screenshots or console logs are stale or capture the wrong surface, record that reason and fall back to a fresh Playwright context with screenshots saved under `/tmp`.
* Seed localStorage in smoke scripts to suppress welcome overlays, and stop the Vite dev server after QA. Keep screenshots outside the repo unless the user explicitly asks for committed artifacts.
* When user reports a blocking network call or timeout, investigate that first with the Network/console surface before continuing general warning cleanup. It may be a stale dev script, external RPC noise, or a real app blocker.

### Time-Efficient Cleanup Loop

Keep the same quality bar, but reduce elapsed time by working in narrower, pre-planned loops:

* Cap each React Doctor slice to one warning family or one file. Do not start the next warning until the current slice has passed `tsc`, Prettier, React Doctor, and diff checks.
* Before editing a giant component, spend a few minutes mapping declarations, imports, and JSX regions. A short extraction map is faster than discovering rule interactions after a large patch.
* Extract by copy-preserving JSX first, then improve names or types only where needed. Avoid visual or behavioral cleanup during architecture cleanup unless the warning requires it.
* For visual surfaces, create the Playwright smoke script once and reuse it after each relevant slice. Keep the route, viewport, localStorage seeds, screenshot paths, and interaction proof stable.
* Run long checks in parallel when they are independent: `tsc`, targeted Prettier, React Doctor, and `git diff --check` can usually run together after a slice.
* Use targeted Prettier checks for touched files and full-app checks only when the touched surface or user request justifies it.
* If a Browser run fails or returns stale screenshots/logs once, switch to Playwright for the rest of that QA pass instead of retrying repeatedly.
* Keep temporary QA scripts outside the repo and command-based. Do not spend time building committed test scaffolding unless the task asks for durable tests.
* Preserve a scratch note of current warning count, touched files, validation commands, screenshot paths, and known external noise. This prevents re-discovering the same context after interruptions.
* Treat unexpected runtime blockers as separate slices: fix or classify the blocker, rerun the smallest route smoke, then return to the warning backlog.

## Environment & Configuration

* `src/configs/index.ts` builds `APP_CFG` from `import.meta.env.VITE_*`. On module import it validates every key and throws if any VITE var is undefined.
* Vite env plugin loads `.env.shared` then `.env.local.shared` plus `frontend/.env` in development, and `.env.<network>.shared` + `frontend/.env.<network>` for production builds (via `--mode` or `VITE_NETWORK`); shared vars are auto-prefixed to `VITE_*`.
* Required vars cover API base URL, package IDs, contract object IDs, OAuth client IDs, ZK login prover, Moonpay/Coinbase keys, and coin type IDs per environment.
* Feature toggles handled via env (e.g., SUI environment, coin types). No runtime config file beyond `APP_CFG`.

## Build & Deployment

* `pnpm run build` outputs to `frontend/dist`; includes PWA manifest/offline runtime via `vite-plugin-pwa` and static asset compression.
* Ensure backend `API_URL` env matches deployed Nest hostname; Socket.IO origin uses `.origin` of that URL.
* Deployment pipeline not codified here; artifacts are static files suitable for CDN/edge hosting.

## Debugging & Troubleshooting

* If startup throws "Missing environment variables" it comes from `validateAppConfig()`; double-check shared env files and Vite prefixing.
* Socket connection issues: confirm backend reachable and CORS/websocket ports align; inspect `src/lib/socket.ts` for origin logic.
* UI layout depends on Zustand chat/sidebar state. If views look offset, ensure stores initialized and `SideMenu` collapse state updated.
* Tailwind 4 content paths cover `src/**/*`; run `pnpm run lint` or `pnpm run build` after adding new component paths.

## Reference Links

* Backend REST + websocket definitions: see `docs/codex/backend.md` and Nest controllers under `backend/src/presentation`.
* Contract/event metadata: `backend/src/app/config/game-config.ts`, quest docs in `backend/docs/`.
* Design assets live in repo (e.g., `/communication`), with shadcn docs at <https://ui.shadcn.com/>.

## Open Questions

* Document shadcn component generation workflow (command wrappers, custom tokens) if it differs from default.
* Capture any automated test strategy once introduced (Vitest, Playwright, etc.).
