diff --git a/apps/web/components/BridgeCompare.tsx b/apps/web/components/BridgeCompare.tsx new file mode 100644 index 0000000..510f298 --- /dev/null +++ b/apps/web/components/BridgeCompare.tsx @@ -0,0 +1,140 @@ +// packages/ui/src/components/BridgeCompare.tsx + +import React, { useState, useEffect } from 'react'; +import { useBridgeQuotes, BridgeQuoteParams } from '@bridgewise/react'; +import { RefreshIndicator } from './RefreshIndicator'; +import { QuoteCard } from './QuoteCard'; +import { SlippageWarning } from './SlippageWarning'; + +interface BridgeCompareProps { + initialParams: BridgeQuoteParams; + onQuoteSelect?: (quoteId: string) => void; + refreshInterval?: number; + autoRefresh?: boolean; +} + +export const BridgeCompare: React.FC = ({ + initialParams, + onQuoteSelect, + refreshInterval = 15000, + autoRefresh = true +}) => { + const [selectedQuoteId, setSelectedQuoteId] = useState(null); + const [showRefreshIndicator, setShowRefreshIndicator] = useState(false); + + const { + quotes, + isLoading, + error, + lastRefreshed, + isRefreshing, + refresh, + updateParams, + retryCount + } = useBridgeQuotes({ + initialParams, + intervalMs: refreshInterval, + autoRefresh, + onRefreshStart: () => setShowRefreshIndicator(true), + onRefreshEnd: () => { + setTimeout(() => setShowRefreshIndicator(false), 1000); + } + }); + + // Handle quote selection + const handleQuoteSelect = (quoteId: string) => { + setSelectedQuoteId(quoteId); + onQuoteSelect?.(quoteId); + }; + + // Format last refreshed time + const getLastRefreshedText = () => { + if (!lastRefreshed) return 'Never'; + + const seconds = Math.floor((Date.now() - lastRefreshed.getTime()) / 1000); + + if (seconds < 60) return `${seconds}s ago`; + if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`; + return lastRefreshed.toLocaleTimeString(); + }; + + return ( +
+ {/* Header with refresh controls */} +
+

Bridge Routes

