# CLXEND — Production Handoff Handbook

> This MVP simulates blockchain, biometrics, AML, and on/off-ramp.
> This handbook maps each simulated component to its real implementation owner.

## Mock → Real implementation matrix

| Area | Current (MVP) | Real implementation | Owner | Est. effort |
|---|---|---|---|---|
| Face match (KYC) | Browser blink detection + AI Vision (Gemini 2.5 Flash) | FastAPI service running DeepFace / InsightFace + PAD (passive liveness) | AI / Identity Lead | 4–6 wks |
| Face match (login) | Same Vision compare against stored KYC selfie | Same FastAPI service + 1:N search index (FAISS) | AI / Identity Lead | 2 wks |
| DID | `SHA-256(face_hash + user_id)` stored in `dids` table | `did:ethr` registered on Sepolia → mainnet via `DIDRegistry.sol` | Blockchain Architect | 3 wks |
| KYC OCR | None — operator copies name/DOB | AWS Rekognition Identity / Google Vision Document AI | AI / Identity Lead | 2 wks |
| Blockchain settlement | Random tx_hash, no on-chain calls | `Remittance.sol` (USDC), ethers.js v6 + Alchemy/Infura, EIP-1559 gas | Blockchain Architect | 6–8 wks |
| Multi-chain bridge | `chain` field is metadata only | Chainlink CCIP or LayerZero V2 | Blockchain Architect | 6 wks |
| Wallet connect | None | WalletConnect v2 + MetaMask SDK (web) / WalletConnect mobile | Full-Stack Engineer | 2 wks |
| Tx monitoring | Status pinned at insert | Alchemy Notify webhooks → `/api/public/webhooks/alchemy` | DevOps | 1 wk |
| Fraud scoring | Heuristic in `fraud.server.ts` | ComplyAdvantage AML API + custom ML on `transactions` history | Governance / AI | 4 wks |
| Travel Rule | `compliance_events` table logs FATF fields | Notabene / Sumsub Travel Rule API + VASP directory | Governance | 4 wks |
| On/off ramp | Mock fiat balances in `wallets` | MoonPay / Ramp on-ramp + Bridge.xyz off-ramp | Full-Stack Engineer | 4 wks |
| Notifications | sonner toasts | OneSignal + SES email + Twilio SMS | Full-Stack Engineer | 1 wk |
| Rate limiting | `rate_limits` table (10 req/min) | Cloudflare WAF / AWS API Gateway | DevOps | 1 wk |
| Audit immutability | SHA-256 hash chain in Postgres | Anchor head hash hourly to L1 (Polygon checkpoint) | Governance / Blockchain | 2 wks |

---

## 1. For AI / Identity Lead

**Current state**
- `src/routes/_authenticated/kyc.tsx` — browser-based liveness (frame-diff blink detection, ≥2 in 5s).
- `src/lib/face-vision.server.ts` — calls AI Gateway (`google/gemini-2.5-flash`) to compare selfie ↔ ID doc.
- `src/lib/kyc.functions.ts` — auto-approves on similarity ≥ 85%.
- DID minted as `did:clxend:sha256:...` and stored in `dids` table with a mock `tx_hash`.

**What to replace**
1. **Stand up a Python FastAPI microservice** with endpoints:
   - `POST /face/embed` → 512-d embedding via InsightFace ArcFace
   - `POST /face/compare` → cosine similarity between two embeddings
   - `POST /face/liveness` → real PAD (texture + depth via Silent-Face-Anti-Spoofing)
   - `POST /id/ocr` → AWS Rekognition Identity (MRZ + barcode + face crop)
2. **Replace `face-vision.server.ts`** with a fetch wrapper to the FastAPI service.
3. **Replace mock DID** with `did:ethr` registration via `DIDRegistry.sol`. Store the resolved DID Document URL in `profiles.did`.
4. **Add periodic re-verification** (DIDs already have an `expires_at` column — wire a cron to re-prompt users at expiry).

---

## 2. For Blockchain Architect

**Current state**
- `transactions.tx_hash` is `0x` + 64 random hex chars; no on-chain call.
- `chain` column accepts `ethereum | polygon | bsc | off-chain` but is metadata only.
- Gas estimate is `0.0008 + Math.random() * 0.0012` ETH.

**Contracts to write**
- `Remittance.sol` — escrow-style transfer with sender/recipient/amount/memo, emits `RemittanceSent(bytes32 indexed id, address sender, address recipient, uint256 amount)`.
- `DIDRegistry.sol` — `did:ethr` compatible, or use ethr-did-registry on Sepolia.
- `MerchantRegistry.sol` — when merchant features are built.

