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(zerolocalStorageexposure). - Architect an Optimistic UI engine that updates interface state instantly on signature submission, with automatic rollback on
revert/droppedtransactions. - Build Encrypted Pre-Flight Validation (
euint32range checks,lockEscrowsolvency 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 (
<300KBgzipped) 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
| Task | Description | Audit Gate (P0) |
|---|---|---|
| 5.1 Session Key Abstraction | Implement 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 Engine | Build 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-Flight | Implement 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 Dashboard | Develop 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 & Performance | Write 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/CD | Configure ci-frontend.yml: lint → type-check → test:e2e → build. 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 Term | User-Facing Language | Visibility Rule |
|---|---|---|
FHE Encryption | Bid Protected | Always shown during ACTIVE |
CoFHE Processing | ️ Sealed Vault Active | Shduring RESOLVING |
AVS Verification | Verified by Network | Shduring FINALIZED |
Dynamic Timeout | ️ Auto-refund triggered | Shonly during VOIDED |
Ciphertext Hash | Encrypted & Confirmed | Never shows raw hex |
Frontend Execution Flow
️ Security & UX Guarantees
- XSS Attack Surface Elimination: By strictly prohibiting
localStorageand encrypting session permits via the Web Crypto API beforeIndexedDBpersistence, malicious scripts cannot harvest active signing keys. - 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 torevertafter user signature, protecting UX trust. - Progressive Data Isolation: The
ConfidenceDashboardenforces a strict read policy: no plaintext values, winner addresses, or ranking data are exposed until the contract explicitly transitions toFINALIZEDorVOIDED. This prevents UI-level timing attacks or information leakage. - 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
localStorageorcookieusage for cryptographic permits. Enforced via ESLintno-restricted-propertiesrule. - [] Optimistic UI auto-reverts within
500msof transaction rejection or network drop. - []
ConfidenceDashboarddisplays zero numeric bid values, plaintext hashes, or winner addresses prior toFINALIZEDstate. - [] Pre-flight validation rejects bids exceeding
euint32max (2^32 - 1) or unconfirmedescrowBalances. - [] E2E tests (
Playwright) pass100%on simulation environment covering success, revert, session expiry, and network drop paths. - [] Production bundle size
<300KBgzipped. Lighthouse scores meetPerformance > 90,Accessibility > 95,Best Practices > 100.
Timeline & Dependencies
| Metric | Value |
|---|---|
| Estimated Duration | 12–15 days |
| Team Size | 2–3 Engineers (Frontend/UX + TypeScript + Security) |
| Dependencies | Phase 1 (Proxy/ABI), Phase 2 (Escrow/Settlement), Phase 3 (AVS Events) |
| Enables | Phase 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 UIfinalization require Phase 3’sDecryptionRequestedandAuctionFinalizedevents to be stabilized.
Next Steps
- Proceed to 4.6. Phase 6: Testnet Deployment & Audit to implement testnet deployment, KPI monitoring, chaos engineering, and external audit packaging.
- Review Technical Components → BidForm.tsx for encrypted submission UI patterns and gas estimation logic.
- Explore Security Model → Session Key Isolation for detailed Web Crypto API implementation and XSS mitigation strategies.