+ +
+ + +
+ + Updated: {getLastRefreshedText()} + + {retryCount > 0 && ( + + Retry {retryCount}/{3} + + )} +
+
+
+ + {/* Error state */} + {error && ( +
+

Failed to fetch quotes: {error.message}

+ +
+ )} + + {/* Loading skeleton */} + {isLoading && quotes.length === 0 && ( +
+ {[1, 2, 3].map((i) => ( +
+ ))} +
+ )} + + {/* Quotes grid */} + {quotes.length > 0 && ( +
+ {quotes.map((quote) => ( + handleQuoteSelect(quote.id)} + isRefreshing={isRefreshing && showRefreshIndicator} + /> + ))} +
+ )} + + {/* Slippage warning for outdated quotes */} + {lastRefreshed && ( + + )} + + {/* Empty state */} + {!isLoading && quotes.length === 0 && !error && ( +
+

No bridge routes found for the selected parameters

+
+ )} +
+ ); +}; \ No newline at end of file diff --git a/apps/web/components/RefreshIndicator.tsx b/apps/web/components/RefreshIndicator.tsx new file mode 100644 index 0000000..1c6fcbb --- /dev/null +++ b/apps/web/components/RefreshIndicator.tsx @@ -0,0 +1,73 @@ +import React, { useEffect, useState } from 'react'; + +interface RefreshIndicatorProps { + isRefreshing: boolean; + lastRefreshed: Date | null; + onClick: () => void; + showAnimation?: boolean; +} + +export const RefreshIndicator: React.FC = ({ + isRefreshing, + lastRefreshed, + onClick, + showAnimation = false +}) => { + const [animate, setAnimate] = useState(false); + + useEffect(() => { + if (showAnimation) { + setAnimate(true); + const timer = setTimeout(() => setAnimate(false), 1000); + return () => clearTimeout(timer); + } + }, [showAnimation]); + + const getTimeSinceLastRefresh = () => { + if (!lastRefreshed) return 'Never'; + + const seconds = Math.floor((Date.now() - lastRefreshed.getTime()) / 1000); + + if (seconds < 60) return `${seconds}s`; + if (seconds < 3600) return `${Math.floor(seconds / 60)}m`; + return `${Math.floor(seconds / 3600)}h`; + }; + + return ( + + ); +}; \ No newline at end of file diff --git a/apps/web/components/ui-lib/TransactionHeartbeat.tsx b/apps/web/components/TransactionHeartbeat.tsx similarity index 97% rename from apps/web/components/ui-lib/TransactionHeartbeat.tsx rename to apps/web/components/TransactionHeartbeat.tsx index 2dcf806..11c76f4 100644 --- a/apps/web/components/ui-lib/TransactionHeartbeat.tsx +++ b/apps/web/components/TransactionHeartbeat.tsx @@ -1,6 +1,6 @@ import React from 'react'; -import { useTransactionPersistence } from './hooks/useTransactionPersistence'; +import { useTransactionPersistence } from './ui-lib/hooks/useTransactionPersistence'; export const TransactionHeartbeat = () => { const { state, clearState } = useTransactionPersistence(); diff --git a/apps/web/components/ui-lib/hooks/useBridgeQuotes.ts b/apps/web/components/ui-lib/hooks/useBridgeQuotes.ts new file mode 100644 index 0000000..3f40138 --- /dev/null +++ b/apps/web/components/ui-lib/hooks/useBridgeQuotes.ts @@ -0,0 +1,206 @@ +// packages/react/src/hooks/useBridgeQuotes.ts + +import { useState, useEffect, useCallback, useRef } from 'react'; +import { QuoteRefreshEngine } from '@bridgewise/core'; +import { NormalizedQuote, QuoteRefreshConfig, RefreshState } from '@bridgewise/core/types'; + +export interface UseBridgeQuotesOptions extends QuoteRefreshConfig { + initialParams?: BridgeQuoteParams; + debounceMs?: number; +} + +export interface BridgeQuoteParams { + amount: string; + sourceChain: string; + destinationChain: string; + sourceToken: string; + destinationToken: string; + userAddress?: string; + slippageTolerance?: number; +} + +export interface UseBridgeQuotesReturn { + quotes: NormalizedQuote[]; + isLoading: boolean; + error: Error | null; + lastRefreshed: Date | null; + isRefreshing: boolean; + refresh: () => Promise; + updateParams: (params: Partial) => void; + retryCount: number; +} + +export function useBridgeQuotes( + options: UseBridgeQuotesOptions = {} +): UseBridgeQuotesReturn { + const { + initialParams, + intervalMs = 15000, + autoRefresh = true, + maxRetries = 3, + retryDelayMs = 1000, + debounceMs = 300, + ...callbacks + } = options; + + const [params, setParams] = useState(initialParams); + const [quotes, setQuotes] = useState([]); + const [isLoading, setIsLoading] = useState(false); + const [error, setError] = useState(null); + const [lastRefreshed, setLastRefreshed] = useState(null); + const [isRefreshing, setIsRefreshing] = useState(false); + const [retryCount, setRetryCount] = useState(0); + + const engineRef = useRef(null); + const debounceTimerRef = useRef(); + const paramsRef = useRef(params); + + // Update params ref on change + useEffect(() => { + paramsRef.current = params; + }, [params]); + + // Initialize refresh engine + useEffect(() => { + const fetchQuotes = async (fetchParams: BridgeQuoteParams, options?: { signal?: AbortSignal }) => { + // Implement actual quote fetching logic here + const response = await fetch('/api/quotes', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(fetchParams), + signal: options?.signal + }); + + if (!response.ok) { + throw new Error('Failed to fetch quotes'); + } + + return response.json(); + }; + + engineRef.current = new QuoteRefreshEngine(fetchQuotes, { + intervalMs, + autoRefresh, + maxRetries, + retryDelayMs, + onRefresh: (newQuotes) => { + setQuotes(newQuotes); + setLastRefreshed(new Date()); + callbacks.onRefresh?.(newQuotes); + }, + onError: (err) => { + setError(err); + callbacks.onError?.(err); + }, + onRefreshStart: () => { + setIsRefreshing(true); + callbacks.onRefreshStart?.(); + }, + onRefreshEnd: () => { + setIsRefreshing(false); + callbacks.onRefreshEnd?.(); + } + }); + + // Listen to state changes + const handleStateChange = (state: RefreshState) => { + setRetryCount(state.retryCount); + setIsLoading(state.isRefreshing); + }; + + engineRef.current.on('state-change', handleStateChange); + + // Initialize with params if available + if (params) { + engineRef.current.initialize(params); + } + + return () => { + if (engineRef.current) { + engineRef.current.destroy(); + } + }; + }, []); // Empty dependency array - engine should only be created once + + // Handle parameter changes with debouncing + const updateParams = useCallback((newParams: Partial) => { + if (!paramsRef.current) return; + + const updatedParams = { ...paramsRef.current, ...newParams }; + + // Debounce parameter updates to avoid too many refreshes + if (debounceTimerRef.current) { + clearTimeout(debounceTimerRef.current); + } + + debounceTimerRef.current = setTimeout(() => { + setParams(updatedParams); + + if (engineRef.current) { + engineRef.current.refresh({ + type: 'parameter-change', + timestamp: Date.now(), + params: updatedParams + }).catch((err) => { + console.error('Failed to refresh quotes after parameter change:', err); + }); + } + }, debounceMs); + + }, [debounceMs]); + + // Manual refresh function + const refresh = useCallback(async (): Promise => { + if (!engineRef.current) { + throw new Error('Refresh engine not initialized'); + } + + try { + setIsLoading(true); + setError(null); + + const newQuotes = await engineRef.current.refresh({ + type: 'manual', + timestamp: Date.now() + }); + + return newQuotes; + } catch (err) { + setError(err as Error); + throw err; + } finally { + setIsLoading(false); + } + }, []); + + // Auto-refresh based on config changes + useEffect(() => { + if (engineRef.current) { + engineRef.current.updateConfig({ autoRefresh }); + + if (autoRefresh) { + engineRef.current.startAutoRefresh(); + } else { + engineRef.current.stopAutoRefresh(); + } + } + }, [autoRefresh]); + + // Update interval when changed + useEffect(() => { + if (engineRef.current) { + engineRef.current.updateConfig({ intervalMs }); + } + }, [intervalMs]); + + return { + quotes, + isLoading, + error, + lastRefreshed, + isRefreshing, + refresh, + updateParams, + retryCount + }; +} \ No newline at end of file diff --git a/apps/web/components/ui-lib/index.ts b/apps/web/components/ui-lib/index.ts index f1ef997..5aaf81b 100644 --- a/apps/web/components/ui-lib/index.ts +++ b/apps/web/components/ui-lib/index.ts @@ -1,2 +1,2 @@ -export * from './TransactionHeartbeat'; +export * from '../TransactionHeartbeat'; export * from './context/TransactionContext'; diff --git a/apps/web/services/QuoteRefreshEngine.ts b/apps/web/services/QuoteRefreshEngine.ts new file mode 100644 index 0000000..5b12dcf --- /dev/null +++ b/apps/web/services/QuoteRefreshEngine.ts @@ -0,0 +1,262 @@ +import { NormalizedQuote, QuoteRefreshConfig, RefreshState, RefreshTrigger } from '../types/quote.types'; +import { EventEmitter } from 'events'; + +export class QuoteRefreshEngine extends EventEmitter { + private refreshInterval: NodeJS.Timeout | null = null; + private config: Required; + private state: RefreshState = { + isRefreshing: false, + lastRefreshed: null, + error: null, + retryCount: 0, + quotes: [] + }; + + private abortController: AbortController | null = null; + private refreshQueue: Promise[] = []; + private lastParams: Record = {}; + + constructor( + private fetchQuotesFn: (params: any) => Promise, + config: QuoteRefreshConfig = {} + ) { + super(); + + // Default configuration + this.config = { + intervalMs: 15000, + autoRefresh: true, + maxRetries: 3, + retryDelayMs: 1000, + onRefresh: () => {}, + onError: () => {}, + onRefreshStart: () => {}, + onRefreshEnd: () => {}, + ...config + }; + } + + /** + * Initialize the refresh engine with parameters + */ + public initialize(params: Record): void { + this.lastParams = params; + + if (this.config.autoRefresh) { + this.startAutoRefresh(); + } + } + + /** + * Start auto-refresh interval + */ + public startAutoRefresh(): void { + if (this.refreshInterval) { + clearInterval(this.refreshInterval); + } + + this.refreshInterval = setInterval(() => { + this.refresh({ + type: 'interval', + timestamp: Date.now() + }); + }, this.config.intervalMs); + + // Trigger immediate first refresh + this.refresh({ + type: 'interval', + timestamp: Date.now() + }); + } + + /** + * Stop auto-refresh + */ + public stopAutoRefresh(): void { + if (this.refreshInterval) { + clearInterval(this.refreshInterval); + this.refreshInterval = null; + } + } + + /** + * Manual refresh trigger + */ + public async refresh(trigger: RefreshTrigger): Promise { + // Debounce: if already refreshing, queue this refresh + if (this.state.isRefreshing) { + return new Promise((resolve) => { + this.once('refresh-complete', (quotes: NormalizedQuote[]) => { + resolve(quotes); + }); + }); + } + + // Check if parameters changed significantly (avoid unnecessary refreshes) + if (trigger.type === 'parameter-change' && !this.hasSignificantChange(trigger.params)) { + return this.state.quotes; + } + + this.abortController = new AbortController(); + + try { + this.setState({ + ...this.state, + isRefreshing: true, + error: null + }); + + this.config.onRefreshStart(); + this.emit('refresh-start'); + + // Fetch quotes with retry logic + const quotes = await this.fetchWithRetry(trigger); + + this.setState({ + ...this.state, + isRefreshing: false, + lastRefreshed: new Date(), + error: null, + retryCount: 0, + quotes + }); + + this.config.onRefresh(quotes); + this.emit('refresh-complete', quotes); + + return quotes; + + } catch (error) { + this.setState({ + ...this.state, + isRefreshing: false, + error: error as Error + }); + + this.config.onError(error as Error); + this.emit('refresh-error', error); + + throw error; + + } finally { + this.config.onRefreshEnd(); + this.emit('refresh-end'); + this.abortController = null; + } + } + + /** + * Fetch with retry logic + */ + private async fetchWithRetry(trigger: RefreshTrigger): Promise { + let lastError: Error | null = null; + + for (let attempt = 1; attempt <= this.config.maxRetries; attempt++) { + try { + // Update parameters if this is a parameter change trigger + const params = trigger.type === 'parameter-change' + ? { ...this.lastParams, ...trigger.params } + : this.lastParams; + + const quotes = await this.fetchQuotesFn(params, { + signal: this.abortController?.signal + }); + + // Validate quotes + this.validateQuotes(quotes); + + return quotes; + + } catch (error) { + lastError = error as Error; + + if (attempt < this.config.maxRetries) { + // Exponential backoff + const delay = this.config.retryDelayMs * Math.pow(2, attempt - 1); + await new Promise(resolve => setTimeout(resolve, delay)); + + this.setState({ + ...this.state, + retryCount: attempt + }); + + this.emit('retry-attempt', { attempt, error }); + } + } + } + + throw lastError || new Error('Failed to fetch quotes after retries'); + } + + /** + * Check if parameters changed significantly + */ + private hasSignificantChange(newParams?: Record): boolean { + if (!newParams) return false; + + const significantParams = ['amount', 'sourceChain', 'destinationChain', 'sourceToken', 'destinationToken']; + + for (const param of significantParams) { + if (this.lastParams[param] !== newParams[param]) { + return true; + } + } + + return false; + } + + /** + * Validate quotes data structure + */ + private validateQuotes(quotes: NormalizedQuote[]): void { + quotes.forEach(quote => { + if (!quote.id || !quote.bridgeName || !quote.outputAmount) { + throw new Error('Invalid quote format: missing required fields'); + } + }); + } + + /** + * Update engine state + */ + private setState(newState: RefreshState): void { + this.state = newState; + this.emit('state-change', this.state); + } + + /** + * Get current state + */ + public getState(): RefreshState { + return { ...this.state }; + } + + /** + * Update configuration + */ + public updateConfig(config: Partial): void { + this.config = { + ...this.config, + ...config + }; + + // Restart auto-refresh if interval changed + if (config.intervalMs && this.config.autoRefresh) { + this.startAutoRefresh(); + } + } + + /** + * Clean up resources + */ + public destroy(): void { + this.stopAutoRefresh(); + + if (this.abortController) { + this.abortController.abort(); + } + + this.refreshQueue = []; + this.removeAllListeners(); + } +} \ No newline at end of file diff --git a/apps/web/types/quote.types.ts b/apps/web/types/quote.types.ts new file mode 100644 index 0000000..07e9c0c --- /dev/null +++ b/apps/web/types/quote.types.ts @@ -0,0 +1,55 @@ +export interface NormalizedQuote { + id: string; + bridgeName: string; + sourceChain: string; + destinationChain: string; + sourceToken: string; + destinationToken: string; + inputAmount: string; + outputAmount: string; + fee: { + amount: string; + currency: string; + breakdown?: { + network: string; + bridge: string; + gas: string; + }; + }; + slippage: number; + estimatedTime: number; // in seconds + liquidity: { + available: string; + total: string; + percentage: number; + }; + route: string[]; + reliability: number; // 0-100 + timestamp: number; + expiresAt: number; +} + +export interface QuoteRefreshConfig { + intervalMs?: number; // default 15 seconds + autoRefresh?: boolean; // enable/disable auto-refresh + maxRetries?: number; // maximum retry attempts + retryDelayMs?: number; // delay between retries + onRefresh?: (quotes: NormalizedQuote[]) => void; + onError?: (error: Error) => void; + onRefreshStart?: () => void; + onRefreshEnd?: () => void; +} + +export interface RefreshState { + isRefreshing: boolean; + lastRefreshed: Date | null; + error: Error | null; + retryCount: number; + quotes: NormalizedQuote[]; +} + +export interface RefreshTrigger { + type: 'interval' | 'manual' | 'parameter-change'; + timestamp: number; + params?: Record; +} \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index 6150dcd..754f1b7 100644 --- a/package-lock.json +++ b/package-lock.json @@ -2569,6 +2569,12 @@ } } }, + "node_modules/@nestjs/swagger/node_modules/lodash": { + "version": "4.17.23", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.23.tgz", + "integrity": "sha512-LgVTMpQtIopCi79SJeDiP0TfWi5CNEc/L/aRdTh3yIvmZXTnheWpKjSZhnvMl8iXbC1tFg9gdHHDMLoV7CnG+w==", + "license": "MIT" + }, "node_modules/@nestjs/testing": { "version": "11.1.14", "resolved": "https://registry.npmjs.org/@nestjs/testing/-/testing-11.1.14.tgz", @@ -3009,6 +3015,9 @@ "license": "MIT" }, "node_modules/@types/node": { + "version": "22.19.7", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.19.7.tgz", + "integrity": "sha512-MciR4AKGHWl7xwxkBa6xUGxQJ4VBOmPTF7sL+iGzuahOFaO0jHCsuEfS80pan1ef4gWId1oWOweIhrDEYLuaOw==", "version": "22.19.11", "resolved": "https://registry.npmjs.org/@types/node/-/node-22.19.11.tgz", "integrity": "sha512-BH7YwL6rA93ReqeQS1c4bsPpcfOmJasG+Fkr6Y59q83f9M1WcBRHR2vM+P9eOisYRcN3ujQoiZY8uk5W+1WL8w==", @@ -3877,6 +3886,9 @@ } }, "node_modules/acorn": { + "version": "8.15.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz", + "integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==", "version": "8.16.0", "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.16.0.tgz", "integrity": "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw==", @@ -3914,6 +3926,9 @@ } }, "node_modules/acorn-walk": { + "version": "8.3.4", + "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.3.4.tgz", + "integrity": "sha512-ueEepnujpqee2o5aIYnvHU6C0A42MNdsIDeqy5BydrkuC5R1ZuUFnm27EeFJGoEHJQgn3uleRvmTXaJgfXbt4g==", "version": "8.3.5", "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.3.5.tgz", "integrity": "sha512-HEHNfbars9v4pgpW6SO1KSPkfoS0xVOM/9UzkJltjlsHZmJasxg8aXkuZa7SMf8vKGIBhpUsPluQSqhJFCqebw==", diff --git a/tsconfig.json b/tsconfig.json index 1c704c2..d22b6c9 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -33,7 +33,7 @@ "include": [ "src/**/*", "libs/**/src/**/*" - ], +, "apps/web/services", "apps/web/components/ui-lib/hooks/useBridgeQuotes.ts" ], "exclude": [ "apps", "examples",