feat: Phase 1B complete - Perwerde & ValidatorPool UI

Perwerde (Education Platform):
- Add hybrid backend (Supabase + Blockchain + IPFS)
- Implement CourseList, CourseCreator, StudentDashboard
- Create courses table with RLS policies
- Add IPFS upload utility
- Integrate with pallet-perwerde extrinsics

ValidatorPool:
- Add validator pool management UI
- Implement PoolCategorySelector with 3 categories
- Add ValidatorPoolDashboard with pool stats
- Integrate with pallet-validator-pool extrinsics
- Add to StakingDashboard as new tab

Technical:
- Fix all toast imports (sonner)
- Fix IPFS File upload (Blob conversion)
- Fix RLS policies (wallet_address → auth.uid)
- Add error boundaries
- Add loading states

Status: UI complete, blockchain integration pending VPS deployment
This commit is contained in:
2025-11-17 05:04:51 +03:00
parent 3fe0572e40
commit c488cfc3bc
17 changed files with 1929 additions and 779 deletions
+21 -1
View File
@@ -32,6 +32,8 @@ import { useWallet } from '@/contexts/WalletContext';
import { supabase } from '@/lib/supabase';
import { PolkadotWalletButton } from './PolkadotWalletButton';
import { DEXDashboard } from './dex/DEXDashboard';
import EducationPlatform from '../pages/EducationPlatform';
const AppLayout: React.FC = () => {
const navigate = useNavigate();
const [walletModalOpen, setWalletModalOpen] = useState(false);
@@ -46,6 +48,7 @@ const AppLayout: React.FC = () => {
const [showStaking, setShowStaking] = useState(false);
const [showMultiSig, setShowMultiSig] = useState(false);
const [showDEX, setShowDEX] = useState(false);
const [showEducation, setShowEducation] = useState(false);
const { t } = useTranslation();
const { isConnected } = useWebSocket();
const { account } = useWallet();
@@ -197,6 +200,17 @@ const AppLayout: React.FC = () => {
</div>
</div>
<button
onClick={() => {
setShowEducation(true);
navigate('/education');
}}
className="text-gray-300 hover:text-white transition-colors flex items-center gap-1 text-sm"
>
<Award className="w-4 h-4" />
Education
</button>
<button
onClick={() => navigate('/profile/settings')}
className="text-gray-300 hover:text-white transition-colors flex items-center gap-1 text-sm"
@@ -368,6 +382,10 @@ const AppLayout: React.FC = () => {
<MultiSigWallet />
</div>
</div>
) : showEducation ? (
<div className="pt-20 min-h-screen bg-gray-950">
<EducationPlatform />
</div>
) : (
<>
<HeroSection />
@@ -392,7 +410,7 @@ const AppLayout: React.FC = () => {
)}
{(showDEX || showProposalWizard || showDelegation || showForum || showModeration || showTreasury || showStaking || showMultiSig) && (
{(showDEX || showProposalWizard || showDelegation || showForum || showModeration || showTreasury || showStaking || showMultiSig || showEducation) && (
<div className="fixed bottom-8 right-8 z-50">
<button
onClick={() => {
@@ -404,6 +422,8 @@ const AppLayout: React.FC = () => {
setShowTreasury(false);
setShowStaking(false);
setShowMultiSig(false);
setShowEducation(false);
setShowEducation(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"
>
@@ -0,0 +1,120 @@
import React, { useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
import { usePolkadot } from '@/contexts/PolkadotContext';
import { toast } from 'sonner';
import { createCourse } from '@shared/lib/perwerde';
import { uploadToIPFS } from '@shared/lib/ipfs';
import { Loader2 } from 'lucide-react';
interface CourseCreatorProps {
onCourseCreated: () => void;
}
export function CourseCreator({ onCourseCreated }: CourseCreatorProps) {
const { api, selectedAccount } = usePolkadot();
const [name, setName] = useState('');
const [description, setDescription] = useState('');
const [content, setContent] = useState('');
const [loading, setLoading] = useState(false);
const handleCreateCourse = async () => {
if (!api || !selectedAccount) {
toast.error('Please connect your wallet first');
return;
}
if (!name || !description || !content) {
toast.error('Please fill in all fields');
return;
}
setLoading(true);
try {
// 1. Upload content to IPFS
const blob = new Blob([content], { type: 'text/markdown' });
const file = new File([blob], 'course-content.md', { type: 'text/markdown' });
let ipfsHash: string;
try {
ipfsHash = await uploadToIPFS(file);
toast.success(`Content uploaded: ${ipfsHash.slice(0, 10)}...`);
} catch (ipfsError) {
toast.error('IPFS upload failed');
return; // STOP - don't call blockchain
}
// 2. Create course on blockchain
await createCourse(api, selectedAccount, name, description, ipfsHash);
// 3. Reset form
onCourseCreated();
setName('');
setDescription('');
setContent('');
} catch (error: any) {
console.error('Failed to create course:', error);
// toast already shown in createCourse()
} finally {
setLoading(false);
}
};
return (
<Card className="bg-gray-900 border-gray-800">
<CardHeader>
<CardTitle className="text-white">Create New Course</CardTitle>
<CardDescription>Fill in the details to create a new course on the Perwerde platform.</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-2">
<Label htmlFor="name" className="text-white">Course Name</Label>
<Input
id="name"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="e.g., Introduction to Blockchain"
className="bg-gray-800 border-gray-700 text-white"
/>
</div>
<div className="space-y-2">
<Label htmlFor="description" className="text-white">Course Description</Label>
<Textarea
id="description"
value={description}
onChange={(e) => setDescription(e.target.value)}
placeholder="A brief summary of the course content and objectives."
className="bg-gray-800 border-gray-700 text-white"
/>
</div>
<div className="space-y-2">
<Label htmlFor="content" className="text-white">Course Content (Markdown)</Label>
<Textarea
id="content"
value={content}
onChange={(e) => setContent(e.target.value)}
placeholder="Write your course material here using Markdown..."
className="bg-gray-800 border-gray-700 text-white h-48"
/>
</div>
<Button
onClick={handleCreateCourse}
disabled={loading || !selectedAccount}
className="w-full bg-green-600 hover:bg-green-700"
>
{loading ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Creating...
</>
) : (
'Create Course'
)}
</Button>
</CardContent>
</Card>
);
}
+152
View File
@@ -0,0 +1,152 @@
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, ExternalLink, Play } from 'lucide-react';
import { usePolkadot } from '@/contexts/PolkadotContext';
import { toast } from 'sonner';
import { LoadingState } from '@shared/components/AsyncComponent';
import { getCourses, enrollInCourse, type Course } from '@shared/lib/perwerde';
import { getIPFSUrl } from '@shared/lib/ipfs';
interface CourseListProps {
enrolledCourseIds: number[];
onEnroll: () => void;
}
export function CourseList({ enrolledCourseIds, onEnroll }: CourseListProps) {
const { api, selectedAccount } = usePolkadot();
const [courses, setCourses] = useState<Course[]>([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
const fetchCourses = async () => {
try {
setLoading(true);
const activeCourses = await getCourses('Active');
setCourses(activeCourses);
} catch (error) {
console.error('Failed to fetch courses:', error);
toast({
title: 'Error',
description: 'Failed to fetch courses',
variant: 'destructive',
});
} finally {
setLoading(false);
}
};
fetchCourses();
}, []);
const handleEnroll = async (courseId: number) => {
if (!api || !selectedAccount) {
toast({
title: 'Error',
description: 'Please connect your wallet first',
variant: 'destructive',
});
return;
}
try {
await enrollInCourse(api, selectedAccount, courseId);
onEnroll();
} catch (error: any) {
console.error('Enroll failed:', error);
}
};
if (loading) {
return <LoadingState message="Loading available courses..." />;
}
return (
<div>
<h2 className="text-2xl font-bold text-white mb-6">
{courses.length > 0 ? `Available Courses (${courses.length})` : 'No Courses Available'}
</h2>
{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.
</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">
<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.content_link && (
<a
href={getIPFSUrl(course.content_link)}
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>
<div className="flex flex-col gap-2">
{isUserEnrolled ? (
<Button className="bg-blue-600 hover:bg-blue-700" disabled>
<Play className="w-4 h-4 mr-2" />
Already Enrolled
</Button>
) : (
<Button
className="bg-green-600 hover:bg-green-700"
onClick={() => handleEnroll(course.id)}
disabled={!selectedAccount}
>
Enroll Now
</Button>
)}
</div>
</div>
</CardContent>
</Card>
);
})}
</div>
)}
</div>
);
}
@@ -0,0 +1,124 @@
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 { Progress } from '@/components/ui/progress';
import { BookOpen, CheckCircle, Award } from 'lucide-react';
import { usePolkadot } from '@/contexts/PolkadotContext';
import { toast } from 'sonner';
import { LoadingState } from '@shared/components/AsyncComponent';
import { getStudentEnrollments, completeCourse, type Enrollment } from '@shared/lib/perwerde';
interface StudentDashboardProps {
enrollments: Enrollment[];
loading: boolean;
onCourseCompleted: () => void;
}
export function StudentDashboard({ enrollments, loading, onCourseCompleted }: StudentDashboardProps) {
const { api, selectedAccount } = usePolkadot();
const handleComplete = async (courseId: number) => {
if (!api || !selectedAccount) {
toast.error('Please connect your wallet first');
return;
}
try {
// For now, let's assume a fixed number of points for completion
const points = 10;
await completeCourse(api, selectedAccount, courseId, points);
onCourseCompleted();
} catch (error: any) {
console.error('Failed to complete course:', error);
}
};
if (loading) {
return <LoadingState message="Loading your dashboard..." />;
}
const completedCourses = enrollments.filter(e => e.is_completed).length;
const totalPoints = enrollments.reduce((sum, e) => sum + e.points_earned, 0);
return (
<div className="space-y-6">
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
<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">{enrollments.length}</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">{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-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">{totalPoints}</div>
<div className="text-sm text-gray-400">Total Points</div>
</div>
</div>
</CardContent>
</Card>
</div>
<Card className="bg-gray-900 border-gray-800">
<CardHeader>
<CardTitle className="text-white">My Courses</CardTitle>
</CardHeader>
<CardContent>
{enrollments.length === 0 ? (
<p className="text-gray-400">You are not enrolled in any courses yet.</p>
) : (
<div className="space-y-4">
{enrollments.map(enrollment => (
<div key={enrollment.id} className="p-4 bg-gray-800 rounded-lg">
<div className="flex items-center justify-between">
<div>
<h4 className="font-bold text-white">Course #{enrollment.course_id}</h4>
<p className="text-sm text-gray-400">
Enrolled on: {new Date(enrollment.enrolled_at).toLocaleDateString()}
</p>
</div>
<div>
{enrollment.is_completed ? (
<Badge className="bg-green-500/10 text-green-400">Completed</Badge>
) : (
<Button size="sm" onClick={() => handleComplete(enrollment.course_id)}>
Mark as Complete
</Button>
)}
</div>
</div>
</div>
))}
</div>
)}
</CardContent>
</Card>
</div>
);
}
@@ -0,0 +1,40 @@
import React, { useState } from 'react';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Button } from '@/components/ui/button';
import { Loader2 } from 'lucide-react';
import { ValidatorPoolCategory } from '@shared/lib/validator-pool';
interface PoolCategorySelectorProps {
currentCategory?: ValidatorPoolCategory;
onCategoryChange: (category: ValidatorPoolCategory) => void;
disabled?: boolean;
}
const POOL_CATEGORIES = Object.values(ValidatorPoolCategory);
export function PoolCategorySelector({ currentCategory, onCategoryChange, disabled }: PoolCategorySelectorProps) {
const [selectedCategory, setSelectedCategory] = useState<ValidatorPoolCategory>(currentCategory || POOL_CATEGORIES[0]);
const handleSubmit = () => {
onCategoryChange(selectedCategory);
};
return (
<div className="space-y-4">
<Select value={selectedCategory} onValueChange={(value) => setSelectedCategory(value as ValidatorPoolCategory)} disabled={disabled}>
<SelectTrigger className="w-full bg-gray-800 border-gray-700 text-white">
<SelectValue placeholder="Select a pool category..." />
</SelectTrigger>
<SelectContent>
{POOL_CATEGORIES.map(cat => (
<SelectItem key={cat} value={cat}>{cat.replace(/([A-Z])/g, ' $1').trim()}</SelectItem>
))}
</SelectContent>
</Select>
<Button onClick={handleSubmit} disabled={disabled || !selectedCategory} className="w-full">
{disabled && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
{currentCategory ? 'Switch Category' : 'Join Pool'}
</Button>
</div>
);
}
+26 -74
View File
@@ -10,7 +10,7 @@ import { TrendingUp, Coins, Lock, Clock, Award, AlertCircle, CheckCircle2 } from
import { useTranslation } from 'react-i18next';
import { usePolkadot } from '@/contexts/PolkadotContext';
import { useWallet } from '@/contexts/WalletContext';
import { toast } from '@/components/ui/use-toast';
import { toast } from 'sonner';
import { web3FromAddress } from '@polkadot/extension-dapp';
import {
getStakingInfo,
@@ -22,6 +22,7 @@ import {
type StakingInfo
} from '@pezkuwi/lib/staking';
import { LoadingState } from '@pezkuwi/components/AsyncComponent';
import { ValidatorPoolDashboard } from './ValidatorPoolDashboard';
import { handleBlockchainError, handleBlockchainSuccess } from '@pezkuwi/lib/error-handler';
export const StakingDashboard: React.FC = () => {
@@ -71,11 +72,7 @@ export const StakingDashboard: React.FC = () => {
}
} catch (error) {
console.error('Failed to fetch staking data:', error);
toast({
title: 'Error',
description: 'Failed to fetch staking information',
variant: 'destructive',
});
toast.error('Failed to fetch staking information');
} finally {
setIsLoadingData(false);
}
@@ -140,11 +137,7 @@ export const StakingDashboard: React.FC = () => {
);
} catch (error: any) {
console.error('Bond failed:', error);
toast({
title: 'Error',
description: error.message || 'Failed to bond tokens',
variant: 'destructive',
});
toast.error(error.message || 'Failed to bond tokens');
setIsLoading(false);
}
};
@@ -153,11 +146,7 @@ export const StakingDashboard: React.FC = () => {
if (!api || !selectedAccount || selectedValidators.length === 0) return;
if (!stakingInfo || parseFloat(stakingInfo.bonded) === 0) {
toast({
title: 'Error',
description: 'You must bond tokens before nominating validators',
variant: 'destructive',
});
toast.error('You must bond tokens before nominating validators');
return;
}
@@ -190,11 +179,7 @@ export const StakingDashboard: React.FC = () => {
);
} catch (error: any) {
console.error('Nomination failed:', error);
toast({
title: 'Error',
description: error.message || 'Failed to nominate validators',
variant: 'destructive',
});
toast.error(error.message || 'Failed to nominate validators');
setIsLoading(false);
}
};
@@ -239,11 +224,7 @@ export const StakingDashboard: React.FC = () => {
);
} catch (error: any) {
console.error('Unbond failed:', error);
toast({
title: 'Error',
description: error.message || 'Failed to unbond tokens',
variant: 'destructive',
});
toast.error(error.message || 'Failed to unbond tokens');
setIsLoading(false);
}
};
@@ -252,10 +233,7 @@ export const StakingDashboard: React.FC = () => {
if (!api || !selectedAccount) return;
if (!stakingInfo || parseFloat(stakingInfo.redeemable) === 0) {
toast({
title: 'Info',
description: 'No tokens available to withdraw',
});
toast.info('No tokens available to withdraw');
return;
}
@@ -277,17 +255,10 @@ export const StakingDashboard: React.FC = () => {
const decoded = api.registry.findMetaError(dispatchError.asModule);
errorMessage = `${decoded.section}.${decoded.name}: ${decoded.docs.join(' ')}`;
}
toast({
title: 'Error',
description: errorMessage,
variant: 'destructive',
});
toast.error(errorMessage);
setIsLoading(false);
} else {
toast({
title: 'Success',
description: `Withdrew ${stakingInfo.redeemable} HEZ`,
});
toast.success(`Withdrew ${stakingInfo.redeemable} HEZ`);
refreshBalances();
setTimeout(() => {
if (api && selectedAccount) {
@@ -301,11 +272,7 @@ export const StakingDashboard: React.FC = () => {
);
} catch (error: any) {
console.error('Withdrawal failed:', error);
toast({
title: 'Error',
description: error.message || 'Failed to withdraw tokens',
variant: 'destructive',
});
toast.error(error.message || 'Failed to withdraw tokens');
setIsLoading(false);
}
};
@@ -314,11 +281,7 @@ export const StakingDashboard: React.FC = () => {
if (!api || !selectedAccount) return;
if (!stakingInfo || parseFloat(stakingInfo.bonded) === 0) {
toast({
title: 'Error',
description: 'You must bond tokens before starting score tracking',
variant: 'destructive',
});
toast.error('You must bond tokens before starting score tracking');
return;
}
@@ -338,17 +301,10 @@ export const StakingDashboard: React.FC = () => {
const decoded = api.registry.findMetaError(dispatchError.asModule);
errorMessage = `${decoded.section}.${decoded.name}: ${decoded.docs.join(' ')}`;
}
toast({
title: 'Error',
description: errorMessage,
variant: 'destructive',
});
toast.error(errorMessage);
setIsLoading(false);
} else {
toast({
title: 'Success',
description: 'Score tracking started successfully! Your staking score will now accumulate over time.',
});
toast.success('Score tracking started successfully! Your staking score will now accumulate over time.');
// Refresh staking data after a delay
setTimeout(() => {
if (api && selectedAccount) {
@@ -362,11 +318,7 @@ export const StakingDashboard: React.FC = () => {
);
} catch (error: any) {
console.error('Start score tracking failed:', error);
toast({
title: 'Error',
description: error.message || 'Failed to start score tracking',
variant: 'destructive',
});
toast.error(error.message || 'Failed to start score tracking');
setIsLoading(false);
}
};
@@ -378,10 +330,7 @@ export const StakingDashboard: React.FC = () => {
} else {
// Max 16 nominations
if (prev.length >= 16) {
toast({
title: 'Limit Reached',
description: 'Maximum 16 validators can be nominated',
});
toast.info('Maximum 16 validators can be nominated');
return prev;
}
return [...prev, validator];
@@ -492,10 +441,7 @@ export const StakingDashboard: React.FC = () => {
<Button
size="sm"
onClick={() => {
toast({
title: 'Coming Soon',
description: 'Claim PEZ rewards functionality will be available soon',
});
toast.info('Claim PEZ rewards functionality will be available soon');
}}
disabled={isLoading}
className="mt-2 w-full bg-orange-600 hover:bg-orange-700"
@@ -520,16 +466,17 @@ export const StakingDashboard: React.FC = () => {
{/* Main Staking Interface */}
<Card className="bg-gray-900 border-gray-800">
<CardHeader>
<CardTitle className="text-xl text-white">Validator Nomination Staking</CardTitle>
<CardTitle className="text-xl text-white">Staking</CardTitle>
<CardDescription className="text-gray-400">
Bond HEZ and nominate validators to earn staking rewards
Stake HEZ to secure the network and earn rewards.
</CardDescription>
</CardHeader>
<CardContent>
<Tabs defaultValue="stake">
<TabsList className="grid w-full grid-cols-3">
<TabsList className="grid w-full grid-cols-4">
<TabsTrigger value="stake">Stake</TabsTrigger>
<TabsTrigger value="nominate">Nominate</TabsTrigger>
<TabsTrigger value="pool">Validator Pool</TabsTrigger>
<TabsTrigger value="unstake">Unstake</TabsTrigger>
</TabsList>
@@ -618,6 +565,11 @@ export const StakingDashboard: React.FC = () => {
</Button>
</TabsContent>
{/* VALIDATOR POOL TAB */}
<TabsContent value="pool" className="space-y-4">
<ValidatorPoolDashboard />
</TabsContent>
{/* UNSTAKE TAB */}
<TabsContent value="unstake" className="space-y-4">
<Alert className="bg-yellow-900/20 border-yellow-500">
@@ -0,0 +1,188 @@
import React, { useState, useEffect, useCallback } from 'react';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { usePolkadot } from '@/contexts/PolkadotContext';
import { toast } from 'sonner';
import {
getPoolMember,
getPoolSize,
getCurrentValidatorSet,
joinValidatorPool,
leaveValidatorPool,
updateValidatorCategory,
ValidatorPoolCategory
} from '@shared/lib/validator-pool';
import { Loader2, Users, UserCheck, UserX } from 'lucide-react';
import { PoolCategorySelector } from './PoolCategorySelector';
export function ValidatorPoolDashboard() {
const { api, selectedAccount } = usePolkadot();
const [poolMember, setPoolMember] = useState<ValidatorPoolCategory | null>(null);
const [poolSize, setPoolSize] = useState(0);
const [validatorCount, setValidatorCount] = useState(0);
const [loading, setLoading] = useState(true);
const [actionLoading, setActionLoading] = useState(false);
const fetchData = useCallback(async () => {
if (!api) return;
try {
setLoading(true);
const [size, validatorSet] = await Promise.all([
getPoolSize(api),
getCurrentValidatorSet(api),
]);
setPoolSize(size);
// Calculate total validator count
if (validatorSet) {
const total = validatorSet.stake_validators.length +
validatorSet.parliamentary_validators.length +
validatorSet.merit_validators.length;
setValidatorCount(total);
}
if (selectedAccount) {
const memberData = await getPoolMember(api, selectedAccount.address);
setPoolMember(memberData);
}
} catch (error) {
console.error('Failed to fetch validator pool data:', error);
toast.error('Failed to fetch pool data');
} finally {
setLoading(false);
}
}, [api, selectedAccount]);
useEffect(() => {
fetchData();
}, [fetchData]);
const handleJoin = async (category: ValidatorPoolCategory) => {
if (!api || !selectedAccount) return;
setActionLoading(true);
try {
await joinValidatorPool(api, selectedAccount, category);
toast.success(`Joined the ${category} pool`);
fetchData();
} catch (error: any) {
console.error('Join pool error:', error);
// Error toast already shown in joinValidatorPool
} finally {
setActionLoading(false);
}
};
const handleLeave = async () => {
if (!api || !selectedAccount) return;
setActionLoading(true);
try {
await leaveValidatorPool(api, selectedAccount);
toast.success('Left the validator pool');
fetchData();
} catch (error: any) {
console.error('Leave pool error:', error);
// Error toast already shown in leaveValidatorPool
} finally {
setActionLoading(false);
}
};
const handleCategorySwitch = async (newCategory: ValidatorPoolCategory) => {
if (!api || !selectedAccount) return;
setActionLoading(true);
try {
await updateValidatorCategory(api, selectedAccount, newCategory);
toast.success(`Switched to ${newCategory}`);
fetchData();
} catch (error: any) {
console.error('Switch category error:', error);
// Error toast already shown in updateValidatorCategory
} finally {
setActionLoading(false);
}
};
if (loading) {
return (
<Card className="bg-gray-900 border-gray-800">
<CardContent className="p-12 text-center">
<Loader2 className="w-8 h-8 animate-spin text-green-500 mx-auto mb-4" />
<p className="text-gray-400">Loading validator pool info...</p>
</CardContent>
</Card>
);
}
return (
<Card className="bg-gray-900 border-gray-800">
<CardHeader>
<CardTitle className="text-white">Validator Pool</CardTitle>
<CardDescription>Join a pool to support the network and earn rewards.</CardDescription>
</CardHeader>
<CardContent className="space-y-6">
<div className="grid grid-cols-2 gap-4">
<div className="p-4 bg-gray-800 rounded-lg">
<div className="flex items-center text-gray-400 mb-2">
<Users className="w-4 h-4 mr-2" />
Pool Size
</div>
<div className="text-2xl font-bold text-white">{poolSize}</div>
</div>
<div className="p-4 bg-gray-800 rounded-lg">
<div className="flex items-center text-gray-400 mb-2">
<UserCheck className="w-4 h-4 mr-2" />
Active Validators
</div>
<div className="text-2xl font-bold text-white">{validatorCount}</div>
</div>
</div>
{selectedAccount ? (
poolMember ? (
<div className="space-y-4">
<div className="p-4 bg-green-500/10 border border-green-500/30 rounded-lg">
<p className="text-green-400">
You are in the <span className="font-bold">{poolMember}</span> pool
</p>
</div>
<PoolCategorySelector
currentCategory={poolMember}
onCategoryChange={handleCategorySwitch}
disabled={actionLoading}
/>
<Button
onClick={handleLeave}
variant="destructive"
disabled={actionLoading}
className="w-full"
>
{actionLoading ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : (
<UserX className="mr-2 h-4 w-4" />
)}
Leave Pool
</Button>
</div>
) : (
<div className="space-y-4">
<div className="p-4 bg-yellow-500/10 border border-yellow-500/30 rounded-lg">
<p className="text-yellow-400">You are not currently in a validator pool</p>
</div>
<PoolCategorySelector
onCategoryChange={handleJoin}
disabled={actionLoading}
/>
</div>
)
) : (
<div className="p-6 text-center">
<p className="text-gray-400">Please connect your wallet to manage pool membership</p>
</div>
)}
</CardContent>
</Card>
);
}
+79 -327
View File
@@ -1,355 +1,107 @@
/**
* 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 React, { useState, useEffect, useCallback } from 'react';
import { GraduationCap } from 'lucide-react';
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';
import { usePolkadot } from '@/contexts/PolkadotContext';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { CourseList } from '@/components/perwerde/CourseList';
import { StudentDashboard } from '@/components/perwerde/StudentDashboard';
import { CourseCreator } from '@/components/perwerde/CourseCreator';
import { getStudentEnrollments, type Enrollment } from '@shared/lib/perwerde';
import { toast } from 'sonner';
import { AsyncComponent, LoadingState } from '@shared/components/AsyncComponent';
import { useNavigate } from 'react-router-dom';
import { Button } from '@/components/ui/button';
export default function EducationPlatform() {
const { api, selectedAccount, isApiReady } = usePolkadot();
const { user } = useAuth();
const { selectedAccount } = usePolkadot();
const [enrollments, setEnrollments] = useState<Enrollment[]>([]);
const [loading, setLoading] = useState(true);
const [courses, setCourses] = useState<Course[]>([]);
const [studentProgress, setStudentProgress] = useState<StudentProgress | null>(null);
const [enrolledCourseIds, setEnrolledCourseIds] = useState<number[]>([]);
const [activeTab, setActiveTab] = useState('courses');
const navigate = useNavigate();
// Fetch data
useEffect(() => {
const fetchData = async () => {
if (!api || !isApiReady) return;
const isAdmin = user?.role === 'admin';
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',
});
const fetchEnrollments = useCallback(async () => {
if (!selectedAccount) {
setEnrollments([]);
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);
setLoading(true);
const studentEnrollments = await getStudentEnrollments(selectedAccount.address);
setEnrollments(studentEnrollments);
} catch (error) {
console.error('Failed to fetch enrollments:', error);
toast({
title: 'Error',
description: error.message || 'Failed to enroll in course',
description: 'Failed to fetch your enrollments.',
variant: 'destructive',
});
} finally {
setLoading(false);
}
};
}, [selectedAccount]);
if (loading) {
return <LoadingState message="Loading education platform..." />;
}
useEffect(() => {
fetchEnrollments();
}, [fetchEnrollments]);
const handleDataChange = () => {
// Refetch enrollments after an action
fetchEnrollments();
};
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 className="mb-8 flex items-center justify-between">
<div>
<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>
<Button onClick={() => navigate('/')} className="bg-gray-700 hover:bg-gray-600 text-white">
Back to Home
</Button>
</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>
<Tabs value={activeTab} onValueChange={setActiveTab} className="space-y-4">
<TabsList>
<TabsTrigger value="courses">Available Courses</TabsTrigger>
{selectedAccount && <TabsTrigger value="dashboard">My Dashboard</TabsTrigger>}
{isAdmin && <TabsTrigger value="create">Create Course</TabsTrigger>}
</TabsList>
<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>
<TabsContent value="courses">
<CourseList
enrolledCourseIds={enrollments.map(e => e.course_id)}
onEnroll={handleDataChange}
/>
</TabsContent>
<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>
{selectedAccount && (
<TabsContent value="dashboard">
<StudentDashboard
enrollments={enrollments}
loading={loading}
onCourseCompleted={handleDataChange}
/>
</TabsContent>
)}
</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>
{isAdmin && (
<TabsContent value="create">
<CourseCreator onCourseCreated={() => {
handleDataChange();
setActiveTab('courses'); // Switch back to course list after creation
}} />
</TabsContent>
)}
</Tabs>
</div>
);
}