forked from ritik4ever/stellar-portfolio-rebalancer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.tsx
More file actions
520 lines (493 loc) · 22.8 KB
/
Copy pathApp.tsx
File metadata and controls
520 lines (493 loc) · 22.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
import { useState, useEffect, useRef } from 'react'
import { useQueryClient } from '@tanstack/react-query'
import Landing from './components/Landing'
import Dashboard from './components/Dashboard'
import PortfolioSetup from './components/PortfolioSetup'
import Settings from './pages/Settings'
import { ErrorBoundary } from './components/ErrorBoundary'
import Legal from './components/Legal'
import ConsentGate from './components/ConsentGate'
import { trackPageView, trackEvent } from './analytics'
import { walletManager } from './utils/walletManager'
import { WalletError } from './utils/walletAdapters'
import { login as authLogin } from './services/authService'
import {
isAuthServiceUnavailable,
resolveConsentAcceptedNavigation,
runWalletReconnectBoot,
runBootDiagnostics,
type BootCheck,
} from './app/walletBoot'
import BootDiagnosticsPanel from './components/BootDiagnosticsPanel'
import { api, ENDPOINTS } from './config/api'
import type { LegalDocType } from './components/Legal'
import RealtimeStatusBanner from './components/RealtimeStatusBanner'
import BackendCapabilitiesBanner from './components/BackendCapabilitiesBanner'
import StartupSplash from './components/StartupSplash'
import { useReadinessReport } from './hooks/useReadinessReport'
import {
onAuthSessionExpired,
onAuthSessionRestored,
} from './services/authService'
import DeveloperDrawer from './components/DeveloperDrawer'
import { checkApiCompatibility, type ApiCompatibilityResult } from './config/apiCompatibility'
import {
detectContractCapabilities,
type ContractCapabilityReport,
} from './lib/contractCapabilities'
import { appCopy } from './content/uiCopy'
import PublicPortfolio from './pages/PublicPortfolio'
import PortfolioWizard from './pages/PortfolioWizard'
import Compare from './pages/Compare'
import Shortcuts from './components/Shortcuts'
import Onboarding, { resetOnboarding } from './components/Onboarding'
import OnboardingChecklist from './components/OnboardingChecklist'
function App() {
const queryClient = useQueryClient()
const [currentView, setCurrentView] = useState('landing')
const [publicKey, setPublicKey] = useState<string | null>(null)
const [pendingConsentPublicKey, setPendingConsentPublicKey] = useState<string | null>(null)
const [legalDoc, setLegalDoc] = useState<LegalDocType | null>(null)
const [isConnecting, setIsConnecting] = useState(false)
const [error, setError] = useState<string | null>(null)
const [sessionRecovery, setSessionRecovery] = useState<string | null>(null)
const [sessionRecoverySource, setSessionRecoverySource] = useState<string | null>(null)
const [isRecoveringSession, setIsRecoveringSession] = useState(false)
const { notices, loadError, loading: readinessLoading, bootReady } = useReadinessReport()
const [apiCompatibility, setApiCompatibility] = useState<ApiCompatibilityResult | null>(null)
const [apiCompatibilityDismissed, setApiCompatibilityDismissed] = useState(false)
const [apiCompatibilityLoading, setApiCompatibilityLoading] = useState(true)
const [contractCapabilities, setContractCapabilities] =
useState<ContractCapabilityReport | null>(null)
const showBackendBanner = loadError || notices.length > 0
const showApiCompatibilityBanner =
!apiCompatibilityDismissed &&
apiCompatibility !== null &&
apiCompatibility.severity !== 'ok'
const contentTopPad =
showBackendBanner && showApiCompatibilityBanner
? 'pt-28'
: showBackendBanner || showApiCompatibilityBanner
? 'pt-14'
: 'pt-4'
const [bootChecks, setBootChecks] = useState<BootCheck[]>([])
const [showBootDiagnostics, setShowBootDiagnostics] = useState(false)
const settingsDirtyRef = useRef(false)
const [publicShareHash, setPublicShareHash] = useState<string | null>(() => {
if (typeof window !== 'undefined') {
const match = window.location.pathname.match(/^\/public\/([a-zA-Z0-9-]+)/)
return match ? match[1] : null
}
return null
})
const [embedPortfolioId, setEmbedPortfolioId] = useState<string | null>(() => {
if (typeof window !== 'undefined') {
const match = window.location.pathname.match(/^\/embed\/portfolio\/([a-zA-Z0-9-]+)/)
return match ? match[1] : null
}
return null
})
useEffect(() => {
checkWalletConnection()
runBootDiagnostics({
checkWallets: () => {
const wallets = walletManager.getAvailableWallets()
return wallets.length > 0
},
checkApi: async () => {
try {
await api.get(ENDPOINTS.HEALTH)
return true
} catch {
return false
}
},
}).then((result) => setBootChecks(result.checks))
}, [])
useEffect(() => {
const controller = new AbortController()
setApiCompatibilityLoading(true)
void checkApiCompatibility(controller.signal).then((result) => {
setApiCompatibility(result)
setApiCompatibilityLoading(false)
})
return () => controller.abort()
}, [])
// Lightweight contract capability detection: confirm the deployment supports
// the documented methods before any write is attempted (issue #834).
useEffect(() => {
const controller = new AbortController()
void detectContractCapabilities(controller.signal).then((report) => {
setContractCapabilities(report)
if (report.severity !== 'ok') {
console.warn(`[contract] ${report.title}: ${report.message}`)
}
})
return () => controller.abort()
}, [])
useEffect(() => {
const clearRecovery = () => {
setSessionRecovery(null)
setSessionRecoverySource(null)
}
const unsubscribeExpired = onAuthSessionExpired((detail) => {
setSessionRecovery(detail.message)
setSessionRecoverySource(detail.source ?? null)
setError(null)
})
const unsubscribeRestored = onAuthSessionRestored(() => {
clearRecovery()
})
return () => {
unsubscribeExpired()
unsubscribeRestored()
}
}, [])
const checkConsent = async (userId: string): Promise<boolean> => {
try {
const res = await api.get<{ accepted: boolean }>(
`${ENDPOINTS.CONSENT_STATUS}?userId=${encodeURIComponent(userId)}`
)
return !!res?.accepted
} catch {
return false
}
}
const applyAuthenticatedWallet = async (pk: string, navigateToDashboard: boolean) => {
setIsConnecting(true)
setError(null)
try {
try {
await authLogin(pk)
} catch (authErr: unknown) {
if (isAuthServiceUnavailable(authErr)) {
// Auth service not configured – soft fail, allow access.
console.warn('Auth service unavailable during connect; proceeding without JWT:', authErr)
} else {
// Hard auth failure: wallet is connected but the backend rejected
// authentication. Do NOT navigate to the dashboard.
console.error('Auth login failed during wallet connect:', authErr)
setError(
'Wallet connected but authentication failed. ' +
'Please try reconnecting your wallet.'
)
return false
}
}
setPublicKey(pk)
trackEvent('wallet_connected')
if (navigateToDashboard) {
setCurrentView('dashboard')
trackPageView('dashboard')
}
await queryClient.invalidateQueries()
return true
} finally {
setIsConnecting(false)
}
}
const checkWalletConnection = async () => {
const result = await runWalletReconnectBoot({
reconnect: () => walletManager.reconnect(),
checkConsent,
authLogin,
})
if (result.outcome === 'no_wallet') {
return
}
if (result.outcome === 'needs_consent') {
setPublicKey(result.publicKey)
setPendingConsentPublicKey(result.publicKey)
return
}
if (result.outcome === 'dashboard') {
setPublicKey(result.publicKey)
setCurrentView('dashboard')
return
}
if (result.outcome === 'auth_failed') {
setError(result.message)
return
}
if (result.outcome === 'reconnect_failed') {
setError(result.message)
}
}
const connectWallet = async () => {
try {
const pk = walletManager.getPublicKey()
if (pk) {
await applyAuthenticatedWallet(pk, true)
} else {
setError('No wallet connected. Please select a wallet first.')
}
} catch (err: any) {
console.error('Wallet connection error:', err)
if (err instanceof WalletError) {
if (err.code === 'USER_DECLINED') setError('Connection was declined. Please approve in your wallet.')
else if (err.code === 'WALLET_NOT_INSTALLED') setError(`${err.walletType || 'Wallet'} is not installed. Please install it and refresh.`)
else if (err.code === 'NETWORK_MISMATCH') setError('Network mismatch. Please check your wallet network settings.')
else if (err.code === 'TIMEOUT') setError('Connection timed out. Please try again.')
else setError(err.message || 'Failed to connect wallet.')
} else if (err.message === 'NO_WALLET_FOUND') {
setError('No Stellar wallet detected. Please install Freighter, Rabet, or xBull wallet.')
} else {
setError(err.message || 'Failed to connect wallet. Please try again.')
}
}
}
const retrySessionSignIn = async () => {
const pk = walletManager.getPublicKey() || publicKey
if (!pk) {
setSessionRecovery('No wallet is currently connected. Reconnect your wallet first.')
return
}
setIsRecoveringSession(true)
try {
const success = await applyAuthenticatedWallet(pk, false)
if (success) {
setSessionRecovery(null)
setSessionRecoverySource(null)
}
} finally {
setIsRecoveringSession(false)
}
}
const handleNeedsConsent = (pk: string) => {
setPendingConsentPublicKey(pk)
}
const handleConsentAccepted = () => {
const next = resolveConsentAcceptedNavigation(pendingConsentPublicKey)
if (next) {
setPublicKey(next.publicKey)
setPendingConsentPublicKey(null)
setCurrentView(next.targetView)
}
}
const handleNavigate = (view: string, legalDocType?: LegalDocType) => {
if (currentView === 'settings' && settingsDirtyRef.current && view !== 'settings') {
if (!window.confirm('You have unsaved changes in Settings. Leave without saving?')) return
}
setError(null)
if (legalDocType) setLegalDoc(legalDocType)
else if (view.startsWith('legal-')) setLegalDoc(view.replace('legal-', '') as LegalDocType)
else setLegalDoc(null)
setCurrentView(view)
trackPageView(view)
}
const errorTop = showBackendBanner ? 'top-[4.25rem]' : 'top-4'
if (!bootReady) {
return <StartupSplash loading={readinessLoading} loadError={loadError} />
}
return (
<div className={`App min-h-screen ${contentTopPad}`}>
<RealtimeStatusBanner />
<BackendCapabilitiesBanner belowRealtimeBar={false} />
{showApiCompatibilityBanner && apiCompatibility ? (
<div
className={`fixed left-0 right-0 z-40 border-b px-4 py-3 text-sm ${
showBackendBanner ? 'top-14' : 'top-0'
} ${
apiCompatibility.severity === 'error'
? 'border-red-200 bg-red-50 text-red-900 dark:border-red-900 dark:bg-red-950/80 dark:text-red-100'
: 'border-amber-200 bg-amber-50 text-amber-950 dark:border-amber-900 dark:bg-amber-950/80 dark:text-amber-100'
}`}
role="alert"
>
<div className="mx-auto flex max-w-7xl items-start justify-between gap-4">
<div>
<p className="font-semibold">{apiCompatibility.title}</p>
<p className="mt-1 opacity-90">{apiCompatibility.message}</p>
<p className="mt-1 text-xs opacity-75">
Target: {apiCompatibility.configuredOrigin}
{apiCompatibility.configuredApiRoot}
</p>
</div>
<button
type="button"
onClick={() => setApiCompatibilityDismissed(true)}
className="shrink-0 rounded px-2 py-1 text-xs font-medium hover:bg-black/5 dark:hover:bg-white/10"
>
{appCopy.dismiss}
</button>
</div>
</div>
) : null}
{apiCompatibilityLoading && !apiCompatibility ? (
<span className="sr-only" role="status">
{appCopy.checkingApiConfig}
</span>
) : null}
<DeveloperDrawer publicKey={publicKey} contractCapabilities={contractCapabilities} />
<Shortcuts
onNewPortfolio={() => handleNavigate('setup')}
onOpenSettings={() => {
if (currentView === 'dashboard') {
resetOnboarding()
window.location.reload()
}
}}
/>
<Onboarding />
<OnboardingChecklist publicKey={publicKey} onNavigate={handleNavigate} />
{sessionRecovery ? (
<div
className="fixed bottom-4 right-4 z-50 w-[min(24rem,calc(100vw-2rem))] rounded-2xl border border-amber-200 bg-amber-50 p-4 text-amber-950 shadow-xl dark:border-amber-900 dark:bg-amber-950/80 dark:text-amber-50"
role="status"
aria-live="polite"
>
<div className="flex items-start gap-3">
<div className="mt-0.5 text-lg">⚠️</div>
<div className="min-w-0 flex-1">
<p className="text-sm font-semibold">{appCopy.sessionExpiredTitle}</p>
<p className="mt-1 text-sm leading-5 opacity-90">{sessionRecovery}</p>
{sessionRecoverySource ? (
<p className="mt-1 text-[11px] uppercase tracking-[0.2em] opacity-70">
Source: {sessionRecoverySource}
</p>
) : null}
<div className="mt-3 flex flex-wrap gap-2">
<button
type="button"
onClick={retrySessionSignIn}
disabled={isRecoveringSession}
className="rounded-full bg-amber-600 px-3 py-1.5 text-xs font-semibold text-white hover:bg-amber-700 disabled:cursor-not-allowed disabled:opacity-60"
>
{isRecoveringSession ? appCopy.reconnecting : appCopy.retrySignIn}
</button>
<button
type="button"
onClick={() => {
setSessionRecovery(null)
setSessionRecoverySource(null)
}}
className="rounded-full border border-amber-300 px-3 py-1.5 text-xs font-semibold text-amber-900 hover:bg-amber-100 dark:border-amber-800 dark:text-amber-100 dark:hover:bg-amber-900/40"
>
{appCopy.dismiss}
</button>
</div>
</div>
</div>
</div>
) : null}
{error && (
<div
className={`fixed left-1/2 transform -translate-x-1/2 z-50 bg-red-50 dark:bg-red-900/40 border border-red-200 dark:border-red-800 rounded-lg p-4 max-w-md ${errorTop}`}
>
<div className="flex items-center text-red-800 dark:text-red-300">
<span className="mr-2">⚠️</span>
<span>{error}</span>
<button
onClick={() => setError(null)}
className="ml-4 text-red-600 hover:text-red-800 dark:text-red-400 dark:hover:text-red-200"
>
✕
</button>
</div>
</div>
)}
{pendingConsentPublicKey ? (
legalDoc ? (
<Legal doc={legalDoc} onBack={() => setLegalDoc(null)} />
) : (
<ConsentGate
userId={pendingConsentPublicKey}
onAccept={handleConsentAccepted}
onOpenLegal={(doc) => setLegalDoc(doc)}
/>
)
) : (currentView === 'legal-terms' || currentView === 'legal-privacy' || currentView === 'legal-cookies') && legalDoc ? (
<Legal
doc={legalDoc}
onBack={() => handleNavigate('landing')}
/>
) : embedPortfolioId ? (
<EmbedWidget id={embedPortfolioId} />
) : publicShareHash ? (
<PublicPortfolio hash={publicShareHash} />
) : currentView === 'landing' ? (
<div className="relative">
<Landing
onNavigate={handleNavigate}
onConnectWallet={connectWallet}
onNeedsConsent={handleNeedsConsent}
isConnecting={isConnecting}
publicKey={publicKey}
/>
{!publicKey ? (
<div className="fixed bottom-4 left-4 z-40 max-w-xs">
<button
type="button"
onClick={() => setShowBootDiagnostics(!showBootDiagnostics)}
className="mb-1 flex items-center gap-1.5 rounded-full border border-slate-200 bg-white/90 px-3 py-1.5 text-xs text-slate-500 shadow-sm backdrop-blur hover:bg-white hover:text-slate-700 dark:border-slate-700 dark:bg-slate-900/80 dark:text-slate-400 dark:hover:bg-slate-800 dark:hover:text-slate-200"
>
{showBootDiagnostics ? 'Hide' : 'Show'} startup checks
</button>
{showBootDiagnostics ? (
<BootDiagnosticsPanel
checks={bootChecks}
onRetry={() => {
setBootChecks([
{ id: 'wallet-detection', label: 'Wallet extension', status: 'loading' },
{ id: 'api-reachability', label: 'API reachability', status: 'loading' },
])
runBootDiagnostics({
checkWallets: () => {
const wallets = walletManager.getAvailableWallets()
return wallets.length > 0
},
checkApi: async () => {
try {
await api.get(ENDPOINTS.HEALTH)
return true
} catch {
return false
}
},
}).then((result) => setBootChecks(result.checks))
}}
/>
) : null}
</div>
) : null}
</div>
) : currentView === 'dashboard' ? (
<ErrorBoundary fallbackTitle="Dashboard">
<Dashboard
onNavigate={handleNavigate}
publicKey={publicKey}
/>
</ErrorBoundary>
) : currentView === 'setup' ? (
<ErrorBoundary fallbackTitle="Portfolio Setup">
<PortfolioSetup
onNavigate={handleNavigate}
publicKey={publicKey}
/>
</ErrorBoundary>
) : currentView === 'wizard' ? (
<ErrorBoundary fallbackTitle="Portfolio Wizard">
<PortfolioWizard
onNavigate={handleNavigate}
publicKey={publicKey}
/>
</ErrorBoundary>
) : currentView === 'compare' ? (
<ErrorBoundary fallbackTitle="Compare Portfolios">
<Compare
onNavigate={handleNavigate}
publicKey={publicKey}
/>
</ErrorBoundary>
) : currentView === 'settings' ? (
<ErrorBoundary fallbackTitle="Settings">
<Settings
onNavigate={handleNavigate}
onDirtyChange={(dirty) => { settingsDirtyRef.current = dirty }}
/>
</ErrorBoundary>
) : null}
</div>
)
}
export default App