**Integration points**
1. `src/lib/transfer.functions.ts:sendTransfer` — replace the random `tx_hash` block with `ethers.Contract.sendRemittance(...)` and persist the real tx hash + block number.
2. Add `chain_id` column to `transactions`.
3. Webhook handler at `app/routes/api/public/webhooks/alchemy.ts` to update `status` from `PENDING` → `CONFIRMED` on block inclusion.
4. **Multi-chain**: wire Chainlink CCIP for USDC transfers across Ethereum ↔ Polygon ↔ BSC. Replace the `chain` enum with a routing table.
5. **Wallet connect**: integrate `@walletconnect/web3-provider` so users can sign tx in their own wallet instead of the platform custodial wallet.

---

## 3. For Full-Stack Engineer (Web + Mobile)

**Web — current state**
- Wallet balances are stored in `wallets.balance` and edited server-side.
- Transactions debited at insert (or at staff approval for flagged).

**Web — what to change**
- Read on-chain balances directly via `ethers.providers.JsonRpcProvider(ALCHEMY_URL).getBalance(address)` and the ERC-20 `balanceOf` for USDC/USDT.
- `wallets` table becomes a cache, refreshed via webhook.

**Mobile (React Native) — handoff package**
- Use **Expo + Supabase JS** (same project URL, same publishable key — set via env).
- Auth: `supabase.auth.signInWithOtp({ email })` exactly like web's face-login fallback. For face login, port `src/routes/auth.tsx:faceLogin` to call the same server fn via raw HTTPS POST to `/_serverFn/faceLogin`.
- Data fetching: prefer direct Supabase queries with RLS (avoids one network hop). Use server fns only for the writes listed in `/api-docs` (sendTransfer, submitKyc, admin actions).
- Camera: `expo-camera` for KYC selfie + ID capture; upload via `supabase.storage.from('kyc-documents').upload(...)`.
- Reuse `openapi.yaml` to generate a typed client (e.g. `openapi-typescript`).

**Social lookup**
- Add Privy embedded wallets (or Auth0 + WalletConnect) so users can be discovered by phone/email and receive without a wallet address.

---

## 4. For DevOps

**Deployments**
1. **AI microservice** — AWS ECS Fargate or GCP Cloud Run, GPU-backed for InsightFace.
2. **RPC** — Alchemy (Ethereum, Polygon, Base) + QuickNode (BSC) with key rotation.
3. **CI/CD** — GitHub Actions:
   - `lint → typecheck → vitest → vite build → deploy preview`
   - Tag-based prod deploy.
4. **Monitoring** — Prometheus + Grafana + Loki for logs; Sentry for runtime errors (already partially wired via `lib/error-reporting.ts`).
5. **Secrets** — AWS Secrets Manager / GCP Secret Manager. Rotate Supabase service role key quarterly.

**Production rate limiting**
- Replace the Postgres-based `rate_limits` table with Cloudflare WAF + Bot Management or AWS API Gateway throttling. Keep the table for audit only.

---

## 5. For Governance

**Compliance tables already present**
- `compliance_events` — FATF Travel Rule (originator + beneficiary JSONB), GDPR events (export, deletion request), retention windows.
- `retention_policies` — per-country retention seeded for EU, GB, US, SG, AE, NG, KE, IN, BR, MX, GLOBAL.
- `audit_logs` — hash-chained, now with `country`, `user_agent`, `session_id`.

**Production gaps**
1. **Travel Rule** — wire Notabene or Sumsub; populate `originator` and `beneficiary` fields with the counterparty VASP info for transfers ≥ USD 1,000.
2. **Sanctions screening** — ComplyAdvantage / Refinitiv World-Check on every transfer; block before insert when hit.
3. **Suspicious Activity Reporting (SAR)** — auto-draft when fraud_score ≥ 90 or multiple high-risk corridors in 24h.
4. **Audit chain anchoring** — hourly head_hash to L1 (Polygon) for tamper-evidence beyond Postgres.
5. **SOC2-lite controls** — separation of duties (no admin can both submit and approve their own KYC), MFA mandatory for staff roles, quarterly access review.

---

## Demo credentials (preview environment only)

| Role | Email | Password |
|---|---|---|
| Admin | `admin@clxend.com` | `Admin123!` |
| Compliance | `compliance@clxend.com` | `Comp123!` |
| User (funded) | `alice@example.com` | `Demo123!` |
| User (recipient) | `bob@example.com` | `Demo123!` |

Use the **Demo Login** button on the landing page or sign in normally on `/auth`.
