4. Execution RoadmapPhase 5: Frontend & UX 2.0

4.5. Phase 5: Frontend & UX 2.0

Phase 5 bridges the cryptographic complexity of FHE/CoFHE and EigenLayer AVS with a mainstream, frictionless user experience. By integrating ERC-4337 Account Abstraction, Optimistic UI state management, and progressive disclosure principles, the protocol delivers a 1-Click Trade workflow that mirrors Web2 responsiveness while preserving Web3-grade security and mathematical privacy.

This phase ensures that users never interact directly with raw ciphertexts, manage volatile signing prompts, or are exposed to vulnerable browser storage patterns. All technical jargon is abstracted into confidence-driven metrics, and transaction flows are hardened against network drops, gas estimation errors, and session expiry.

Phase Objective

  • Implement ERC-4337 Smart Accounts with 24-hour ephemeral session keys stored exclusively in encrypted IndexedDB (zero localStorage exposure).
  • Architect an Optimistic UI engine that updates interface state instantly on signature submission, with automatic rollback on revert/dropped transactions.
  • Build Encrypted Pre-Flight Validation (euint32 range checks, lockEscrow solvency verification, dynamic gas estimation +20% buffer).
  • Develop a Confidence Dashboard that displays only safe metrics (bid count, time remaining, encryption status) and replaces technical terms with user-facing language.
  • Execute comprehensive Playwright E2E tests and optimize bundle size (<300KB gzipped) with strict Lighthouse thresholds.

Target File Structure

packages/frontend/
├── next.config.js # Security headers, CSP, tree-shaking config
├── tailwind.config.ts # Design system tokens
├── tsconfig.json # Strict TypeScript mode
├── .env.example # NEXT_PUBLIC_FHENIX_RPC, NEXT_PUBLIC_CONTRACT_ADDRESS

├── src/
│ ├── app/
│ │ ├── layout.tsx # Wagmi/Viem/Theme providers
│ │ ├── auction/[id]/
│ │ │ ├── page.tsx # Auction detail + bid routing
│ │ │ └── components/
│ │ │ ├── BidForm.tsx # Encrypted bid submission UI
│ │ │ ├── ConfidenceDashboard.tsx # Non-revealing status metrics
│ │ │ ├── AuctionTimer.tsx # Precision countdown
│ │ │ └── SettlementStatus.tsx # RESOLVING → FINALIZED tracker
│ │ └── api/
│ │ └── keeper/route.ts # Webhook endpoint for Gelato/Chainlink
│ │
│ ├── lib/
│ │ ├── cofhe/
│ │ │ ├── client.ts # @cofhe/sdk initialization
│ │ │ ├── encryption.ts # Bid encryption + range validation
│ │ │ └── avd-proof.ts # AVS signature parsing
│ │ ├── hooks/
│ │ │ ├── useERC4337Session.ts # Smart account + ephemeral key management
│ │ │ ├── useOptimisticUI.ts # Instant UI state + auto-rollback
│ │ │ └── useAuctionState.ts # WebSocket event subscription
│ │ └── utils/
│ │ ├── validation.ts # Pre-flight solvency & type checks
│ │ └── format.ts # Time/progress formatting
│ │
│ └── components/
│ ├── wallet/
│ │ └── SessionKeyManager.tsx # Session TTL UI + renewal prompt
│ └── ui/ # shadcn/radix primitives

└── tests/
 ├── e2e/
 │ ├── auction-flow.spec.ts # Full lifecycle E2E
 │ └── encryption-flow.spec.ts # SDK integration & error paths
 └── unit/
 ├── BidForm.test.tsx # React component tests
 └── usePlaceBid.test.ts # Hook logic validation

️ Execution Tasks & Audit Gates

TaskDescriptionAudit Gate (P0)
5.1 Session Key AbstractionImplement useERC4337Session.ts using permissionless SDK. Generate 24h TTL permits scoped to placeBid, lockEscrow, claimRefund. Store in encrypted IndexedDB.Zero localStorage/cookie usage. Keys auto-expire. Fallback prompts on expiry.
5.2 Optimistic UI EngineBuild useOptimisticUI.ts. Update state on tx submitted (<500ms). Monitor waitForTransactionReceipt. Auto-rollback on failure. Persist state via Zustand.UI updates instantly. 100% rollback on revert/dropped. No stale state post-reload.
5.3 Encryption & Pre-FlightImplement encryptBid with @cofhe/sdk. Validate bidAmount < 2**32. Check lockEscrow >= bidAmount via viem.readContract. Dynamic gas estimation * 1.2.Local rejection for out-of-range or insolvent bids. Gas accuracy ±15%. Zero plaintext in console.
5.4 Confidence DashboardDevelop ConfidenceDashboard.tsx. Show only: activeBidsCount, timeRemaining, encryptionStatus. Replace FHE/AVS with progressive disclosure terms.Zero numeric bid values or winner addresses shown pre-FINALIZED. Live WebSocket sync (<2s latency).
5.5 E2E & PerformanceWrite Playwright suites covering full flow + failure paths. Optimize bundle via dynamic imports & tree-shaking. Run Lighthouse audits.E2E pass rate 100%. Gzipped bundle <300KB. Lighthouse: Perf>90, A11y>95, Best>100.
5.6 Frontend CI/CDConfigure ci-frontend.yml: linttype-checktest:e2ebuild. Env var segregation per network. Preview deployments per PR. Add CSP/Security Headers.CI blocks merge on any failure. Previews auto-generate. Zero-downtime production deploy.

