Merge branch 'claude/calisma-ya-011CV6DKKRcWvDTxoEY7rYV4' into main

This commit is contained in:
2025-11-17 03:15:30 +03:00
23 changed files with 3923 additions and 1333 deletions
+64 -49
View File
@@ -10,6 +10,8 @@ import AdminPanel from '@/pages/AdminPanel';
import WalletDashboard from './pages/WalletDashboard';
import ReservesDashboardPage from './pages/ReservesDashboardPage';
import BeCitizen from './pages/BeCitizen';
import Elections from './pages/Elections';
import EducationPlatform from './pages/EducationPlatform';
import { AppProvider } from '@/contexts/AppContext';
import { PolkadotProvider } from '@/contexts/PolkadotContext';
import { WalletProvider } from '@/contexts/WalletContext';
@@ -19,63 +21,76 @@ import { AuthProvider } from '@/contexts/AuthContext';
import { ProtectedRoute } from '@/components/ProtectedRoute';
import NotFound from '@/pages/NotFound';
import { Toaster } from '@/components/ui/toaster';
import { ErrorBoundary } from '@/components/ErrorBoundary';
import './App.css';
import './i18n/config';
function App() {
return (
<ThemeProvider defaultTheme="dark" storageKey="vite-ui-theme">
<AuthProvider>
<AppProvider>
<PolkadotProvider>
<WalletProvider>
<WebSocketProvider>
<IdentityProvider>
<Router>
<Routes>
<Route path="/login" element={<Login />} />
<ErrorBoundary>
<AuthProvider>
<AppProvider>
<PolkadotProvider endpoint="ws://127.0.0.1:9944">
<WalletProvider>
<WebSocketProvider>
<IdentityProvider>
<Router>
<Routes>
<Route path="/login" element={<Login />} />
<Route path="/email-verification" element={<EmailVerification />} />
<Route path="/reset-password" element={<PasswordReset />} />
<Route path="/" element={<Index />} />
<Route path="/be-citizen" element={<BeCitizen />} />
<Route path="/dashboard" element={
<ProtectedRoute>
<Dashboard />
</ProtectedRoute>
} />
<Route path="/profile/settings" element={
<ProtectedRoute>
<ProfileSettings />
</ProtectedRoute>
} />
<Route path="/admin" element={
<ProtectedRoute requireAdmin>
<AdminPanel />
</ProtectedRoute>
} />
<Route path="/wallet" element={
<ProtectedRoute>
<WalletDashboard />
</ProtectedRoute>
} />
<Route path="/reserves" element={
<ProtectedRoute>
<ReservesDashboardPage />
</ProtectedRoute>
} />
<Route path="*" element={<NotFound />} />
</Routes>
</Router>
</IdentityProvider>
</WebSocketProvider>
</WalletProvider>
</PolkadotProvider>
</AppProvider>
</AuthProvider>
<Toaster />
<Route path="/email-verification" element={<EmailVerification />} />
<Route path="/reset-password" element={<PasswordReset />} />
<Route path="/" element={<Index />} />
<Route path="/be-citizen" element={<BeCitizen />} />
<Route path="/dashboard" element={
<ProtectedRoute>
<Dashboard />
</ProtectedRoute>
} />
<Route path="/profile/settings" element={
<ProtectedRoute>
<ProfileSettings />
</ProtectedRoute>
} />
<Route path="/admin" element={
<ProtectedRoute requireAdmin>
<AdminPanel />
</ProtectedRoute>
} />
<Route path="/wallet" element={
<ProtectedRoute>
<WalletDashboard />
</ProtectedRoute>
} />
<Route path="/reserves" element={
<ProtectedRoute>
<ReservesDashboardPage />
</ProtectedRoute>
} />
<Route path="/elections" element={
<ProtectedRoute>
<Elections />
</ProtectedRoute>
} />
<Route path="/education" element={
<ProtectedRoute>
<EducationPlatform />
</ProtectedRoute>
} />
<Route path="*" element={<NotFound />} />
</Routes>
</Router>
</IdentityProvider>
</WebSocketProvider>
</WalletProvider>
</PolkadotProvider>
</AppProvider>
</AuthProvider>
<Toaster />
</ErrorBoundary>
</ThemeProvider>
);
}
export default App;
export default App;
+1 -25
View File
@@ -27,7 +27,6 @@ import RewardDistribution from './RewardDistribution';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { useWebSocket } from '@/contexts/WebSocketContext';
import { StakingDashboard } from './staking/StakingDashboard';
import { P2PMarket } from './p2p/P2PMarket';
import { MultiSigWallet } from './wallet/MultiSigWallet';
import { useWallet } from '@/contexts/WalletContext';
import { supabase } from '@/lib/supabase';
@@ -45,7 +44,6 @@ const AppLayout: React.FC = () => {
const [showTreasury, setShowTreasury] = useState(false);
const [treasuryTab, setTreasuryTab] = useState('overview');
const [showStaking, setShowStaking] = useState(false);
const [showP2P, setShowP2P] = useState(false);
const [showMultiSig, setShowMultiSig] = useState(false);
const [showDEX, setShowDEX] = useState(false);
const { t } = useTranslation();
@@ -182,13 +180,6 @@ const AppLayout: React.FC = () => {
<Droplet className="w-4 h-4" />
DEX Pools
</button>
<button
onClick={() => setShowP2P(true)}
className="w-full text-left px-4 py-2 text-gray-300 hover:bg-gray-800 hover:text-white flex items-center gap-2"
>
<ArrowRightLeft className="w-4 h-4" />
P2P Market
</button>
<button
onClick={() => setShowStaking(true)}
className="w-full text-left px-4 py-2 text-gray-300 hover:bg-gray-800 hover:text-white flex items-center gap-2"
@@ -363,20 +354,6 @@ const AppLayout: React.FC = () => {
<StakingDashboard />
</div>
</div>
) : showP2P ? (
<div className="pt-20 min-h-screen bg-gray-950">
<div className="max-w-full mx-auto px-4">
<div className="text-center mb-12">
<h2 className="text-4xl font-bold mb-4 bg-gradient-to-r from-green-500 via-yellow-400 to-red-500 bg-clip-text text-transparent">
P2P Trading Market
</h2>
<p className="text-gray-400 text-lg max-w-3xl mx-auto">
Trade tokens directly with other users
</p>
</div>
<P2PMarket />
</div>
</div>
) : showMultiSig ? (
<div className="pt-20 min-h-screen bg-gray-950">
<div className="max-w-full mx-auto px-4">
@@ -415,7 +392,7 @@ const AppLayout: React.FC = () => {
)}
{(showDEX || showProposalWizard || showDelegation || showForum || showModeration || showTreasury || showStaking || showP2P || showMultiSig) && (
{(showDEX || showProposalWizard || showDelegation || showForum || showModeration || showTreasury || showStaking || showMultiSig) && (
<div className="fixed bottom-8 right-8 z-50">
<button
onClick={() => {
@@ -426,7 +403,6 @@ const AppLayout: React.FC = () => {
setShowModeration(false);
setShowTreasury(false);
setShowStaking(false);
setShowP2P(false);
setShowMultiSig(false);
}}
className="bg-green-600 hover:bg-green-700 text-white px-6 py-3 rounded-full shadow-lg flex items-center gap-2 transition-all"
+243
View File
@@ -0,0 +1,243 @@
// ========================================
// Error Boundary Component
// ========================================
// Catches React errors and displays fallback UI
import React, { Component, ErrorInfo, ReactNode } from 'react';
import { Card, CardContent } from '@/components/ui/card';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Button } from '@/components/ui/button';
import { AlertTriangle, RefreshCw, Home } from 'lucide-react';
interface Props {
children: ReactNode;
fallback?: ReactNode;
onError?: (error: Error, errorInfo: ErrorInfo) => void;
}
interface State {
hasError: boolean;
error: Error | null;
errorInfo: ErrorInfo | null;
}
/**
* Global Error Boundary
* Catches unhandled errors in React component tree
*
* @example
* <ErrorBoundary>
* <App />
* </ErrorBoundary>
*/
export class ErrorBoundary extends Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = {
hasError: false,
error: null,
errorInfo: null,
};
}
static getDerivedStateFromError(error: Error): Partial<State> {
// Update state so next render shows fallback UI
return {
hasError: true,
error,
};
}
componentDidCatch(error: Error, errorInfo: ErrorInfo): void {
// Log error to console
console.error('ErrorBoundary caught an error:', error, errorInfo);
// Update state with error details
this.setState({
error,
errorInfo,
});
// Call custom error handler if provided
if (this.props.onError) {
this.props.onError(error, errorInfo);
}
// In production, you might want to log to an error reporting service
// Example: Sentry.captureException(error);
}
handleReset = (): void => {
this.setState({
hasError: false,
error: null,
errorInfo: null,
});
};
handleReload = (): void => {
window.location.reload();
};
handleGoHome = (): void => {
window.location.href = '/';
};
render(): ReactNode {
if (this.state.hasError) {
// Use custom fallback if provided
if (this.props.fallback) {
return this.props.fallback;
}
// Default error UI
return (
<div className="min-h-screen bg-gray-950 flex items-center justify-center p-4">
<Card className="bg-gray-900 border-gray-800 max-w-2xl w-full">
<CardContent className="p-8">
<Alert className="bg-red-900/20 border-red-500 mb-6">
<AlertTriangle className="h-6 w-6 text-red-400" />
<AlertDescription className="text-gray-300">
<h2 className="text-xl font-bold mb-2 text-white">Something Went Wrong</h2>
<p className="mb-4">
An unexpected error occurred. We apologize for the inconvenience.
</p>
{this.state.error && (
<details className="mt-4 p-4 bg-gray-950 rounded border border-gray-700">
<summary className="cursor-pointer text-sm font-semibold text-gray-400 hover:text-gray-300">
Error Details (for developers)
</summary>
<div className="mt-3 text-xs font-mono space-y-2">
<div>
<strong className="text-red-400">Error:</strong>
<pre className="mt-1 text-gray-400 whitespace-pre-wrap">
{this.state.error.toString()}
</pre>
</div>
{this.state.errorInfo && (
<div>
<strong className="text-red-400">Component Stack:</strong>
<pre className="mt-1 text-gray-400 whitespace-pre-wrap">
{this.state.errorInfo.componentStack}
</pre>
</div>
)}
</div>
</details>
)}
</AlertDescription>
</Alert>
<div className="flex flex-col sm:flex-row gap-3">
<Button
onClick={this.handleReset}
className="bg-green-600 hover:bg-green-700 flex items-center gap-2"
>
<RefreshCw className="w-4 h-4" />
Try Again
</Button>
<Button
onClick={this.handleReload}
variant="outline"
className="border-gray-700 hover:bg-gray-800 flex items-center gap-2"
>
<RefreshCw className="w-4 h-4" />
Reload Page
</Button>
<Button
onClick={this.handleGoHome}
variant="outline"
className="border-gray-700 hover:bg-gray-800 flex items-center gap-2"
>
<Home className="w-4 h-4" />
Go Home
</Button>
</div>
<p className="mt-6 text-sm text-gray-500">
If this problem persists, please contact support at{' '}
<a
href="mailto:info@pezkuwichain.io"
className="text-green-400 hover:underline"
>
info@pezkuwichain.io
</a>
</p>
</CardContent>
</Card>
</div>
);
}
// No error, render children normally
return this.props.children;
}
}
// ========================================
// ROUTE-LEVEL ERROR BOUNDARY
// ========================================
/**
* Smaller error boundary for individual routes
* Less intrusive, doesn't take over the whole screen
*/
export const RouteErrorBoundary: React.FC<{
children: ReactNode;
routeName?: string;
}> = ({ children, routeName = 'this page' }) => {
const [hasError, setHasError] = React.useState(false);
const handleReset = () => {
setHasError(false);
};
if (hasError) {
return (
<div className="p-8">
<Alert className="bg-red-900/20 border-red-500">
<AlertTriangle className="h-5 w-5 text-red-400" />
<AlertDescription className="text-gray-300">
<strong className="block mb-2">Error loading {routeName}</strong>
An error occurred while rendering this component.
<div className="mt-4">
<Button onClick={handleReset} size="sm" className="bg-green-600 hover:bg-green-700">
<RefreshCw className="w-4 h-4 mr-2" />
Try Again
</Button>
</div>
</AlertDescription>
</Alert>
</div>
);
}
return (
<ErrorBoundary fallback={<RouteErrorFallback routeName={routeName} onReset={handleReset} />}>
{children}
</ErrorBoundary>
);
};
const RouteErrorFallback: React.FC<{ routeName: string; onReset: () => void }> = ({
routeName,
onReset,
}) => {
return (
<div className="p-8">
<Alert className="bg-red-900/20 border-red-500">
<AlertTriangle className="h-5 w-5 text-red-400" />
<AlertDescription className="text-gray-300">
<strong className="block mb-2">Error loading {routeName}</strong>
An unexpected error occurred.
<div className="mt-4">
<Button onClick={onReset} size="sm" className="bg-green-600 hover:bg-green-700">
<RefreshCw className="w-4 h-4 mr-2" />
Try Again
</Button>
</div>
</AlertDescription>
</Alert>
</div>
);
};
+466
View File
@@ -0,0 +1,466 @@
// ========================================
// Route Guard Components
// ========================================
// Protected route wrappers that check user permissions
import React, { useEffect, useState, ReactNode } from 'react';
import { Navigate } from 'react-router-dom';
import { usePolkadot } from '@/contexts/PolkadotContext';
import { useAuth } from '@/contexts/AuthContext';
import {
checkCitizenStatus,
checkValidatorStatus,
checkEducatorRole,
checkModeratorRole,
} from '@pezkuwi/lib/guards';
import { Card, CardContent } from '@/components/ui/card';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Loader2, AlertCircle, Users, GraduationCap, Shield } from 'lucide-react';
import { Button } from '@/components/ui/button';
interface RouteGuardProps {
children: ReactNode;
fallbackPath?: string;
}
// ========================================
// LOADING COMPONENT
// ========================================
const LoadingGuard: React.FC = () => {
return (
<div className="min-h-screen bg-gray-950 flex items-center justify-center">
<Card className="bg-gray-900 border-gray-800 p-8">
<CardContent className="flex flex-col items-center gap-4">
<Loader2 className="w-12 h-12 text-green-500 animate-spin" />
<p className="text-gray-400">Checking permissions...</p>
</CardContent>
</Card>
</div>
);
};
// ========================================
// CITIZEN ROUTE GUARD
// ========================================
/**
* CitizenRoute - Requires approved KYC (citizenship)
* Use for: Voting, Education, Elections, etc.
*
* @example
* <Route path="/vote" element={
* <CitizenRoute>
* <VotingPage />
* </CitizenRoute>
* } />
*/
export const CitizenRoute: React.FC<RouteGuardProps> = ({
children,
fallbackPath = '/be-citizen',
}) => {
const { api, isApiReady, selectedAccount } = usePolkadot();
const { user } = useAuth();
const [isCitizen, setIsCitizen] = useState<boolean | null>(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
const checkPermission = async () => {
if (!isApiReady || !api) {
setLoading(true);
return;
}
if (!selectedAccount?.address) {
setIsCitizen(false);
setLoading(false);
return;
}
try {
const citizenStatus = await checkCitizenStatus(api, selectedAccount.address);
setIsCitizen(citizenStatus);
} catch (error) {
console.error('Citizen check failed:', error);
setIsCitizen(false);
} finally {
setLoading(false);
}
};
checkPermission();
}, [api, isApiReady, selectedAccount]);
// Loading state
if (loading || !isApiReady) {
return <LoadingGuard />;
}
// Not connected to wallet
if (!selectedAccount) {
return (
<div className="min-h-screen bg-gray-950 flex items-center justify-center p-4">
<Card className="bg-gray-900 border-gray-800 max-w-md">
<CardContent className="p-8">
<div className="flex flex-col items-center gap-4 text-center">
<Users className="w-16 h-16 text-yellow-500" />
<h2 className="text-2xl font-bold text-white">Wallet Not Connected</h2>
<p className="text-gray-400">
Please connect your Polkadot wallet to access this feature.
</p>
<Button
onClick={() => window.location.href = '/'}
className="bg-green-600 hover:bg-green-700"
>
Go to Home
</Button>
</div>
</CardContent>
</Card>
</div>
);
}
// Not a citizen
if (isCitizen === false) {
return <Navigate to={fallbackPath} replace />;
}
// Authorized
return <>{children}</>;
};
// ========================================
// VALIDATOR ROUTE GUARD
// ========================================
/**
* ValidatorRoute - Requires validator pool membership
* Use for: Validator pool dashboard, validator settings
*
* @example
* <Route path="/validator-pool" element={
* <ValidatorRoute>
* <ValidatorPoolDashboard />
* </ValidatorRoute>
* } />
*/
export const ValidatorRoute: React.FC<RouteGuardProps> = ({
children,
fallbackPath = '/staking',
}) => {
const { api, isApiReady, selectedAccount } = usePolkadot();
const [isValidator, setIsValidator] = useState<boolean | null>(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
const checkPermission = async () => {
if (!isApiReady || !api) {
setLoading(true);
return;
}
if (!selectedAccount?.address) {
setIsValidator(false);
setLoading(false);
return;
}
try {
const validatorStatus = await checkValidatorStatus(api, selectedAccount.address);
setIsValidator(validatorStatus);
} catch (error) {
console.error('Validator check failed:', error);
setIsValidator(false);
} finally {
setLoading(false);
}
};
checkPermission();
}, [api, isApiReady, selectedAccount]);
// Loading state
if (loading || !isApiReady) {
return <LoadingGuard />;
}
// Not connected to wallet
if (!selectedAccount) {
return <Navigate to="/" replace />;
}
// Not in validator pool
if (isValidator === false) {
return (
<div className="min-h-screen bg-gray-950 flex items-center justify-center p-4">
<Card className="bg-gray-900 border-gray-800 max-w-md">
<CardContent className="p-8">
<Alert className="bg-red-900/20 border-red-500">
<AlertCircle className="h-5 w-5 text-red-400" />
<AlertDescription className="text-gray-300">
<strong className="block mb-2">Validator Access Required</strong>
You must be registered in the Validator Pool to access this feature.
<div className="mt-4">
<Button
onClick={() => window.location.href = fallbackPath}
className="bg-green-600 hover:bg-green-700"
>
Go to Staking
</Button>
</div>
</AlertDescription>
</Alert>
</CardContent>
</Card>
</div>
);
}
// Authorized
return <>{children}</>;
};
// ========================================
// EDUCATOR ROUTE GUARD
// ========================================
/**
* EducatorRoute - Requires educator Tiki role
* Use for: Creating courses in Perwerde (Education platform)
*
* @example
* <Route path="/education/create-course" element={
* <EducatorRoute>
* <CourseCreator />
* </EducatorRoute>
* } />
*/
export const EducatorRoute: React.FC<RouteGuardProps> = ({
children,
fallbackPath = '/education',
}) => {
const { api, isApiReady, selectedAccount } = usePolkadot();
const [isEducator, setIsEducator] = useState<boolean | null>(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
const checkPermission = async () => {
if (!isApiReady || !api) {
setLoading(true);
return;
}
if (!selectedAccount?.address) {
setIsEducator(false);
setLoading(false);
return;
}
try {
const educatorStatus = await checkEducatorRole(api, selectedAccount.address);
setIsEducator(educatorStatus);
} catch (error) {
console.error('Educator check failed:', error);
setIsEducator(false);
} finally {
setLoading(false);
}
};
checkPermission();
}, [api, isApiReady, selectedAccount]);
// Loading state
if (loading || !isApiReady) {
return <LoadingGuard />;
}
// Not connected to wallet
if (!selectedAccount) {
return <Navigate to="/" replace />;
}
// Not an educator
if (isEducator === false) {
return (
<div className="min-h-screen bg-gray-950 flex items-center justify-center p-4">
<Card className="bg-gray-900 border-gray-800 max-w-md">
<CardContent className="p-8">
<Alert className="bg-red-900/20 border-red-500">
<GraduationCap className="h-5 w-5 text-red-400" />
<AlertDescription className="text-gray-300">
<strong className="block mb-2">Educator Role Required</strong>
You need one of these Tiki roles to create courses:
<ul className="list-disc list-inside mt-2 text-sm">
<li>Perwerdekar (Educator)</li>
<li>Mamoste (Teacher)</li>
<li>WezireCand (Education Minister)</li>
<li>Rewsenbîr (Intellectual)</li>
</ul>
<div className="mt-4">
<Button
onClick={() => window.location.href = fallbackPath}
className="bg-green-600 hover:bg-green-700"
>
Browse Courses
</Button>
</div>
</AlertDescription>
</Alert>
</CardContent>
</Card>
</div>
);
}
// Authorized
return <>{children}</>;
};
// ========================================
// MODERATOR ROUTE GUARD
// ========================================
/**
* ModeratorRoute - Requires moderator Tiki role
* Use for: Forum moderation, governance moderation
*
* @example
* <Route path="/moderate" element={
* <ModeratorRoute>
* <ModerationPanel />
* </ModeratorRoute>
* } />
*/
export const ModeratorRoute: React.FC<RouteGuardProps> = ({
children,
fallbackPath = '/',
}) => {
const { api, isApiReady, selectedAccount } = usePolkadot();
const [isModerator, setIsModerator] = useState<boolean | null>(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
const checkPermission = async () => {
if (!isApiReady || !api) {
setLoading(true);
return;
}
if (!selectedAccount?.address) {
setIsModerator(false);
setLoading(false);
return;
}
try {
const moderatorStatus = await checkModeratorRole(api, selectedAccount.address);
setIsModerator(moderatorStatus);
} catch (error) {
console.error('Moderator check failed:', error);
setIsModerator(false);
} finally {
setLoading(false);
}
};
checkPermission();
}, [api, isApiReady, selectedAccount]);
// Loading state
if (loading || !isApiReady) {
return <LoadingGuard />;
}
// Not connected to wallet
if (!selectedAccount) {
return <Navigate to="/" replace />;
}
// Not a moderator
if (isModerator === false) {
return (
<div className="min-h-screen bg-gray-950 flex items-center justify-center p-4">
<Card className="bg-gray-900 border-gray-800 max-w-md">
<CardContent className="p-8">
<Alert className="bg-red-900/20 border-red-500">
<Shield className="h-5 w-5 text-red-400" />
<AlertDescription className="text-gray-300">
<strong className="block mb-2">Moderator Access Required</strong>
You need moderator privileges to access this feature.
<div className="mt-4">
<Button
onClick={() => window.location.href = fallbackPath}
className="bg-green-600 hover:bg-green-700"
>
Go to Home
</Button>
</div>
</AlertDescription>
</Alert>
</CardContent>
</Card>
</div>
);
}
// Authorized
return <>{children}</>;
};
// ========================================
// ADMIN ROUTE GUARD (Supabase-based)
// ========================================
/**
* AdminRoute - Requires Supabase admin role
* Use for: Admin panel, system settings
* Note: This is separate from blockchain permissions
*/
export const AdminRoute: React.FC<RouteGuardProps> = ({
children,
fallbackPath = '/',
}) => {
const { user, isAdmin, loading } = useAuth();
// Loading state
if (loading) {
return <LoadingGuard />;
}
// Not logged in
if (!user) {
return <Navigate to="/login" replace />;
}
// Not admin
if (!isAdmin) {
return (
<div className="min-h-screen bg-gray-950 flex items-center justify-center p-4">
<Card className="bg-gray-900 border-gray-800 max-w-md">
<CardContent className="p-8">
<Alert className="bg-red-900/20 border-red-500">
<AlertCircle className="h-5 w-5 text-red-400" />
<AlertDescription className="text-gray-300">
<strong className="block mb-2">Admin Access Required</strong>
You do not have permission to access the admin panel.
<div className="mt-4">
<Button
onClick={() => window.location.href = fallbackPath}
className="bg-green-600 hover:bg-green-700"
>
Go to Home
</Button>
</div>
</AlertDescription>
</Alert>
</CardContent>
</Card>
</div>
);
}
// Authorized
return <>{children}</>;
};
-8
View File
@@ -13,7 +13,6 @@ import { ASSET_IDS, formatBalance, parseAmount } from '@pezkuwi/lib/wallet';
import { useToast } from '@/hooks/use-toast';
import { KurdistanSun } from './KurdistanSun';
import { PriceChart } from './trading/PriceChart';
import { LimitOrders } from './trading/LimitOrders';
// Available tokens for swap
const AVAILABLE_TOKENS = [
@@ -1107,13 +1106,6 @@ const TokenSwap = () => {
</div>
)}
</Card>
{/* Limit Orders Section */}
<LimitOrders
fromToken={fromToken}
toToken={toToken}
currentPrice={exchangeRate}
/>
</div>
<div>
@@ -13,6 +13,7 @@ import DelegateProfile from './DelegateProfile';
import { useDelegation } from '@/hooks/useDelegation';
import { usePolkadot } from '@/contexts/PolkadotContext';
import { formatNumber } from '@/lib/utils';
import { LoadingState } from '@pezkuwi/components/AsyncComponent';
const DelegationManager: React.FC = () => {
const { t } = useTranslation();
@@ -37,14 +38,7 @@ const DelegationManager: React.FC = () => {
};
if (loading) {
return (
<div className="container mx-auto px-4 py-8 max-w-7xl">
<div className="flex items-center justify-center py-12">
<Loader2 className="h-8 w-8 animate-spin text-green-600 mr-3" />
<span className="text-lg">Loading delegation data from blockchain...</span>
</div>
</div>
);
return <LoadingState message="Loading delegation data from blockchain..." />;
}
if (error) {
+2 -5
View File
@@ -7,6 +7,7 @@ import { TrendingUp, Droplet, BarChart3, Search, Plus } from 'lucide-react';
import { PoolInfo } from '@/types/dex';
import { fetchPools, formatTokenBalance } from '@pezkuwi/utils/dex';
import { isFounderWallet } from '@pezkuwi/utils/auth';
import { LoadingState } from '@pezkuwi/components/AsyncComponent';
interface PoolBrowserProps {
onAddLiquidity?: (pool: PoolInfo) => void;
@@ -63,11 +64,7 @@ export const PoolBrowser: React.FC<PoolBrowserProps> = ({
});
if (loading && pools.length === 0) {
return (
<div className="flex items-center justify-center py-12">
<div className="text-gray-400">Loading pools...</div>
</div>
);
return <LoadingState message="Loading liquidity pools..." />;
}
return (
+2 -6
View File
@@ -6,6 +6,7 @@ import { Badge } from '@/components/ui/badge';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { LoadingState } from '@pezkuwi/components/AsyncComponent';
import {
MessageSquare,
Users,
@@ -105,12 +106,7 @@ export function ForumOverview() {
}
if (loading) {
return (
<div className="flex items-center justify-center py-12">
<Loader2 className="h-8 w-8 animate-spin text-primary" />
<span className="ml-3 text-muted-foreground">Loading forum...</span>
</div>
);
return <LoadingState message="Loading forum..." />;
}
return (
@@ -9,6 +9,7 @@ import { Badge } from '../ui/badge';
import { Progress } from '../ui/progress';
import { usePolkadot } from '../../contexts/PolkadotContext';
import { formatBalance } from '@pezkuwi/lib/wallet';
import { LoadingState } from '@pezkuwi/components/AsyncComponent';
interface GovernanceStats {
activeProposals: number;
@@ -123,6 +124,10 @@ const GovernanceOverview: React.FC = () => {
}
};
if (loading) {
return <LoadingState message="Loading governance data..." />;
}
return (
<div className="space-y-6">
{/* Stats Grid */}
@@ -7,6 +7,7 @@ import { Progress } from '../ui/progress';
import { Alert, AlertDescription } from '../ui/alert';
import { useGovernance } from '@/hooks/useGovernance';
import { formatNumber } from '@/lib/utils';
import { LoadingState } from '@pezkuwi/components/AsyncComponent';
interface Proposal {
id: number;
@@ -84,12 +85,7 @@ const ProposalsList: React.FC = () => {
};
if (loading) {
return (
<div className="flex items-center justify-center py-12">
<Loader2 className="h-8 w-8 animate-spin text-primary mr-3" />
<span className="text-muted-foreground">Loading proposals from blockchain...</span>
</div>
);
return <LoadingState message="Loading proposals from blockchain..." />;
}
if (error) {
-798
View File
@@ -1,798 +0,0 @@
import React, { useState } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Badge } from '@/components/ui/badge';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { ArrowUpDown, Search, Filter, TrendingUp, TrendingDown, User, Shield, Clock, DollarSign, Plus, X, SlidersHorizontal, Lock, CheckCircle, AlertCircle } from 'lucide-react';
import { useTranslation } from 'react-i18next';
interface P2POffer {
id: string;
type: 'buy' | 'sell';
token: 'HEZ' | 'PEZ';
amount: number;
price: number;
paymentMethod: string;
seller: {
name: string;
rating: number;
completedTrades: number;
verified: boolean;
};
minOrder: number;
maxOrder: number;
timeLimit: number;
}
export const P2PMarket: React.FC = () => {
const { t } = useTranslation();
const [activeTab, setActiveTab] = useState<'buy' | 'sell'>('buy');
const [selectedToken, setSelectedToken] = useState<'HEZ' | 'PEZ'>('HEZ');
const [searchTerm, setSearchTerm] = useState('');
const [selectedOffer, setSelectedOffer] = useState<P2POffer | null>(null);
const [tradeAmount, setTradeAmount] = useState('');
// Advanced filters
const [paymentMethodFilter, setPaymentMethodFilter] = useState<string>('all');
const [minPrice, setMinPrice] = useState<string>('');
const [maxPrice, setMaxPrice] = useState<string>('');
const [sortBy, setSortBy] = useState<'price' | 'rating' | 'trades'>('price');
const [showFilters, setShowFilters] = useState(false);
// Order creation
const [showCreateOrder, setShowCreateOrder] = useState(false);
const [newOrderAmount, setNewOrderAmount] = useState('');
const [newOrderPrice, setNewOrderPrice] = useState('');
const [newOrderPaymentMethod, setNewOrderPaymentMethod] = useState('Bank Transfer');
const offers: P2POffer[] = [
{
id: '1',
type: 'sell',
token: 'HEZ',
amount: 10000,
price: 0.95,
paymentMethod: 'Bank Transfer',
seller: {
name: 'CryptoTrader',
rating: 4.8,
completedTrades: 234,
verified: true
},
minOrder: 100,
maxOrder: 5000,
timeLimit: 30
},
{
id: '2',
type: 'sell',
token: 'HEZ',
amount: 5000,
price: 0.96,
paymentMethod: 'PayPal',
seller: {
name: 'TokenMaster',
rating: 4.9,
completedTrades: 567,
verified: true
},
minOrder: 50,
maxOrder: 2000,
timeLimit: 15
},
{
id: '3',
type: 'buy',
token: 'PEZ',
amount: 15000,
price: 1.02,
paymentMethod: 'Crypto',
seller: {
name: 'PezWhale',
rating: 4.7,
completedTrades: 123,
verified: false
},
minOrder: 500,
maxOrder: 10000,
timeLimit: 60
},
{
id: '4',
type: 'sell',
token: 'PEZ',
amount: 8000,
price: 1.01,
paymentMethod: 'Wire Transfer',
seller: {
name: 'QuickTrade',
rating: 4.6,
completedTrades: 89,
verified: true
},
minOrder: 200,
maxOrder: 3000,
timeLimit: 45
}
];
// Payment methods list
const paymentMethods = ['Bank Transfer', 'PayPal', 'Crypto', 'Wire Transfer', 'Cash', 'Mobile Money'];
// Advanced filtering and sorting
const filteredOffers = offers
.filter(offer => {
// Basic filters
if (offer.type !== activeTab) return false;
if (offer.token !== selectedToken) return false;
if (searchTerm && !offer.seller.name.toLowerCase().includes(searchTerm.toLowerCase())) return false;
// Payment method filter
if (paymentMethodFilter !== 'all' && offer.paymentMethod !== paymentMethodFilter) return false;
// Price range filter
if (minPrice && offer.price < parseFloat(minPrice)) return false;
if (maxPrice && offer.price > parseFloat(maxPrice)) return false;
return true;
})
.sort((a, b) => {
// Sorting logic
if (sortBy === 'price') {
return activeTab === 'buy' ? a.price - b.price : b.price - a.price;
} else if (sortBy === 'rating') {
return b.seller.rating - a.seller.rating;
} else if (sortBy === 'trades') {
return b.seller.completedTrades - a.seller.completedTrades;
}
return 0;
});
// Escrow state
const [showEscrow, setShowEscrow] = useState(false);
const [escrowStep, setEscrowStep] = useState<'funding' | 'confirmation' | 'release'>('funding');
const [escrowOffer, setEscrowOffer] = useState<P2POffer | null>(null);
const handleTrade = (offer: P2POffer) => {
console.log('Initiating trade:', tradeAmount, offer.token, 'with', offer.seller.name);
setEscrowOffer(offer);
setShowEscrow(true);
setEscrowStep('funding');
};
const handleEscrowFund = () => {
console.log('Funding escrow with:', tradeAmount, escrowOffer?.token);
setEscrowStep('confirmation');
};
const handleEscrowConfirm = () => {
console.log('Confirming payment received');
setEscrowStep('release');
};
const handleEscrowRelease = () => {
console.log('Releasing escrow funds');
setShowEscrow(false);
setSelectedOffer(null);
setEscrowOffer(null);
setEscrowStep('funding');
};
return (
<div className="space-y-6">
{/* Market Stats */}
<div className="grid grid-cols-1 md:grid-cols-4 gap-4">
<Card className="bg-gray-900 border-gray-800">
<CardHeader className="pb-3">
<CardTitle className="text-sm text-gray-400">HEZ Price</CardTitle>
</CardHeader>
<CardContent>
<div className="text-2xl font-bold text-white">$0.95</div>
<div className="flex items-center text-green-500 text-xs mt-1">
<TrendingUp className="w-3 h-3 mr-1" />
+2.3%
</div>
</CardContent>
</Card>
<Card className="bg-gray-900 border-gray-800">
<CardHeader className="pb-3">
<CardTitle className="text-sm text-gray-400">PEZ Price</CardTitle>
</CardHeader>
<CardContent>
<div className="text-2xl font-bold text-white">$1.02</div>
<div className="flex items-center text-red-500 text-xs mt-1">
<TrendingDown className="w-3 h-3 mr-1" />
-0.8%
</div>
</CardContent>
</Card>
<Card className="bg-gray-900 border-gray-800">
<CardHeader className="pb-3">
<CardTitle className="text-sm text-gray-400">24h Volume</CardTitle>
</CardHeader>
<CardContent>
<div className="text-2xl font-bold text-white">$2.4M</div>
<p className="text-xs text-gray-500 mt-1">1,234 trades</p>
</CardContent>
</Card>
<Card className="bg-gray-900 border-gray-800">
<CardHeader className="pb-3">
<CardTitle className="text-sm text-gray-400">Active Offers</CardTitle>
</CardHeader>
<CardContent>
<div className="text-2xl font-bold text-white">342</div>
<p className="text-xs text-gray-500 mt-1">89 verified sellers</p>
</CardContent>
</Card>
</div>
{/* P2P Trading Interface */}
<Card className="bg-gray-900 border-gray-800">
<CardHeader>
<CardTitle className="text-xl text-white">P2P Market</CardTitle>
<CardDescription className="text-gray-400">
Buy and sell tokens directly with other users
</CardDescription>
</CardHeader>
<CardContent>
<div className="space-y-4">
{/* Top Action Bar */}
<div className="flex justify-between items-center">
<Button
onClick={() => setShowCreateOrder(true)}
className="bg-green-600 hover:bg-green-700"
>
<Plus className="w-4 h-4 mr-2" />
Create Order
</Button>
<Button
variant="outline"
onClick={() => setShowFilters(!showFilters)}
className="border-gray-700"
>
<SlidersHorizontal className="w-4 h-4 mr-2" />
{showFilters ? 'Hide Filters' : 'Show Filters'}
</Button>
</div>
{/* Basic Filters */}
<div className="flex flex-wrap gap-4">
<Tabs value={activeTab} onValueChange={(v) => setActiveTab(v as 'buy' | 'sell')} className="flex-1">
<TabsList className="grid w-full max-w-[200px] grid-cols-2">
<TabsTrigger value="buy">Buy</TabsTrigger>
<TabsTrigger value="sell">Sell</TabsTrigger>
</TabsList>
</Tabs>
<Select value={selectedToken} onValueChange={(v) => setSelectedToken(v as 'HEZ' | 'PEZ')}>
<SelectTrigger className="w-[120px] bg-gray-800 border-gray-700">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="HEZ">HEZ</SelectItem>
<SelectItem value="PEZ">PEZ</SelectItem>
</SelectContent>
</Select>
<div className="flex-1 max-w-xs">
<div className="relative">
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
<Input
placeholder="Search sellers..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
className="pl-10 bg-gray-800 border-gray-700"
/>
</div>
</div>
{/* Sort Selector */}
<Select value={sortBy} onValueChange={(v) => setSortBy(v as 'price' | 'rating' | 'trades')}>
<SelectTrigger className="w-[150px] bg-gray-800 border-gray-700">
<SelectValue placeholder="Sort by" />
</SelectTrigger>
<SelectContent>
<SelectItem value="price">Price</SelectItem>
<SelectItem value="rating">Rating</SelectItem>
<SelectItem value="trades">Trades</SelectItem>
</SelectContent>
</Select>
</div>
{/* Advanced Filters Panel (Binance P2P style) */}
{showFilters && (
<Card className="bg-gray-800 border-gray-700 p-4">
<div className="space-y-4">
<h4 className="font-semibold text-white flex items-center gap-2">
<Filter className="w-4 h-4" />
Advanced Filters
</h4>
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
{/* Payment Method Filter */}
<div>
<Label className="text-sm text-gray-400">Payment Method</Label>
<Select value={paymentMethodFilter} onValueChange={setPaymentMethodFilter}>
<SelectTrigger className="bg-gray-900 border-gray-700">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">All Methods</SelectItem>
{paymentMethods.map(method => (
<SelectItem key={method} value={method}>{method}</SelectItem>
))}
</SelectContent>
</Select>
</div>
{/* Min Price Filter */}
<div>
<Label className="text-sm text-gray-400">Min Price ($)</Label>
<Input
type="number"
placeholder="Min"
value={minPrice}
onChange={(e) => setMinPrice(e.target.value)}
className="bg-gray-900 border-gray-700"
/>
</div>
{/* Max Price Filter */}
<div>
<Label className="text-sm text-gray-400">Max Price ($)</Label>
<Input
type="number"
placeholder="Max"
value={maxPrice}
onChange={(e) => setMaxPrice(e.target.value)}
className="bg-gray-900 border-gray-700"
/>
</div>
</div>
{/* Clear Filters Button */}
<Button
variant="outline"
size="sm"
onClick={() => {
setPaymentMethodFilter('all');
setMinPrice('');
setMaxPrice('');
setSearchTerm('');
}}
className="border-gray-700"
>
<X className="w-3 h-3 mr-1" />
Clear All Filters
</Button>
</div>
</Card>
)}
{/* Offers List */}
<div className="space-y-3">
{filteredOffers.map((offer) => (
<Card key={offer.id} className="bg-gray-800 border-gray-700">
<CardContent className="p-4">
<div className="flex items-center justify-between">
<div className="flex items-center space-x-4">
<div className="w-10 h-10 bg-gray-700 rounded-full flex items-center justify-center">
<User className="w-5 h-5 text-gray-400" />
</div>
<div>
<div className="flex items-center gap-2">
<span className="font-semibold text-white">{offer.seller.name}</span>
{offer.seller.verified && (
<Badge variant="secondary" className="bg-blue-600/20 text-blue-400">
<Shield className="w-3 h-3 mr-1" />
Verified
</Badge>
)}
</div>
<div className="flex items-center gap-3 text-sm text-gray-400">
<span> {offer.seller.rating}</span>
<span>{offer.seller.completedTrades} trades</span>
<span>{offer.paymentMethod}</span>
</div>
</div>
</div>
<div className="text-right space-y-1">
<div className="text-lg font-bold text-white">
${offer.price} / {offer.token}
</div>
<div className="text-sm text-gray-400">
Available: {offer.amount.toLocaleString()} {offer.token}
</div>
<div className="text-xs text-gray-500">
Limits: {offer.minOrder} - {offer.maxOrder} {offer.token}
</div>
</div>
<Button
className="ml-4 bg-green-600 hover:bg-green-700"
onClick={() => setSelectedOffer(offer)}
>
{activeTab === 'buy' ? 'Buy' : 'Sell'} {offer.token}
</Button>
</div>
</CardContent>
</Card>
))}
</div>
</div>
</CardContent>
</Card>
{/* Trade Modal */}
{selectedOffer && (
<Card className="bg-gray-900 border-gray-800">
<CardHeader>
<CardTitle>
{activeTab === 'buy' ? 'Buy' : 'Sell'} {selectedOffer.token} from {selectedOffer.seller.name}
</CardTitle>
<CardDescription>Complete your P2P trade</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div>
<Label>Amount ({selectedOffer.token})</Label>
<Input
type="number"
placeholder={`Min: ${selectedOffer.minOrder}, Max: ${selectedOffer.maxOrder}`}
value={tradeAmount}
onChange={(e) => setTradeAmount(e.target.value)}
className="bg-gray-800 border-gray-700"
/>
</div>
<div className="bg-gray-800 p-4 rounded-lg space-y-2">
<div className="flex justify-between text-sm">
<span className="text-gray-400">Price per {selectedOffer.token}</span>
<span className="text-white">${selectedOffer.price}</span>
</div>
<div className="flex justify-between text-sm">
<span className="text-gray-400">Total Amount</span>
<span className="text-white font-semibold">
${(parseFloat(tradeAmount || '0') * selectedOffer.price).toFixed(2)}
</span>
</div>
<div className="flex justify-between text-sm">
<span className="text-gray-400">Payment Method</span>
<span className="text-white">{selectedOffer.paymentMethod}</span>
</div>
<div className="flex justify-between text-sm">
<span className="text-gray-400">Time Limit</span>
<span className="text-white">{selectedOffer.timeLimit} minutes</span>
</div>
</div>
<div className="flex gap-3">
<Button
className="flex-1 bg-green-600 hover:bg-green-700"
onClick={() => handleTrade(selectedOffer)}
>
Confirm {activeTab === 'buy' ? 'Purchase' : 'Sale'}
</Button>
<Button
variant="outline"
className="flex-1"
onClick={() => setSelectedOffer(null)}
>
Cancel
</Button>
</div>
</CardContent>
</Card>
)}
{/* Create Order Modal (Binance P2P style) */}
{showCreateOrder && (
<Card className="bg-gray-900 border-gray-800 fixed top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 z-50 w-full max-w-md">
<CardHeader>
<div className="flex justify-between items-center">
<CardTitle>Create P2P Order</CardTitle>
<Button variant="ghost" size="icon" onClick={() => setShowCreateOrder(false)}>
<X className="w-4 h-4" />
</Button>
</div>
<CardDescription>
Create a {activeTab === 'buy' ? 'buy' : 'sell'} order for {selectedToken}
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div>
<Label>Order Type</Label>
<Tabs value={activeTab} onValueChange={(v) => setActiveTab(v as 'buy' | 'sell')}>
<TabsList className="grid w-full grid-cols-2">
<TabsTrigger value="buy">Buy</TabsTrigger>
<TabsTrigger value="sell">Sell</TabsTrigger>
</TabsList>
</Tabs>
</div>
<div>
<Label>Token</Label>
<Select value={selectedToken} onValueChange={(v) => setSelectedToken(v as 'HEZ' | 'PEZ')}>
<SelectTrigger className="bg-gray-800 border-gray-700">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="HEZ">HEZ</SelectItem>
<SelectItem value="PEZ">PEZ</SelectItem>
</SelectContent>
</Select>
</div>
<div>
<Label>Amount ({selectedToken})</Label>
<Input
type="number"
placeholder="Enter amount"
value={newOrderAmount}
onChange={(e) => setNewOrderAmount(e.target.value)}
className="bg-gray-800 border-gray-700"
/>
</div>
<div>
<Label>Price per {selectedToken} ($)</Label>
<Input
type="number"
placeholder="Enter price"
value={newOrderPrice}
onChange={(e) => setNewOrderPrice(e.target.value)}
className="bg-gray-800 border-gray-700"
/>
</div>
<div>
<Label>Payment Method</Label>
<Select value={newOrderPaymentMethod} onValueChange={setNewOrderPaymentMethod}>
<SelectTrigger className="bg-gray-800 border-gray-700">
<SelectValue />
</SelectTrigger>
<SelectContent>
{paymentMethods.map(method => (
<SelectItem key={method} value={method}>{method}</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="bg-gray-800 p-3 rounded-lg">
<div className="flex justify-between text-sm">
<span className="text-gray-400">Total Value</span>
<span className="text-white font-semibold">
${(parseFloat(newOrderAmount || '0') * parseFloat(newOrderPrice || '0')).toFixed(2)}
</span>
</div>
</div>
<div className="flex gap-3">
<Button
className="flex-1 bg-green-600 hover:bg-green-700"
onClick={() => {
console.log('Creating order:', {
type: activeTab,
token: selectedToken,
amount: newOrderAmount,
price: newOrderPrice,
paymentMethod: newOrderPaymentMethod
});
// TODO: Implement blockchain integration
setShowCreateOrder(false);
}}
>
Create Order
</Button>
<Button
variant="outline"
className="flex-1"
onClick={() => setShowCreateOrder(false)}
>
Cancel
</Button>
</div>
<div className="text-xs text-gray-500 text-center">
Note: Blockchain integration for P2P orders is coming soon
</div>
</CardContent>
</Card>
)}
{/* Escrow Modal (Binance P2P Escrow style) */}
{showEscrow && escrowOffer && (
<Card className="bg-gray-900 border-gray-800 fixed top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 z-50 w-full max-w-2xl">
<CardHeader>
<div className="flex justify-between items-center">
<CardTitle className="flex items-center gap-2">
<Lock className="w-5 h-5 text-blue-400" />
Secure Escrow Trade
</CardTitle>
<Button variant="ghost" size="icon" onClick={() => setShowEscrow(false)}>
<X className="w-4 h-4" />
</Button>
</div>
<CardDescription>
Trade safely with escrow protection {activeTab === 'buy' ? 'Buying' : 'Selling'} {escrowOffer.token}
</CardDescription>
</CardHeader>
<CardContent className="space-y-6">
{/* Escrow Steps Indicator */}
<div className="flex justify-between items-center">
{[
{ step: 'funding', label: 'Fund Escrow', icon: Lock },
{ step: 'confirmation', label: 'Payment', icon: Clock },
{ step: 'release', label: 'Complete', icon: CheckCircle }
].map((item, idx) => (
<div key={item.step} className="flex-1 flex flex-col items-center">
<div className={`w-10 h-10 rounded-full flex items-center justify-center ${
escrowStep === item.step ? 'bg-blue-600' :
['funding', 'confirmation', 'release'].indexOf(escrowStep) > idx ? 'bg-green-600' : 'bg-gray-700'
}`}>
<item.icon className="w-5 h-5 text-white" />
</div>
<span className="text-xs text-gray-400 mt-2">{item.label}</span>
{idx < 2 && (
<div className={`absolute w-32 h-0.5 mt-5 ${
['funding', 'confirmation', 'release'].indexOf(escrowStep) > idx ? 'bg-green-600' : 'bg-gray-700'
}`} style={{ left: `calc(${(idx + 1) * 33.33}% - 64px)` }}></div>
)}
</div>
))}
</div>
{/* Trade Details Card */}
<Card className="bg-gray-800 border-gray-700 p-4">
<h4 className="font-semibold text-white mb-3">Trade Details</h4>
<div className="space-y-2 text-sm">
<div className="flex justify-between">
<span className="text-gray-400">Seller</span>
<span className="text-white font-semibold">{escrowOffer.seller.name}</span>
</div>
<div className="flex justify-between">
<span className="text-gray-400">Amount</span>
<span className="text-white font-semibold">{tradeAmount} {escrowOffer.token}</span>
</div>
<div className="flex justify-between">
<span className="text-gray-400">Price per {escrowOffer.token}</span>
<span className="text-white font-semibold">${escrowOffer.price}</span>
</div>
<div className="flex justify-between">
<span className="text-gray-400">Payment Method</span>
<span className="text-white font-semibold">{escrowOffer.paymentMethod}</span>
</div>
<div className="flex justify-between pt-2 border-t border-gray-700">
<span className="text-gray-400">Total</span>
<span className="text-lg font-bold text-white">
${(parseFloat(tradeAmount || '0') * escrowOffer.price).toFixed(2)}
</span>
</div>
</div>
</Card>
{/* Step Content */}
{escrowStep === 'funding' && (
<div className="space-y-4">
<div className="bg-blue-900/20 border border-blue-500/30 rounded-lg p-4">
<div className="flex gap-3">
<Shield className="w-5 h-5 text-blue-400 flex-shrink-0 mt-0.5" />
<div className="text-sm text-blue-200">
<strong>Escrow Protection:</strong> Your funds will be held securely in smart contract escrow until both parties confirm the trade. This protects both buyer and seller.
</div>
</div>
</div>
<div className="text-sm text-gray-400">
1. Fund the escrow with {tradeAmount} {escrowOffer.token}<br />
2. Wait for seller to provide payment details<br />
3. Complete payment via {escrowOffer.paymentMethod}<br />
4. Confirm payment to release escrow
</div>
<Button
onClick={handleEscrowFund}
className="w-full bg-blue-600 hover:bg-blue-700"
>
Fund Escrow ({tradeAmount} {escrowOffer.token})
</Button>
</div>
)}
{escrowStep === 'confirmation' && (
<div className="space-y-4">
<div className="bg-yellow-900/20 border border-yellow-500/30 rounded-lg p-4">
<div className="flex gap-3">
<Clock className="w-5 h-5 text-yellow-400 flex-shrink-0 mt-0.5" />
<div className="text-sm text-yellow-200">
<strong>Waiting for Payment:</strong> Complete your {escrowOffer.paymentMethod} payment and click confirm when done. Do not release escrow until payment is verified!
</div>
</div>
</div>
<Card className="bg-gray-800 border-gray-700 p-4">
<h4 className="font-semibold text-white mb-2">Payment Instructions</h4>
<div className="text-sm text-gray-300 space-y-1">
<p> Payment Method: {escrowOffer.paymentMethod}</p>
<p> Amount: ${(parseFloat(tradeAmount || '0') * escrowOffer.price).toFixed(2)}</p>
<p> Time Limit: {escrowOffer.timeLimit} minutes</p>
</div>
</Card>
<div className="flex gap-3">
<Button
variant="outline"
onClick={() => {
setShowEscrow(false);
setEscrowStep('funding');
}}
className="flex-1"
>
Cancel Trade
</Button>
<Button
onClick={handleEscrowConfirm}
className="flex-1 bg-green-600 hover:bg-green-700"
>
I've Made Payment
</Button>
</div>
</div>
)}
{escrowStep === 'release' && (
<div className="space-y-4">
<div className="bg-green-900/20 border border-green-500/30 rounded-lg p-4">
<div className="flex gap-3">
<CheckCircle className="w-5 h-5 text-green-400 flex-shrink-0 mt-0.5" />
<div className="text-sm text-green-200">
<strong>Payment Confirmed:</strong> Your payment has been verified. The escrow will be released to the seller automatically.
</div>
</div>
</div>
<Card className="bg-gray-800 border-gray-700 p-4">
<h4 className="font-semibold text-white mb-2">Trade Summary</h4>
<div className="text-sm text-gray-300 space-y-1">
<p>✅ Escrow Funded: {tradeAmount} {escrowOffer.token}</p>
<p>✅ Payment Sent: ${(parseFloat(tradeAmount || '0') * escrowOffer.price).toFixed(2)}</p>
<p> Payment Verified</p>
<p className="text-green-400 font-semibold mt-2">🎉 Trade Completed Successfully!</p>
</div>
</Card>
<Button
onClick={handleEscrowRelease}
className="w-full bg-green-600 hover:bg-green-700"
>
Close & Release Escrow
</Button>
</div>
)}
<div className="text-xs text-gray-500 text-center">
Note: Smart contract escrow integration coming soon
</div>
</CardContent>
</Card>
)}
{/* Overlay */}
{(showCreateOrder || selectedOffer || showEscrow) && (
<div className="fixed inset-0 bg-black/50 backdrop-blur-sm z-40" onClick={() => {
setShowCreateOrder(false);
setSelectedOffer(null);
setShowEscrow(false);
}}></div>
)}
</div>
);
};
+11 -46
View File
@@ -21,6 +21,8 @@ import {
parseAmount,
type StakingInfo
} from '@pezkuwi/lib/staking';
import { LoadingState } from '@pezkuwi/components/AsyncComponent';
import { handleBlockchainError, handleBlockchainSuccess } from '@pezkuwi/lib/error-handler';
export const StakingDashboard: React.FC = () => {
const { t } = useTranslation();
@@ -119,22 +121,10 @@ export const StakingDashboard: React.FC = () => {
console.log('Transaction in block:', status.asInBlock.toHex());
if (dispatchError) {
let errorMessage = 'Transaction failed';
if (dispatchError.isModule) {
const decoded = api.registry.findMetaError(dispatchError.asModule);
errorMessage = `${decoded.section}.${decoded.name}: ${decoded.docs.join(' ')}`;
}
toast({
title: 'Error',
description: errorMessage,
variant: 'destructive',
});
handleBlockchainError(dispatchError, api, toast);
setIsLoading(false);
} else {
toast({
title: 'Success',
description: `Bonded ${bondAmount} HEZ successfully`,
});
handleBlockchainSuccess('staking.bonded', toast, { amount: bondAmount });
setBondAmount('');
refreshBalances();
// Refresh staking data after a delay
@@ -183,22 +173,10 @@ export const StakingDashboard: React.FC = () => {
({ status, dispatchError }) => {
if (status.isInBlock) {
if (dispatchError) {
let errorMessage = 'Nomination failed';
if (dispatchError.isModule) {
const decoded = api.registry.findMetaError(dispatchError.asModule);
errorMessage = `${decoded.section}.${decoded.name}: ${decoded.docs.join(' ')}`;
}
toast({
title: 'Error',
description: errorMessage,
variant: 'destructive',
});
handleBlockchainError(dispatchError, api, toast);
setIsLoading(false);
} else {
toast({
title: 'Success',
description: `Nominated ${selectedValidators.length} validator(s)`,
});
handleBlockchainSuccess('staking.nominated', toast, { count: selectedValidators.length.toString() });
// Refresh staking data
setTimeout(() => {
if (api && selectedAccount) {
@@ -241,21 +219,12 @@ export const StakingDashboard: React.FC = () => {
({ status, dispatchError }) => {
if (status.isInBlock) {
if (dispatchError) {
let errorMessage = 'Unbond failed';
if (dispatchError.isModule) {
const decoded = api.registry.findMetaError(dispatchError.asModule);
errorMessage = `${decoded.section}.${decoded.name}: ${decoded.docs.join(' ')}`;
}
toast({
title: 'Error',
description: errorMessage,
variant: 'destructive',
});
handleBlockchainError(dispatchError, api, toast);
setIsLoading(false);
} else {
toast({
title: 'Success',
description: `Unbonded ${unbondAmount} HEZ. Withdrawal available in ${bondingDuration} eras`,
handleBlockchainSuccess('staking.unbonded', toast, {
amount: unbondAmount,
duration: bondingDuration.toString()
});
setUnbondAmount('');
setTimeout(() => {
@@ -421,11 +390,7 @@ export const StakingDashboard: React.FC = () => {
};
if (isLoadingData) {
return (
<div className="flex items-center justify-center h-64">
<div className="text-gray-400">Loading staking data...</div>
</div>
);
return <LoadingState message="Loading staking data..." />;
}
return (
-306
View File
@@ -1,306 +0,0 @@
import React, { useState } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { X, Clock, CheckCircle, AlertCircle } from 'lucide-react';
interface LimitOrder {
id: string;
type: 'buy' | 'sell';
fromToken: string;
toToken: string;
fromAmount: number;
limitPrice: number;
currentPrice: number;
status: 'pending' | 'filled' | 'cancelled' | 'expired';
createdAt: number;
expiresAt: number;
}
interface LimitOrdersProps {
fromToken: string;
toToken: string;
currentPrice: number;
onCreateOrder?: (order: Omit<LimitOrder, 'id' | 'status' | 'createdAt' | 'expiresAt'>) => void;
}
export const LimitOrders: React.FC<LimitOrdersProps> = ({
fromToken,
toToken,
currentPrice,
onCreateOrder
}) => {
const [orderType, setOrderType] = useState<'buy' | 'sell'>('buy');
const [amount, setAmount] = useState('');
const [limitPrice, setLimitPrice] = useState('');
const [showCreateForm, setShowCreateForm] = useState(false);
// Mock orders (in production, fetch from blockchain)
const [orders, setOrders] = useState<LimitOrder[]>([
{
id: '1',
type: 'buy',
fromToken: 'PEZ',
toToken: 'HEZ',
fromAmount: 100,
limitPrice: 0.98,
currentPrice: 1.02,
status: 'pending',
createdAt: Date.now() - 3600000,
expiresAt: Date.now() + 82800000
},
{
id: '2',
type: 'sell',
fromToken: 'HEZ',
toToken: 'PEZ',
fromAmount: 50,
limitPrice: 1.05,
currentPrice: 1.02,
status: 'pending',
createdAt: Date.now() - 7200000,
expiresAt: Date.now() + 79200000
}
]);
const handleCreateOrder = () => {
const newOrder: Omit<LimitOrder, 'id' | 'status' | 'createdAt' | 'expiresAt'> = {
type: orderType,
fromToken: orderType === 'buy' ? toToken : fromToken,
toToken: orderType === 'buy' ? fromToken : toToken,
fromAmount: parseFloat(amount),
limitPrice: parseFloat(limitPrice),
currentPrice
};
console.log('Creating limit order:', newOrder);
// Add to orders list (mock)
const order: LimitOrder = {
...newOrder,
id: Date.now().toString(),
status: 'pending',
createdAt: Date.now(),
expiresAt: Date.now() + 86400000 // 24 hours
};
setOrders([order, ...orders]);
setShowCreateForm(false);
setAmount('');
setLimitPrice('');
if (onCreateOrder) {
onCreateOrder(newOrder);
}
};
const handleCancelOrder = (orderId: string) => {
setOrders(orders.map(order =>
order.id === orderId ? { ...order, status: 'cancelled' as const } : order
));
};
const getStatusBadge = (status: LimitOrder['status']) => {
switch (status) {
case 'pending':
return <Badge variant="outline" className="bg-yellow-500/10 text-yellow-400 border-yellow-500/30">
<Clock className="w-3 h-3 mr-1" />
Pending
</Badge>;
case 'filled':
return <Badge variant="outline" className="bg-green-500/10 text-green-400 border-green-500/30">
<CheckCircle className="w-3 h-3 mr-1" />
Filled
</Badge>;
case 'cancelled':
return <Badge variant="outline" className="bg-gray-500/10 text-gray-400 border-gray-500/30">
<X className="w-3 h-3 mr-1" />
Cancelled
</Badge>;
case 'expired':
return <Badge variant="outline" className="bg-red-500/10 text-red-400 border-red-500/30">
<AlertCircle className="w-3 h-3 mr-1" />
Expired
</Badge>;
}
};
const getPriceDistance = (order: LimitOrder) => {
const distance = ((order.limitPrice - order.currentPrice) / order.currentPrice) * 100;
return distance;
};
return (
<Card className="bg-gray-900 border-gray-800">
<CardHeader>
<div className="flex justify-between items-center">
<div>
<CardTitle>Limit Orders</CardTitle>
<CardDescription>
Set orders to execute at your target price
</CardDescription>
</div>
<Button
onClick={() => setShowCreateForm(!showCreateForm)}
className="bg-blue-600 hover:bg-blue-700"
>
{showCreateForm ? 'Cancel' : '+ New Order'}
</Button>
</div>
</CardHeader>
<CardContent className="space-y-4">
{showCreateForm && (
<Card className="bg-gray-800 border-gray-700 p-4">
<div className="space-y-4">
<div>
<Label>Order Type</Label>
<Tabs value={orderType} onValueChange={(v) => setOrderType(v as 'buy' | 'sell')}>
<TabsList className="grid w-full grid-cols-2">
<TabsTrigger value="buy">Buy {fromToken}</TabsTrigger>
<TabsTrigger value="sell">Sell {fromToken}</TabsTrigger>
</TabsList>
</Tabs>
</div>
<div>
<Label>Amount ({orderType === 'buy' ? toToken : fromToken})</Label>
<Input
type="number"
placeholder="0.0"
value={amount}
onChange={(e) => setAmount(e.target.value)}
className="bg-gray-900 border-gray-700"
/>
</div>
<div>
<Label>Limit Price (1 {fromToken} = ? {toToken})</Label>
<Input
type="number"
placeholder="0.0"
value={limitPrice}
onChange={(e) => setLimitPrice(e.target.value)}
className="bg-gray-900 border-gray-700"
/>
<div className="text-xs text-gray-500 mt-1">
Current market price: ${currentPrice.toFixed(4)}
</div>
</div>
<div className="bg-gray-900 p-3 rounded-lg space-y-1">
<div className="flex justify-between text-sm">
<span className="text-gray-400">You will {orderType}</span>
<span className="text-white font-semibold">
{amount || '0'} {orderType === 'buy' ? fromToken : toToken}
</span>
</div>
<div className="flex justify-between text-sm">
<span className="text-gray-400">When price reaches</span>
<span className="text-white font-semibold">
${limitPrice || '0'} per {fromToken}
</span>
</div>
<div className="flex justify-between text-sm">
<span className="text-gray-400">Estimated total</span>
<span className="text-white font-semibold">
{((parseFloat(amount || '0') * parseFloat(limitPrice || '0'))).toFixed(2)} {orderType === 'buy' ? toToken : fromToken}
</span>
</div>
</div>
<Button
onClick={handleCreateOrder}
disabled={!amount || !limitPrice}
className="w-full bg-green-600 hover:bg-green-700"
>
Create Limit Order
</Button>
<div className="text-xs text-gray-500 text-center">
Order will expire in 24 hours if not filled
</div>
</div>
</Card>
)}
{/* Orders List */}
<div className="space-y-3">
{orders.length === 0 ? (
<div className="text-center py-8 text-gray-400">
No limit orders yet. Create one to get started!
</div>
) : (
orders.map(order => {
const priceDistance = getPriceDistance(order);
return (
<Card key={order.id} className="bg-gray-800 border-gray-700 p-4">
<div className="flex items-start justify-between mb-3">
<div className="flex items-center gap-2">
<Badge variant={order.type === 'buy' ? 'default' : 'secondary'}>
{order.type.toUpperCase()}
</Badge>
<span className="font-semibold text-white">
{order.fromToken} {order.toToken}
</span>
</div>
{getStatusBadge(order.status)}
</div>
<div className="grid grid-cols-2 gap-4 text-sm mb-3">
<div>
<div className="text-gray-400">Amount</div>
<div className="text-white font-semibold">
{order.fromAmount} {order.fromToken}
</div>
</div>
<div>
<div className="text-gray-400">Limit Price</div>
<div className="text-white font-semibold">
${order.limitPrice.toFixed(4)}
</div>
</div>
<div>
<div className="text-gray-400">Current Price</div>
<div className="text-white">
${order.currentPrice.toFixed(4)}
</div>
</div>
<div>
<div className="text-gray-400">Distance</div>
<div className={priceDistance > 0 ? 'text-green-400' : 'text-red-400'}>
{priceDistance > 0 ? '+' : ''}{priceDistance.toFixed(2)}%
</div>
</div>
</div>
<div className="flex items-center justify-between text-xs text-gray-500">
<span>
Created {new Date(order.createdAt).toLocaleString()}
</span>
{order.status === 'pending' && (
<Button
variant="ghost"
size="sm"
onClick={() => handleCancelOrder(order.id)}
className="h-7 text-red-400 hover:text-red-300 hover:bg-red-500/10"
>
Cancel
</Button>
)}
</div>
</Card>
);
})
)}
</div>
<div className="text-xs text-gray-500 text-center pt-2">
Note: Limit orders require blockchain integration to execute automatically
</div>
</CardContent>
</Card>
);
};
@@ -20,6 +20,7 @@ import {
ArrowDownRight,
Loader2
} from 'lucide-react';
import { LoadingState } from '@pezkuwi/components/AsyncComponent';
interface TreasuryMetrics {
totalBalance: number;
@@ -63,12 +64,7 @@ export const TreasuryOverview: React.FC = () => {
const HealthIcon = healthStatus.icon;
if (loading) {
return (
<div className="flex items-center justify-center py-12">
<Loader2 className="h-8 w-8 animate-spin text-primary" />
<span className="ml-3 text-muted-foreground">Loading treasury data from blockchain...</span>
</div>
);
return <LoadingState message="Loading treasury data from blockchain..." />;
}
if (error) {
+68 -65
View File
@@ -1,7 +1,12 @@
import React, { createContext, useContext, useEffect, useState } from 'react';
import React, { createContext, useContext, useEffect, useState, useCallback } from 'react';
import { supabase } from '@/lib/supabase';
import { User } from '@supabase/supabase-js';
// Session timeout configuration
const SESSION_TIMEOUT_MS = 30 * 60 * 1000; // 30 minutes
const ACTIVITY_CHECK_INTERVAL_MS = 60 * 1000; // Check every 1 minute
const LAST_ACTIVITY_KEY = 'last_activity_timestamp';
interface AuthContextType {
user: User | null;
loading: boolean;
@@ -12,23 +17,6 @@ interface AuthContextType {
checkAdminStatus: () => Promise<boolean>;
}
// Demo/Founder account credentials from environment variables
// ⚠️ SECURITY: Never hardcode credentials in source code!
const FOUNDER_ACCOUNT = {
email: import.meta.env.VITE_DEMO_FOUNDER_EMAIL || '',
password: import.meta.env.VITE_DEMO_FOUNDER_PASSWORD || '',
id: import.meta.env.VITE_DEMO_FOUNDER_ID || 'founder-001',
user_metadata: {
full_name: 'Satoshi Qazi Muhammed',
phone: '+9647700557978',
recovery_email: 'satoshi@pezkuwichain.io',
founder: true
}
};
// Check if demo mode is enabled
const DEMO_MODE_ENABLED = import.meta.env.VITE_ENABLE_DEMO_MODE === 'true';
const AuthContext = createContext<AuthContextType | undefined>(undefined);
export const useAuth = () => {
@@ -44,6 +32,66 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
const [loading, setLoading] = useState(true);
const [isAdmin, setIsAdmin] = useState(false);
// ========================================
// SESSION TIMEOUT MANAGEMENT
// ========================================
// Update last activity timestamp
const updateLastActivity = useCallback(() => {
localStorage.setItem(LAST_ACTIVITY_KEY, Date.now().toString());
}, []);
// Check if session has timed out
const checkSessionTimeout = useCallback(async () => {
if (!user) return;
const lastActivity = localStorage.getItem(LAST_ACTIVITY_KEY);
if (!lastActivity) {
updateLastActivity();
return;
}
const lastActivityTime = parseInt(lastActivity, 10);
const now = Date.now();
const inactiveTime = now - lastActivityTime;
if (inactiveTime >= SESSION_TIMEOUT_MS) {
console.log('⏱️ Session timeout - logging out due to inactivity');
await signOut();
}
}, [user]);
// Setup activity listeners
useEffect(() => {
if (!user) return;
// Update activity on user interactions
const activityEvents = ['mousedown', 'keydown', 'scroll', 'touchstart'];
const handleActivity = () => {
updateLastActivity();
};
// Register event listeners
activityEvents.forEach((event) => {
window.addEventListener(event, handleActivity);
});
// Initial activity timestamp
updateLastActivity();
// Check for timeout periodically
const timeoutChecker = setInterval(checkSessionTimeout, ACTIVITY_CHECK_INTERVAL_MS);
// Cleanup
return () => {
activityEvents.forEach((event) => {
window.removeEventListener(event, handleActivity);
});
clearInterval(timeoutChecker);
};
}, [user, updateLastActivity, checkSessionTimeout]);
useEffect(() => {
// Check active sessions and sets the user
supabase.auth.getSession().then(({ data: { session } }) => {
@@ -89,42 +137,6 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
};
const signIn = async (email: string, password: string) => {
// Check if demo mode is enabled and this is the founder account
if (DEMO_MODE_ENABLED && email === FOUNDER_ACCOUNT.email && password === FOUNDER_ACCOUNT.password) {
// Try Supabase first
try {
const { data, error } = await supabase.auth.signInWithPassword({
email,
password,
});
if (!error && data.user) {
await checkAdminStatus();
return { error: null };
}
} catch {
// Supabase not available
}
// Fallback to demo mode for founder account
const demoUser = {
id: FOUNDER_ACCOUNT.id,
email: FOUNDER_ACCOUNT.email,
user_metadata: FOUNDER_ACCOUNT.user_metadata,
email_confirmed_at: new Date().toISOString(),
created_at: new Date().toISOString(),
} as User;
setUser(demoUser);
setIsAdmin(true);
// Store in localStorage for persistence
localStorage.setItem('demo_user', JSON.stringify(demoUser));
return { error: null };
}
// For other accounts, use Supabase
try {
const { data, error } = await supabase.auth.signInWithPassword({
email,
@@ -186,21 +198,12 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
};
const signOut = async () => {
localStorage.removeItem('demo_user');
setIsAdmin(false);
setUser(null);
localStorage.removeItem(LAST_ACTIVITY_KEY);
await supabase.auth.signOut();
};
// Check for demo user on mount
useEffect(() => {
const demoUser = localStorage.getItem('demo_user');
if (demoUser && !user) {
const parsedUser = JSON.parse(demoUser);
setUser(parsedUser);
setIsAdmin(true);
}
}, []);
return (
<AuthContext.Provider value={{
user,
+355
View File
@@ -0,0 +1,355 @@
/**
* Perwerde Education Platform
*
* Decentralized education system for Digital Kurdistan
* - Browse courses from blockchain
* - Enroll in courses
* - Track learning progress
* - Earn educational credentials
*/
import React, { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import {
GraduationCap,
BookOpen,
Award,
Users,
Clock,
Star,
TrendingUp,
CheckCircle,
Play,
ExternalLink,
} from 'lucide-react';
import { usePolkadot } from '@/contexts/PolkadotContext';
import { useAuth } from '@/contexts/AuthContext';
import { toast } from '@/components/ui/use-toast';
import { AsyncComponent, LoadingState } from '@pezkuwi/components/AsyncComponent';
import {
getActiveCourses,
getStudentProgress,
getStudentCourses,
getCourseById,
isEnrolled,
type Course,
type StudentProgress,
formatIPFSLink,
getCourseDifficulty,
} from '@pezkuwi/lib/perwerde';
import { web3FromAddress } from '@polkadot/extension-dapp';
import { handleBlockchainError, handleBlockchainSuccess } from '@pezkuwi/lib/error-handler';
export default function EducationPlatform() {
const { api, selectedAccount, isApiReady } = usePolkadot();
const { user } = useAuth();
const [loading, setLoading] = useState(true);
const [courses, setCourses] = useState<Course[]>([]);
const [studentProgress, setStudentProgress] = useState<StudentProgress | null>(null);
const [enrolledCourseIds, setEnrolledCourseIds] = useState<number[]>([]);
// Fetch data
useEffect(() => {
const fetchData = async () => {
if (!api || !isApiReady) return;
try {
setLoading(true);
const coursesData = await getActiveCourses(api);
setCourses(coursesData);
// If user is logged in, fetch their progress
if (selectedAccount) {
const [progress, enrolledIds] = await Promise.all([
getStudentProgress(api, selectedAccount.address),
getStudentCourses(api, selectedAccount.address),
]);
setStudentProgress(progress);
setEnrolledCourseIds(enrolledIds);
}
} catch (error) {
console.error('Failed to load education data:', error);
toast({
title: 'Error',
description: 'Failed to load courses data',
variant: 'destructive',
});
} finally {
setLoading(false);
}
};
fetchData();
// Refresh every 30 seconds
const interval = setInterval(fetchData, 30000);
return () => clearInterval(interval);
}, [api, isApiReady, selectedAccount]);
const handleEnroll = async (courseId: number) => {
if (!api || !selectedAccount) {
toast({
title: 'Error',
description: 'Please connect your wallet first',
variant: 'destructive',
});
return;
}
try {
const injector = await web3FromAddress(selectedAccount.address);
const tx = api.tx.perwerde.enroll(courseId);
await tx.signAndSend(
selectedAccount.address,
{ signer: injector.signer },
({ status, dispatchError }) => {
if (status.isInBlock) {
if (dispatchError) {
handleBlockchainError(dispatchError, api, toast);
} else {
handleBlockchainSuccess('perwerde.enrolled', toast);
// Refresh data
setTimeout(async () => {
if (api && selectedAccount) {
const [progress, enrolledIds] = await Promise.all([
getStudentProgress(api, selectedAccount.address),
getStudentCourses(api, selectedAccount.address),
]);
setStudentProgress(progress);
setEnrolledCourseIds(enrolledIds);
}
}, 2000);
}
}
}
);
} catch (error: any) {
console.error('Enroll failed:', error);
toast({
title: 'Error',
description: error.message || 'Failed to enroll in course',
variant: 'destructive',
});
}
};
if (loading) {
return <LoadingState message="Loading education platform..." />;
}
return (
<div className="container mx-auto px-4 py-8 max-w-7xl">
{/* Header */}
<div className="mb-8">
<h1 className="text-4xl font-bold text-white mb-2 flex items-center gap-3">
<GraduationCap className="w-10 h-10 text-green-500" />
Perwerde - Education Platform
</h1>
<p className="text-gray-400">
Decentralized learning for Digital Kurdistan. Build skills, earn credentials, empower our nation.
</p>
</div>
{/* Stats Cards */}
{studentProgress && (
<div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
<Card className="bg-gray-900 border-gray-800">
<CardContent className="p-6">
<div className="flex items-center gap-3">
<div className="w-12 h-12 rounded-lg bg-blue-500/10 flex items-center justify-center">
<BookOpen className="w-6 h-6 text-blue-400" />
</div>
<div>
<div className="text-2xl font-bold text-white">{studentProgress.totalCourses}</div>
<div className="text-sm text-gray-400">Enrolled Courses</div>
</div>
</div>
</CardContent>
</Card>
<Card className="bg-gray-900 border-gray-800">
<CardContent className="p-6">
<div className="flex items-center gap-3">
<div className="w-12 h-12 rounded-lg bg-green-500/10 flex items-center justify-center">
<CheckCircle className="w-6 h-6 text-green-400" />
</div>
<div>
<div className="text-2xl font-bold text-white">{studentProgress.completedCourses}</div>
<div className="text-sm text-gray-400">Completed</div>
</div>
</div>
</CardContent>
</Card>
<Card className="bg-gray-900 border-gray-800">
<CardContent className="p-6">
<div className="flex items-center gap-3">
<div className="w-12 h-12 rounded-lg bg-purple-500/10 flex items-center justify-center">
<TrendingUp className="w-6 h-6 text-purple-400" />
</div>
<div>
<div className="text-2xl font-bold text-white">{studentProgress.activeCourses}</div>
<div className="text-sm text-gray-400">In Progress</div>
</div>
</div>
</CardContent>
</Card>
<Card className="bg-gray-900 border-gray-800">
<CardContent className="p-6">
<div className="flex items-center gap-3">
<div className="w-12 h-12 rounded-lg bg-yellow-500/10 flex items-center justify-center">
<Award className="w-6 h-6 text-yellow-400" />
</div>
<div>
<div className="text-2xl font-bold text-white">{studentProgress.totalPoints}</div>
<div className="text-sm text-gray-400">Total Points</div>
</div>
</div>
</CardContent>
</Card>
</div>
)}
{/* Courses List */}
<div>
<div className="flex items-center justify-between mb-6">
<h2 className="text-2xl font-bold text-white">
{courses.length > 0 ? `Available Courses (${courses.length})` : 'No Courses Available'}
</h2>
</div>
{courses.length === 0 ? (
<Card className="bg-gray-900 border-gray-800">
<CardContent className="p-12 text-center">
<BookOpen className="w-16 h-16 text-gray-600 mx-auto mb-4" />
<h3 className="text-xl font-bold text-gray-400 mb-2">No Active Courses</h3>
<p className="text-gray-500 mb-6">
Check back later for new educational content. Courses will be added by educators.
</p>
</CardContent>
</Card>
) : (
<div className="grid gap-6">
{courses.map((course) => {
const isUserEnrolled = enrolledCourseIds.includes(course.id);
return (
<Card
key={course.id}
className="bg-gray-900 border-gray-800 hover:border-green-500/50 transition-colors"
>
<CardContent className="p-6">
<div className="flex items-start justify-between gap-6">
{/* Course Info */}
<div className="flex-1">
<div className="flex items-center gap-3 mb-2">
<h3 className="text-xl font-bold text-white">{course.name}</h3>
<Badge className="bg-green-500/10 text-green-400 border-green-500/30">
#{course.id}
</Badge>
{isUserEnrolled && (
<Badge className="bg-blue-500/10 text-blue-400 border-blue-500/30">
Enrolled
</Badge>
)}
</div>
<p className="text-gray-400 mb-4">{course.description}</p>
<div className="flex items-center gap-4 text-sm text-gray-400">
<div className="flex items-center gap-1">
<GraduationCap className="w-4 h-4" />
{course.owner.slice(0, 8)}...{course.owner.slice(-6)}
</div>
{course.contentLink && (
<a
href={formatIPFSLink(course.contentLink)}
target="_blank"
rel="noopener noreferrer"
className="flex items-center gap-1 text-green-400 hover:text-green-300"
>
<ExternalLink className="w-4 h-4" />
Course Materials
</a>
)}
</div>
</div>
{/* Actions */}
<div className="flex flex-col gap-2">
{isUserEnrolled ? (
<>
<Button className="bg-blue-600 hover:bg-blue-700">
<Play className="w-4 h-4 mr-2" />
Continue Learning
</Button>
<Button variant="outline">View Progress</Button>
</>
) : (
<>
<Button
className="bg-green-600 hover:bg-green-700"
onClick={() => handleEnroll(course.id)}
disabled={!selectedAccount}
>
Enroll Now
</Button>
<Button variant="outline">View Details</Button>
</>
)}
</div>
</div>
</CardContent>
</Card>
);
})}
</div>
)}
</div>
{/* Blockchain Features */}
<Card className="mt-8 bg-gray-900 border-gray-800">
<CardHeader>
<CardTitle className="flex items-center gap-2 text-white">
<CheckCircle className="w-5 h-5 text-green-500" />
Blockchain-Powered Education
</CardTitle>
</CardHeader>
<CardContent>
<ul className="grid grid-cols-2 gap-4 text-sm">
<li className="flex items-center gap-2 text-gray-300">
<div className="w-1.5 h-1.5 rounded-full bg-green-500" />
Decentralized course hosting (IPFS)
</li>
<li className="flex items-center gap-2 text-gray-300">
<div className="w-1.5 h-1.5 rounded-full bg-green-500" />
On-chain enrollment & completion tracking
</li>
<li className="flex items-center gap-2 text-gray-300">
<div className="w-1.5 h-1.5 rounded-full bg-green-500" />
Points-based achievement system
</li>
<li className="flex items-center gap-2 text-gray-300">
<div className="w-1.5 h-1.5 rounded-full bg-green-500" />
Trust score integration
</li>
<li className="flex items-center gap-2 text-gray-300">
<div className="w-1.5 h-1.5 rounded-full bg-green-500" />
Transparent educator verification
</li>
<li className="flex items-center gap-2 text-gray-300">
<div className="w-1.5 h-1.5 rounded-full bg-green-500" />
Immutable learning records
</li>
</ul>
</CardContent>
</Card>
</div>
);
}
+461
View File
@@ -0,0 +1,461 @@
/**
* Welati Elections & Governance Page
*
* Features:
* - View active elections (Presidential, Parliamentary, Speaker, Constitutional Court)
* - Register as candidate
* - Cast votes
* - View proposals & vote on them
* - See government officials
*/
import React, { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Alert, AlertDescription } from '@/components/ui/alert';
import {
Vote,
Users,
Trophy,
Clock,
FileText,
CheckCircle2,
XCircle,
AlertCircle,
Crown,
Scale,
Building,
} from 'lucide-react';
import { usePolkadot } from '@/contexts/PolkadotContext';
import { useAuth } from '@/contexts/AuthContext';
import { toast } from '@/components/ui/use-toast';
import { AsyncComponent, LoadingState } from '@pezkuwi/components/AsyncComponent';
import {
getActiveElections,
getElectionCandidates,
getActiveProposals,
getCurrentOfficials,
getCurrentMinisters,
getElectionTypeLabel,
getElectionStatusLabel,
getMinisterRoleLabel,
blocksToTime,
getRemainingBlocks,
type ElectionInfo,
type CollectiveProposal,
type CandidateInfo,
} from '@pezkuwi/lib/welati';
import { handleBlockchainError, handleBlockchainSuccess } from '@pezkuwi/lib/error-handler';
import { web3FromAddress } from '@polkadot/extension-dapp';
export default function Elections() {
const { api, selectedAccount, isApiReady } = usePolkadot();
const { user } = useAuth();
const [loading, setLoading] = useState(true);
const [elections, setElections] = useState<ElectionInfo[]>([]);
const [proposals, setProposals] = useState<CollectiveProposal[]>([]);
const [officials, setOfficials] = useState<any>({});
const [ministers, setMinisters] = useState<any>({});
// Fetch data
useEffect(() => {
const fetchData = async () => {
if (!api || !isApiReady) return;
try {
setLoading(true);
const [electionsData, proposalsData, officialsData, ministersData] = await Promise.all([
getActiveElections(api),
getActiveProposals(api),
getCurrentOfficials(api),
getCurrentMinisters(api),
]);
setElections(electionsData);
setProposals(proposalsData);
setOfficials(officialsData);
setMinisters(ministersData);
} catch (error) {
console.error('Failed to load elections data:', error);
toast({
title: 'Error',
description: 'Failed to load elections data',
variant: 'destructive',
});
} finally {
setLoading(false);
}
};
fetchData();
// Refresh every 30 seconds
const interval = setInterval(fetchData, 30000);
return () => clearInterval(interval);
}, [api, isApiReady]);
if (loading) {
return <LoadingState message="Loading elections and governance data..." />;
}
return (
<div className="container mx-auto px-4 py-8 max-w-7xl">
{/* Header */}
<div className="mb-8">
<h1 className="text-4xl font-bold text-white mb-2">Welati - Elections & Governance</h1>
<p className="text-gray-400">
Democratic governance for Digital Kurdistan. Vote, propose, and participate in building our nation.
</p>
</div>
{/* Tabs */}
<Tabs defaultValue="elections" className="space-y-6">
<TabsList className="grid w-full grid-cols-3 lg:w-auto bg-gray-900">
<TabsTrigger value="elections">
<Vote className="w-4 h-4 mr-2" />
Elections
</TabsTrigger>
<TabsTrigger value="proposals">
<FileText className="w-4 h-4 mr-2" />
Proposals
</TabsTrigger>
<TabsTrigger value="government">
<Crown className="w-4 h-4 mr-2" />
Government
</TabsTrigger>
</TabsList>
{/* Elections Tab */}
<TabsContent value="elections" className="space-y-6">
{elections.length === 0 ? (
<Alert>
<AlertCircle className="h-4 w-4" />
<AlertDescription>
No active elections at this time. Check back later for upcoming elections.
</AlertDescription>
</Alert>
) : (
<div className="grid gap-6">
{elections.map((election) => (
<ElectionCard key={election.electionId} election={election} api={api} />
))}
</div>
)}
</TabsContent>
{/* Proposals Tab */}
<TabsContent value="proposals" className="space-y-6">
{proposals.length === 0 ? (
<Alert>
<AlertCircle className="h-4 w-4" />
<AlertDescription>
No active proposals at this time. Parliament members can submit new proposals.
</AlertDescription>
</Alert>
) : (
<div className="grid gap-6">
{proposals.map((proposal) => (
<ProposalCard key={proposal.proposalId} proposal={proposal} api={api} />
))}
</div>
)}
</TabsContent>
{/* Government Tab */}
<TabsContent value="government" className="space-y-6">
<GovernmentOfficials officials={officials} ministers={ministers} />
</TabsContent>
</Tabs>
</div>
);
}
// ============================================================================
// ELECTION CARD
// ============================================================================
function ElectionCard({ election, api }: { election: ElectionInfo; api: any }) {
const [candidates, setCandidates] = useState<CandidateInfo[]>([]);
const [timeLeft, setTimeLeft] = useState<any>(null);
const typeLabel = getElectionTypeLabel(election.electionType);
const statusLabel = getElectionStatusLabel(election.status);
useEffect(() => {
if (!api) return;
// Load candidates
getElectionCandidates(api, election.electionId).then(setCandidates);
// Update time left
const updateTime = async () => {
let targetBlock = election.votingEndBlock;
if (election.status === 'CandidacyPeriod') targetBlock = election.candidacyEndBlock;
else if (election.status === 'CampaignPeriod') targetBlock = election.campaignEndBlock;
const remaining = await getRemainingBlocks(api, targetBlock);
setTimeLeft(blocksToTime(remaining));
};
updateTime();
const interval = setInterval(updateTime, 10000);
return () => clearInterval(interval);
}, [api, election]);
return (
<Card className="bg-gray-900 border-gray-800">
<CardHeader>
<div className="flex items-center justify-between">
<div>
<CardTitle className="text-2xl text-white">{typeLabel.en}</CardTitle>
<CardDescription className="text-gray-400 mt-1">{typeLabel.kmr}</CardDescription>
</div>
<Badge className="bg-green-500/10 text-green-400 border-green-500/30">
{statusLabel.en}
</Badge>
</div>
</CardHeader>
<CardContent className="space-y-6">
{/* Stats */}
<div className="grid grid-cols-3 gap-4">
<div className="bg-gray-800/50 rounded-lg p-4">
<div className="flex items-center gap-2 text-gray-400 mb-1">
<Users className="w-4 h-4" />
<span className="text-sm">Candidates</span>
</div>
<div className="text-2xl font-bold text-white">{election.totalCandidates}</div>
</div>
<div className="bg-gray-800/50 rounded-lg p-4">
<div className="flex items-center gap-2 text-gray-400 mb-1">
<Vote className="w-4 h-4" />
<span className="text-sm">Votes Cast</span>
</div>
<div className="text-2xl font-bold text-white">{election.totalVotes.toLocaleString()}</div>
</div>
<div className="bg-gray-800/50 rounded-lg p-4">
<div className="flex items-center gap-2 text-gray-400 mb-1">
<Clock className="w-4 h-4" />
<span className="text-sm">Time Left</span>
</div>
<div className="text-lg font-bold text-white">
{timeLeft ? `${timeLeft.days}d ${timeLeft.hours}h` : '-'}
</div>
</div>
</div>
{/* Top Candidates */}
{candidates.length > 0 && (
<div>
<h4 className="text-sm font-medium text-gray-400 mb-3">Leading Candidates</h4>
<div className="space-y-2">
{candidates.slice(0, 5).map((candidate, idx) => (
<div
key={candidate.account}
className="flex items-center justify-between p-3 bg-gray-800/30 rounded-lg"
>
<div className="flex items-center gap-3">
<div className="w-8 h-8 rounded-full bg-green-500/10 border border-green-500/30 flex items-center justify-center">
<span className="text-green-400 font-bold text-sm">#{idx + 1}</span>
</div>
<div>
<div className="text-white text-sm font-medium">
{candidate.account.slice(0, 12)}...{candidate.account.slice(-8)}
</div>
</div>
</div>
<div className="flex items-center gap-2">
<Trophy className="w-4 h-4 text-yellow-500" />
<span className="text-white font-bold">{candidate.voteCount.toLocaleString()}</span>
</div>
</div>
))}
</div>
</div>
)}
{/* Actions */}
<div className="flex gap-3">
{election.status === 'CandidacyPeriod' && (
<Button className="flex-1 bg-green-600 hover:bg-green-700">
Register as Candidate
</Button>
)}
{election.status === 'VotingPeriod' && (
<Button className="flex-1 bg-green-600 hover:bg-green-700">
<Vote className="w-4 h-4 mr-2" />
Cast Your Vote
</Button>
)}
<Button variant="outline" className="flex-1">
View Details
</Button>
</div>
</CardContent>
</Card>
);
}
// ============================================================================
// PROPOSAL CARD
// ============================================================================
function ProposalCard({ proposal, api }: { proposal: CollectiveProposal; api: any }) {
const [timeLeft, setTimeLeft] = useState<any>(null);
const totalVotes = proposal.ayeVotes + proposal.nayVotes + proposal.abstainVotes;
const ayePercent = totalVotes > 0 ? Math.round((proposal.ayeVotes / totalVotes) * 100) : 0;
const nayPercent = totalVotes > 0 ? Math.round((proposal.nayVotes / totalVotes) * 100) : 0;
useEffect(() => {
if (!api) return;
const updateTime = async () => {
const remaining = await getRemainingBlocks(api, proposal.expiresAt);
setTimeLeft(blocksToTime(remaining));
};
updateTime();
const interval = setInterval(updateTime, 10000);
return () => clearInterval(interval);
}, [api, proposal]);
return (
<Card className="bg-gray-900 border-gray-800">
<CardHeader>
<div className="flex items-center justify-between">
<div>
<CardTitle className="text-xl text-white">#{proposal.proposalId} {proposal.title}</CardTitle>
<CardDescription className="text-gray-400 mt-1">{proposal.description}</CardDescription>
</div>
<Badge
className={
proposal.status === 'Active'
? 'bg-green-500/10 text-green-400 border-green-500/30'
: 'bg-gray-500/10 text-gray-400'
}
>
{proposal.status}
</Badge>
</div>
</CardHeader>
<CardContent className="space-y-4">
{/* Vote Progress */}
<div className="space-y-2">
<div className="flex items-center justify-between text-sm">
<span className="text-gray-400">Aye ({proposal.ayeVotes})</span>
<span className="text-gray-400">Nay ({proposal.nayVotes})</span>
</div>
<div className="h-3 bg-gray-800 rounded-full overflow-hidden flex">
<div className="bg-green-500" style={{ width: `${ayePercent}%` }} />
<div className="bg-red-500" style={{ width: `${nayPercent}%` }} />
</div>
<div className="flex items-center justify-between text-xs text-gray-500">
<span>{ayePercent}% Aye</span>
<span>
{proposal.votesCast} / {proposal.threshold} votes cast
</span>
<span>{nayPercent}% Nay</span>
</div>
</div>
{/* Metadata */}
<div className="flex items-center justify-between text-sm">
<div className="flex items-center gap-2 text-gray-400">
<Clock className="w-4 h-4" />
{timeLeft && `${timeLeft.days}d ${timeLeft.hours}h remaining`}
</div>
<Badge variant="outline">{proposal.decisionType}</Badge>
</div>
{/* Actions */}
{proposal.status === 'Active' && (
<div className="grid grid-cols-3 gap-2">
<Button className="bg-green-600 hover:bg-green-700">
<CheckCircle2 className="w-4 h-4 mr-1" />
Aye
</Button>
<Button className="bg-red-600 hover:bg-red-700">
<XCircle className="w-4 h-4 mr-1" />
Nay
</Button>
<Button variant="outline">Abstain</Button>
</div>
)}
</CardContent>
</Card>
);
}
// ============================================================================
// GOVERNMENT OFFICIALS
// ============================================================================
function GovernmentOfficials({ officials, ministers }: { officials: any; ministers: any }) {
return (
<div className="space-y-6">
{/* Executive */}
<Card className="bg-gray-900 border-gray-800">
<CardHeader>
<CardTitle className="flex items-center gap-2 text-white">
<Crown className="w-5 h-5 text-yellow-500" />
Executive Branch
</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
{officials.serok && (
<OfficeRow title="Serok (President)" address={officials.serok} icon={Crown} />
)}
{officials.serokWeziran && (
<OfficeRow title="Serok Weziran (Prime Minister)" address={officials.serokWeziran} icon={Building} />
)}
{officials.meclisBaskanı && (
<OfficeRow title="Meclis Başkanı (Speaker)" address={officials.meclisBaskanı} icon={Scale} />
)}
</CardContent>
</Card>
{/* Cabinet */}
<Card className="bg-gray-900 border-gray-800">
<CardHeader>
<CardTitle className="flex items-center gap-2 text-white">
<Building className="w-5 h-5" />
Cabinet Ministers
</CardTitle>
</CardHeader>
<CardContent className="grid gap-3">
{Object.entries(ministers).map(
([role, address]: [string, any]) =>
address && (
<OfficeRow
key={role}
title={getMinisterRoleLabel(role as any).en}
address={address}
icon={Users}
/>
)
)}
{Object.values(ministers).every((v) => !v) && (
<div className="text-gray-400 text-sm text-center py-4">No ministers appointed yet</div>
)}
</CardContent>
</Card>
</div>
);
}
function OfficeRow({ title, address, icon: Icon }: { title: string; address: string; icon: any }) {
return (
<div className="flex items-center justify-between p-3 bg-gray-800/30 rounded-lg">
<div className="flex items-center gap-3">
<Icon className="w-5 h-5 text-green-400" />
<span className="text-white font-medium">{title}</span>
</div>
<span className="text-gray-400 text-sm font-mono">
{address.slice(0, 8)}...{address.slice(-6)}
</span>
</div>
);
}