Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions apps/frontend/app/escrow/[id]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { useParams } from "next/navigation";
import Link from "next/link";
import { useEscrow } from "@/hooks/useEscrow";
import { useWallet } from "@/hooks/useWallet";
import { useEscrowEvents } from "@/hooks/useEscrowEvents";
import EscrowHeader from "@/components/escrow/detail/EscrowHeader";
import PartiesSection from "@/components/escrow/detail/PartiesSection";
import TermsSection from "@/components/escrow/detail/TermsSection";
Expand All @@ -28,6 +29,37 @@ const EscrowDetailPage = () => {
const [disputeOpen, setDisputeOpen] = useState(false);
const [resolutionOpen, setResolutionOpen] = useState(false);
const [dispute, setDispute] = useState<any>(null);
const { status: escrowSocketStatus, onEscrowEvent } = useEscrowEvents(id as string);

useEffect(() => {
const cleanupFunctions: Array<() => void> = [];

cleanupFunctions.push(
onEscrowEvent('escrow:status_changed', () => refetch()),
);
cleanupFunctions.push(
onEscrowEvent('escrow:funded', () => refetch()),
);
cleanupFunctions.push(
onEscrowEvent('escrow:completed', () => refetch()),
);
cleanupFunctions.push(
onEscrowEvent('escrow:dispute_filed', () => refetch()),
);
cleanupFunctions.push(
onEscrowEvent('escrow:dispute_resolved', () => refetch()),
);

return () => {
cleanupFunctions.forEach((cleanup) => cleanup());
};
}, [id, onEscrowEvent, refetch]);

useEffect(() => {
if (escrowSocketStatus === 'connected') {
refetch();
}
}, [escrowSocketStatus, refetch]);

useEffect(() => {
if (escrow && publicKey) {
Expand Down
4 changes: 4 additions & 0 deletions apps/frontend/components/Providers.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import React, { useState } from 'react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { ToastProvider } from '@/app/contexts/ToastProvider';
import { ThemeProvider } from '@/components/ThemeProvider';
import { WebSocketProvider } from '@/providers/WebSocketProvider';
import { ErrorBoundary } from '@/components/ErrorBoundary';

export default function Providers({ children }: { children: React.ReactNode }) {
Expand All @@ -20,6 +21,9 @@ export default function Providers({ children }: { children: React.ReactNode }) {
<QueryClientProvider client={queryClient}>
<ThemeProvider>
<ToastProvider>
<WebSocketProvider>
{children}
</WebSocketProvider>
<ErrorBoundary>
{children}
</ErrorBoundary>
Expand Down
42 changes: 38 additions & 4 deletions apps/frontend/components/common/NotificationBell.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ interface NotificationBellProps {

const NotificationBell: React.FC<NotificationBellProps> = ({ className = '' }) => {
const [isOpen, setIsOpen] = useState(false);
const { notifications, unreadCount, isLoading, markAsRead, markAllAsRead } = useNotifications();
const { notifications, unreadCount, isLoading, connectionStatus, markAsRead, markAllAsRead } = useNotifications();

// Group notifications by date
const groupedNotifications = notifications.reduce((acc, notification) => {
Expand Down Expand Up @@ -99,8 +99,24 @@ const NotificationBell: React.FC<NotificationBellProps> = ({ className = '' }) =
onClick={() => setIsOpen(!isOpen)}
className="relative p-2 text-gray-300 hover:text-white transition-colors"
aria-label="Notifications"
title={
connectionStatus === 'connected'
? 'Realtime updates active'
: connectionStatus === 'reconnecting'
? 'Realtime reconnecting'
: 'Realtime disconnected'
}
>
<Bell className="w-6 h-6" />
<span
className={`absolute -top-1 -right-1 h-3 w-3 rounded-full border border-black transition-colors ${
connectionStatus === 'connected'
? 'bg-emerald-400'
: connectionStatus === 'reconnecting'
? 'bg-amber-400'
: 'bg-red-500'
}`}
/>
{unreadCount > 0 && (
<span className="absolute top-0 right-0 inline-flex items-center justify-center px-2 py-1 text-xs font-bold leading-none text-white transform translate-x-1/4 -translate-y-1/4 bg-red-500 rounded-full">
{unreadCount > 99 ? '99+' : unreadCount}
Expand All @@ -120,9 +136,27 @@ const NotificationBell: React.FC<NotificationBellProps> = ({ className = '' }) =
{/* Panel */}
<div className="absolute right-0 mt-2 w-96 max-w-[calc(100vw-2rem)] bg-gray-900 border border-gray-700 rounded-lg shadow-2xl z-50 overflow-hidden">
{/* Header */}
<div className="flex items-center justify-between px-4 py-3 border-b border-gray-700">
<h3 className="text-lg font-semibold text-white">Notifications</h3>
<div className="flex items-center gap-2">
<div className="flex flex-col gap-2 px-4 py-3 border-b border-gray-700">
<div className="flex items-center justify-between gap-3">
<h3 className="text-lg font-semibold text-white">Notifications</h3>
<div className="inline-flex items-center gap-2 rounded-full bg-slate-950/80 px-3 py-1 text-xs uppercase tracking-[0.18em] text-gray-400">
<span
className={`h-2.5 w-2.5 rounded-full ${
connectionStatus === 'connected'
? 'bg-emerald-400'
: connectionStatus === 'reconnecting'
? 'bg-amber-400'
: 'bg-red-500'
}`}
/>
{connectionStatus === 'connected'
? 'Live'
: connectionStatus === 'reconnecting'
? 'Reconnecting'
: 'Disconnected'}
</div>
</div>
<div className="flex items-center justify-between gap-2">
{unreadCount > 0 && (
<button
onClick={handleMarkAllAsRead}
Expand Down
51 changes: 51 additions & 0 deletions apps/frontend/hooks/useEscrowEvents.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { useCallback, useEffect } from 'react';
import { useWebSocket } from '@/providers/WebSocketProvider';
import { EscrowSocketEvent, WebSocketStatus } from '@/lib/websocket';

export interface UseEscrowEventsReturn {
status: WebSocketStatus;
joinEscrowRoom: (escrowId: string) => void;
leaveEscrowRoom: (escrowId: string) => void;
onEscrowEvent: (
event: EscrowSocketEvent,
handler: (payload: Record<string, unknown>) => void,
) => () => void;
}

export const useEscrowEvents = (escrowId: string | null): UseEscrowEventsReturn => {
const {
status,
joinEscrowRoom,
leaveEscrowRoom,
onEscrowEvent: rawOnEscrowEvent,
offEscrowEvent,
} = useWebSocket();

useEffect(() => {
if (!escrowId) {
return;
}

joinEscrowRoom(escrowId);
return () => {
leaveEscrowRoom(escrowId);
};
}, [escrowId, joinEscrowRoom, leaveEscrowRoom]);

const onEscrowEvent = useCallback(
(event: EscrowSocketEvent, handler: (payload: Record<string, unknown>) => void) => {
rawOnEscrowEvent(event, handler);
return () => {
offEscrowEvent(event, handler);
};
},
[offEscrowEvent, rawOnEscrowEvent],
);

return {
status,
joinEscrowRoom,
leaveEscrowRoom,
onEscrowEvent,
};
};
42 changes: 37 additions & 5 deletions apps/frontend/hooks/useNotifications.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import { useState, useEffect, useCallback } from 'react';
import { useState, useEffect, useCallback, useRef } from 'react';
import { notificationService } from '@/services/notification';
import { Notification } from '@/types/notification';
import { useWebSocket } from '@/providers/WebSocketProvider';

interface UseNotificationsReturn {
notifications: Notification[];
unreadCount: number;
isLoading: boolean;
error: Error | null;
connectionStatus: 'connected' | 'reconnecting' | 'disconnected' | 'error';
markAsRead: (notificationId?: string) => Promise<void>;
markAllAsRead: () => Promise<void>;
refetch: () => Promise<void>;
Expand All @@ -17,6 +19,12 @@ export const useNotifications = (): UseNotificationsReturn => {
const [unreadCount, setUnreadCount] = useState<number>(0);
const [isLoading, setIsLoading] = useState<boolean>(true);
const [error, setError] = useState<Error | null>(null);
const notificationsRef = useRef<Notification[]>([]);
const { onNotification, offNotification, status: connectionStatus } = useWebSocket();

useEffect(() => {
notificationsRef.current = notifications;
}, [notifications]);

const fetchNotifications = useCallback(async () => {
try {
Expand Down Expand Up @@ -56,17 +64,41 @@ export const useNotifications = (): UseNotificationsReturn => {
useEffect(() => {
fetchNotifications();

// Poll for new notifications every 10 seconds
const interval = setInterval(fetchNotifications, 10000);
const handleNotification = (payload: Notification) => {
setNotifications((current) => {
const exists = current.some((notification) => notification.id === payload.id);
if (exists) {
return current.map((notification) =>
notification.id === payload.id ? payload : notification,
);
}
return [payload, ...current];
});

setUnreadCount((current) => {
const alreadyExists = notificationsRef.current.some(
(notification) => notification.id === payload.id,
);
if (alreadyExists) {
return current;
}
return current + (payload.readAt ? 0 : 1);
});
};

onNotification(handleNotification);

return () => clearInterval(interval);
}, [fetchNotifications]);
return () => {
offNotification(handleNotification);
};
}, [fetchNotifications, onNotification, offNotification]);

return {
notifications,
unreadCount,
isLoading,
error,
connectionStatus,
markAsRead,
markAllAsRead,
refetch: fetchNotifications,
Expand Down
52 changes: 52 additions & 0 deletions apps/frontend/lib/websocket.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { io, Socket } from 'socket.io-client';

export type EscrowSocketEvent =
| 'escrow:status_changed'
| 'escrow:funded'
| 'escrow:completed'
| 'escrow:milestone_released'
| 'escrow:condition_fulfilled'
| 'escrow:condition_confirmed'
| 'escrow:dispute_filed'
| 'escrow:dispute_resolved'
| 'escrow:party_joined'
| 'escrow:cancelled';

export type NotificationSocketEvent = 'notification:new';

export type SocketEvent = EscrowSocketEvent | NotificationSocketEvent;

export type WebSocketStatus = 'connected' | 'reconnecting' | 'disconnected' | 'error';

export interface WebSocketEventPayload {
[key: string]: unknown;
}

const AUTH_TOKEN_KEY = 'authToken';
const DEFAULT_API_URL = 'http://localhost:3000';
const ESCROW_NAMESPACE = '/escrow';

export const getWebSocketUrl = (): string => {
const baseUrl = process.env.NEXT_PUBLIC_API_URL || DEFAULT_API_URL;
return `${baseUrl.replace(/\/$/, '')}${ESCROW_NAMESPACE}`;
};

export const createEscrowWebSocket = (token: string): Socket => {
return io(getWebSocketUrl(), {
auth: { token },
path: '/socket.io',
transports: ['websocket'],
autoConnect: false,
reconnection: true,
reconnectionAttempts: Infinity,
reconnectionDelay: 1000,
reconnectionDelayMax: 10000,
});
};

export const getStoredAuthToken = (): string | null => {
if (typeof window === 'undefined') {
return null;
}
return window.localStorage.getItem(AUTH_TOKEN_KEY);
};
1 change: 1 addition & 0 deletions apps/frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
"react": "19.1.0",
"react-dom": "19.1.0",
"react-hook-form": "^7.71.1",
"socket.io-client": "^4.7.2",
"stellar-sdk": "^13.3.0",
"tailwind-merge": "^3.4.0",
"zod": "^4.3.6"
Expand Down
Loading