Technical Implementation

1. ERC-4337 Session Key Management (useERC4337Session.ts)

Eliminates repetitive wallet prompts while strictly isolating signing permits from browser XSS vectors.

// packages/frontend/src/lib/hooks/useERC4337Session.ts
import { createSmartAccountClient } from 'permissionless';
import { encryptWithWebCrypto, storeInIndexedDB } from '@lib/crypto';
 
export function useERC4337Session() {
 const [session, setSession] = useState<SessionPermit | null>(null);
 
 const createSession = async () => {
 const smartAccount = await createSmartAccountClient({ /* config */ });
 const permit = await smartAccount.createSessionKey({
 ttl: 24 * 60 * 60, // 24h
 scope: ['placeBid', 'lockEscrow', 'claimRefund'],
 });
 
 // STRICT: Encrypted IndexedDB only. No localStorage.
 const encrypted = await encryptWithWebCrypto(permit);
 await storeInIndexedDB('ffm_session', encrypted);
 setSession(permit);
 };
 
 return { session, createSession, renewSession, isSessionActive };
}

2. Optimistic UI & Auto-Rollback (useOptimisticUI.ts)

Provides Web2-like responsiveness while guaranteeing cryptographic finality.

// packages/frontend/src/lib/hooks/useOptimisticUI.ts
import { useWaitForTransactionReceipt } from 'wagmi';
 
export function useOptimisticUI(txHash?: string) {
 const { status, isPending, isError } = useWaitForTransactionReceipt({ hash: txHash });
 
 const rollback = useCallback(() => {
 // Revert UI state, clear optimistic cache, notify user
 useAuctionStore.getState().resetOptimisticState();
 }, []);
 
 useEffect(() => {
 if (status === 'reverted' || status === 'dropped' || isError) {
 rollback();
 }
 }, [status, isError, rollback]);
 
 return { isOptimistic: !!txHash && status === 'pending', rollback };
}

3. Progressive Disclosure & Confidence Mapping

Technical complexity is translated into trust-building, non-leaking UI metrics.

Technical TermUser-Facing LanguageVisibility Rule
FHE EncryptionBid ProtectedAlways shown during ACTIVE
CoFHE Processing️ Sealed Vault ActiveShduring RESOLVING
AVS VerificationVerified by NetworkShduring FINALIZED
Dynamic Timeout️ Auto-refund triggeredShonly during VOIDED
Ciphertext HashEncrypted & ConfirmedNever shows raw hex

Frontend Execution Flow

️ Security & UX Guarantees

  1. XSS Attack Surface Elimination: By strictly prohibiting localStorage and encrypting session permits via the Web Crypto API before IndexedDB persistence, malicious scripts cannot harvest active signing keys.
  2. Gas Optimization & Failure Prevention: Dynamic gas estimation with a 20% safety margin (estimated * 1.2) combined with pre-flight solvency checks ensures transactions are highly unlikely to revert after user signature, protecting UX trust.
  3. Progressive Data Isolation: The ConfidenceDashboard enforces a strict read policy: no plaintext values, winner addresses, or ranking data are exposed until the contract explicitly transitions to FINALIZED or VOIDED. This prevents UI-level timing attacks or information leakage.
  4. Resilient Session Lifecycle: The 24-hour TTL aligns with typical auction windows. If a session expires mid-bid, the UI gracefully falls back to standard wallet signing without losing form state or draft inputs.

Phase 5 Audit Gate (P0 Checklist)

Progression to Phase 6 is strictly blocked until all P0 criteria are verified and merged:

  • [] Zero localStorage or cookie usage for cryptographic permits. Enforced via ESLint no-restricted-properties rule.
  • [] Optimistic UI auto-reverts within 500ms of transaction rejection or network drop.
  • [] ConfidenceDashboard displays zero numeric bid values, plaintext hashes, or winner addresses prior to FINALIZED state.
  • [] Pre-flight validation rejects bids exceeding euint32 max (2^32 - 1) or unconfirmed escrowBalances.
  • [] E2E tests (Playwright) pass 100% on simulation environment covering success, revert, session expiry, and network drop paths.
  • [] Production bundle size &lt;300KB gzipped. Lighthouse scores meet Performance > 90, Accessibility > 95, Best Practices > 100.

Timeline & Dependencies

MetricValue
Estimated Duration12–15 days
Team Size2–3 Engineers (Frontend/UX + TypeScript + Security)
DependenciesPhase 1 (Proxy/ABI), Phase 2 (Escrow/Settlement), Phase 3 (AVS Events)
EnablesPhase 6 (Testnet Deployment, User Onboarding, Load Testing)

Parallel Development Note: Frontend scaffolding can begin using mock ABIs from Phase 1, but real-time event subscriptions and Optimistic UI finalization require Phase 3’s DecryptionRequested and AuctionFinalized events to be stabilized.


Next Steps