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 628221ebb4
commit a635610b7c
17 changed files with 1929 additions and 779 deletions
+343
View File
@@ -0,0 +1,343 @@
# FAZ 1: Mobile App Temel Yapı - Özet Rapor
## Genel Bakış
FAZ 1, mobil uygulama için temel kullanıcı akışının ve blockchain bağlantısının kurulmasını kapsar. Bu faz tamamlandığında kullanıcı, dil seçimi yapabilecek, insan doğrulamasından geçecek ve gerçek blockchain verilerini görebilecek.
## Tamamlanan Görevler ✅
### 1. WelcomeScreen - Dil Seçimi ✅
**Dosya:** `/home/mamostehp/pwap/mobile/src/screens/WelcomeScreen.tsx`
**Durum:** Tamamen hazır, değişiklik gerekmez
**Özellikler:**
- 6 dil desteği (EN, TR, KMR, CKB, AR, FA)
- RTL (Sağdan-sola) dil desteği badge'i
- Kurdistan renk paleti ile gradient tasarım
- i18next entegrasyonu aktif
- LanguageContext ile dil state yönetimi
**Kod İncelemesi:**
- Lines 22-42: 6 dil tanımı (name, nativeName, code, rtl)
- Lines 44-58: handleLanguageSelect() - Dil değişim fonksiyonu
- Lines 59-88: Dil kartları UI (TouchableOpacity ile seçilebilir)
- Lines 104-107: Devam butonu (dil seçildikten sonra aktif olur)
### 2. VerificationScreen - İnsan Doğrulama ✅
**Dosya:** `/home/mamostehp/pwap/mobile/src/screens/VerificationScreen.tsx`
**Durum:** Syntax hatası düzeltildi (line 50: KurdistanColors)
**Özellikler:**
- Mock doğrulama (FAZ 1.2 için yeterli)
- Dev modunda "Skip" butonu (__DEV__ flag)
- 1.5 saniye simüle doğrulama delay'i
- Linear gradient tasarım (Kesk → Zer)
- i18n çeviri desteği
- Loading state (ActivityIndicator)
**Kod İncelemesi:**
- Lines 30-38: handleVerify() - 1.5s simüle doğrulama
- Lines 40-45: handleSkip() - Sadece dev modda aktif
- Lines 50: **FIX APPLIED** - `KurdistanColors.kesk` (was: `Kurdistan Colors.kesk`)
- Lines 75-81: Dev mode badge gösterimi
- Lines 100-110: Skip butonu (sadece __DEV__)
**Düzeltilen Hata:**
```diff
- colors={[Kurdistan Colors.kesk, KurdistanColors.zer]}
+ colors={[KurdistanColors.kesk, KurdistanColors.zer]}
```
## Devam Eden Görevler 🚧
### 3. DashboardScreen - Blockchain Bağlantısı 🚧
**Dosya:** `/home/mamostehp/pwap/mobile/src/screens/DashboardScreen.tsx`
**Durum:** UI hazır, blockchain entegrasyonu gerekli
**Hardcoded Değerler (Değiştirilmesi Gereken):**
#### Balance Card (Lines 94-108)
```typescript
// ❌ ŞU AN HARDCODED:
<Text style={styles.balanceAmount}>0.00 HEZ</Text>
// Satır 98-101: Total Staked
<Text style={styles.statValue}>0.00</Text>
// Satır 103-106: Rewards
<Text style={styles.statValue}>0.00</Text>
```
**Gerekli Değişiklik:**
```typescript
// ✅ OLMASI GEREKEN:
import { useBalance } from '@pezkuwi/shared/hooks/blockchain/useBalance';
const { balance, isLoading, error } = useBalance(api, userAddress);
<Text style={styles.balanceAmount}>
{isLoading ? 'Loading...' : formatBalance(balance.free)} HEZ
</Text>
```
#### Active Proposals Card (Lines 133-142)
```typescript
// ❌ ŞU AN HARDCODED:
<Text style={styles.proposalsCount}>0</Text>
```
**Gerekli Değişiklik:**
```typescript
// ✅ OLMASI GEREKEN:
import { useProposals } from '@pezkuwi/shared/hooks/blockchain/useProposals';
const { proposals, isLoading } = useProposals(api);
<Text style={styles.proposalsCount}>
{isLoading ? '...' : proposals.length}
</Text>
```
### 4. Quick Actions - Gerçek Veri Bağlantısı 🚧
**Durum:** UI hazır, blockchain queries gerekli
**Mevcut Quick Actions:**
1. 💼 **Wallet** - `onNavigateToWallet()` ✅ (navigation var)
2. 🔒 **Staking** - `console.log()` ❌ (stub)
3. 🗳️ **Governance** - `console.log()` ❌ (stub)
4. 💱 **DEX** - `console.log()` ❌ (stub)
5. 📜 **History** - `console.log()` ❌ (stub)
6. ⚙️ **Settings** - `onNavigateToSettings()` ✅ (navigation var)
**FAZ 1 İçin Gerekli:**
- Quick Actions'lar gerçek blockchain data ile çalışacak şekilde güncellenecek
- Her action için ilgili screen navigation'ı eklenecek
- FAZ 2'de detaylı implementasyonlar yapılacak (şimdilik sadece navigation yeterli)
## Gerekli Shared Hooks (Oluşturulmalı)
### 1. useBalance Hook ✅ (ZATEN OLUŞTURULDU)
**Dosya:** `/home/mamostehp/pwap/shared/hooks/blockchain/usePolkadotApi.ts`
**Durum:** Platform-agnostic API connection hook hazır
**Kod:**
```typescript
export function usePolkadotApi(endpoint?: string): UsePolkadotApiReturn {
const [api, setApi] = useState<ApiPromise | null>(null);
const [isReady, setIsReady] = useState(false);
const [error, setError] = useState<Error | null>(null);
// Auto-connect on mount, disconnect on unmount
// Returns: { api, isReady, error, connect, disconnect }
}
```
**Kullanım:**
```typescript
import { usePolkadotApi } from '@pezkuwi/shared/hooks/blockchain/usePolkadotApi';
const { api, isReady, error } = usePolkadotApi('ws://localhost:9944');
```
### 2. useBalance Hook (Oluşturulacak)
**Dosya:** `/home/mamostehp/pwap/shared/hooks/blockchain/useBalance.ts` (YOK)
**Gerekli Kod:**
```typescript
import { useState, useEffect } from 'react';
import { ApiPromise } from '@polkadot/api';
interface Balance {
free: string;
reserved: string;
frozen: string;
}
export function useBalance(api: ApiPromise | null, address: string) {
const [balance, setBalance] = useState<Balance>({
free: '0',
reserved: '0',
frozen: '0'
});
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<Error | null>(null);
useEffect(() => {
if (!api || !address) return;
setIsLoading(true);
api.query.system.account(address)
.then((account: any) => {
setBalance({
free: account.data.free.toString(),
reserved: account.data.reserved.toString(),
frozen: account.data.frozen.toString(),
});
setIsLoading(false);
})
.catch((err) => {
setError(err);
setIsLoading(false);
});
}, [api, address]);
return { balance, isLoading, error };
}
```
### 3. useStaking Hook (Oluşturulacak)
**Dosya:** `/home/mamostehp/pwap/shared/hooks/blockchain/useStaking.ts` (YOK)
**Gerekli Queries:**
- `api.query.staking.bonded(address)` - Bonded amount
- `api.query.staking.ledger(address)` - Staking ledger
- `api.query.staking.payee(address)` - Reward destination
### 4. useProposals Hook (Oluşturulacak)
**Dosya:** `/home/mamostehp/pwap/shared/hooks/blockchain/useProposals.ts` (YOK)
**Gerekli Queries:**
- `api.query.welati.proposals()` - All active proposals
- `api.query.welati.proposalCount()` - Total proposal count
## FAZ 1 Tamamlama Planı
### Adım 1: Shared Hooks Oluşturma ⏳
1. `useBalance.ts` - Balance fetching
2. `useStaking.ts` - Staking info
3. `useProposals.ts` - Governance proposals
4. `formatBalance.ts` utility - Token formatting
### Adım 2: DashboardScreen Entegrasyonu ⏳
1. Import shared hooks
2. Replace hardcoded `0.00 HEZ` with real balance
3. Replace hardcoded `0.00` staked amount
4. Replace hardcoded `0.00` rewards
5. Replace hardcoded `0` proposals count
### Adım 3: Error Handling & Loading States ⏳
1. Add loading spinners for blockchain queries
2. Add error messages for failed queries
3. Add retry mechanism
4. Add offline state detection
### Adım 4: Testing ⏳
1. Test with local dev node (ws://localhost:9944)
2. Test with beta testnet
3. Test offline behavior
4. Test error scenarios
## Blockchain Endpoints
### Development
```typescript
const DEV_ENDPOINT = 'ws://localhost:9944';
```
### Beta Testnet
```typescript
const BETA_ENDPOINT = 'ws://beta.pezkuwichain.io:9944';
```
### Mainnet (Future)
```typescript
const MAINNET_ENDPOINT = 'wss://mainnet.pezkuwichain.io';
```
## Dosya Yapısı
```
pwap/
├── mobile/
│ ├── src/
│ │ ├── screens/
│ │ │ ├── WelcomeScreen.tsx ✅ (Tamamlandı)
│ │ │ ├── VerificationScreen.tsx ✅ (Tamamlandı, syntax fix)
│ │ │ ├── DashboardScreen.tsx 🚧 (Blockchain entegrasyonu gerekli)
│ │ │ ├── WalletScreen.tsx ❌ (FAZ 2)
│ │ │ └── SettingsScreen.tsx ❌ (Var, ama update gerekli)
│ │ └── theme/
│ │ └── colors.ts ✅
│ └── docs/
│ ├── QUICK_ACTIONS_IMPLEMENTATION.md ✅ (400+ satır)
│ └── FAZ_1_SUMMARY.md ✅ (Bu dosya)
└── shared/
└── hooks/
└── blockchain/
├── usePolkadotApi.ts ✅ (Tamamlandı)
├── useBalance.ts ❌ (Oluşturulacak)
├── useStaking.ts ❌ (Oluşturulacak)
└── useProposals.ts ❌ (Oluşturulacak)
```
## Sonraki Adımlar (Öncelik Sırasına Göre)
### FAZ 1.3 (Şu An) 🚧
1. `useBalance.ts` hook'unu oluştur
2. `useStaking.ts` hook'unu oluştur
3. `useProposals.ts` hook'unu oluştur
4. `formatBalance.ts` utility'sini oluştur
5. DashboardScreen'e entegre et
6. Test et
### FAZ 1.4 (Sonraki) ⏳
1. Quick Actions navigation'larını ekle
2. Her action için loading state ekle
3. Error handling ekle
4. Offline state detection ekle
### FAZ 2 (Gelecek) 📅
1. WalletScreen - Transfer, Receive, History
2. StakingScreen - Bond, Unbond, Nominate
3. GovernanceScreen - Proposals, Voting
4. DEXScreen - Swap, Liquidity
5. HistoryScreen - Transaction list
6. Detailed documentation (QUICK_ACTIONS_IMPLEMENTATION.md zaten var)
## Beklenen Timeline
- **FAZ 1.3 (Blockchain Bağlantısı):** 2-3 gün
- **FAZ 1.4 (Quick Actions Navigation):** 1 gün
- **FAZ 1 Toplam:** ~1 hafta
- **FAZ 2 (Detaylı Features):** 3-4 hafta (daha önce planlandı)
## Bağımlılıklar
### NPM Paketleri (Zaten Kurulu)
- `@polkadot/api` v16.5.2 ✅
- `@polkadot/util` v13.5.7 ✅
- `@polkadot/util-crypto` v13.5.7 ✅
- `react-i18next`
- `expo-linear-gradient`
### Platform Desteği
- ✅ React Native (mobile)
- ✅ Web (shared hooks platform-agnostic)
## Notlar
### Güvenlik
- Mnemonic/private key'ler SecureStore'da saklanacak
- Biometric authentication FAZ 2'de eklenecek
- Demo mode sadece `__DEV__` flag'inde aktif
### i18n
- 6 dil desteği aktif (EN, TR, KMR, CKB, AR, FA)
- RTL diller için özel layout (AR, FA)
- Çeviriler `/home/mamostehp/pwap/mobile/src/locales/` klasöründe
### Tasarım
- Kurdistan renk paleti: Kesk (green), Zer (yellow), Sor (red), Spi (white), Reş (black)
- Linear gradient backgrounds
- Shadow/elevation effects
- Responsive grid layout
---
**Durum:** FAZ 1.2 tamamlandı, FAZ 1.3 devam ediyor
**Güncelleme:** 2025-11-17
**Yazar:** Claude Code
+24 -24
View File
@@ -405,7 +405,7 @@ export const translations = {
statusRejected: 'Your citizenship application has been rejected. Please check for notifications or contact support for more information.',
},
// Referral Tab - YENİ EKLENDİ
referral: {
referralTab: {
title: 'Referral Program',
subtitle: 'Invite friends and earn rewards',
code: 'Your Referral Code',
@@ -420,7 +420,7 @@ export const translations = {
copiedLinkMessage: 'Your referral link is copied to the clipboard.'
},
// Profile Tab - YENİ EKLENDİ
profile: {
profileTab: {
notLoggedIn: 'Please log in to view your profile.',
editProfile: 'Edit Profile',
walletAddress: 'Wallet Address',
@@ -860,7 +860,7 @@ export const translations = {
statusRejected: 'داواکاری هاوڵاتیبوونت ڕەتکرایەوە. تکایە سەیری ئاگادارکردنەوەکان بکە یان بۆ زانیاری زیاتر پەیوەندی بە پشتگیرییەوە بکە.',
},
// Referral Tab - YENİ EKLENDİ
referral: {
referralTab: {
title: 'بەرنامەی ئاماژەدان',
subtitle: 'هاوڕێکانت بانگهێشت بکە و خەڵات بەدەست بهێنە',
code: 'کۆدی ئاماژەدانەکەت',
@@ -875,7 +875,7 @@ export const translations = {
copiedLinkMessage: 'لینکی ئamaژەدانەکەت بۆ کلیپبۆرد کۆپی کرا.'
},
// Profile Tab - YENİ EKLENDİ
profile: {
profileTab: {
notLoggedIn: 'تکایە بۆ بینینی پڕۆفایلەکەت بچۆ ژوورەوە.',
editProfile: 'دەستکاری پڕۆفایل',
walletAddress: 'ناونیشانی جزدان',
@@ -1311,7 +1311,7 @@ export const translations = {
statusRejected: 'Serlêdana weya hemwelatiyê hate red kirin. Ji kerema xwe ji bo bêtir agahdarî agahdariyan kontrol bikin an bi piştgiriyê re têkilî daynin.',
},
// Referral Tab - YENİ EKLENDİ
referral: {
referralTab: {
title: 'Programa Referansê',
subtitle: 'Hevalên xwe vexwîne û xelatan qezenc bike',
code: 'Koda We ya Referansê',
@@ -1326,7 +1326,7 @@ export const translations = {
copiedLinkMessage: 'Lînka weya referansê li clipboardê hat kopî kirin.'
},
// Profile Tab - YENİ EKLENDİ
profile: {
profileTab: {
notLoggedIn: 'Ji kerema xwe ji bo dîtina profîla xwe têkevin.',
editProfile: 'Profîlê Biguherîne',
walletAddress: 'Navnîşana Berîkê',
@@ -1762,7 +1762,7 @@ export const translations = {
statusRejected: 'تم رفض طلب المواطنة الخاص بك. يرجى التحقق من الإشعارات أو الاتصال بالدعم لمزيد من المعلومات.',
},
// Referral Tab - YENİ EKLENDİ
referral: {
referralTab: {
title: 'برنامج الإحالة',
subtitle: 'ادعُ الأصدقاء واكسب المكافآت',
code: 'رمز الإحالة الخاص بك',
@@ -1777,7 +1777,7 @@ export const translations = {
copiedLinkMessage: 'تم نسخ رابط الإحالة الخاص بك إلى الحافظة.'
},
// Profile Tab - YENİ EKLENDİ
profile: {
profileTab: {
notLoggedIn: 'يرجى تسجيل الدخول لعرض ملفك الشخصي.',
editProfile: 'تعديل الملف الشخصي',
walletAddress: 'عنوان المحفظة',
@@ -2136,22 +2136,22 @@ export const translations = {
statusRejected: 'Vatandaşlık başvurunuz reddedildi. Lütfen bildirimleri kontrol edin veya daha fazla bilgi için destek ile iletişime geçin.',
},
// Referral Tab - YENİ EKLENDİ
referral: {
referralTab: {
title: 'Yönlendirme Programı',
subtitle: 'Arkadaşlarını davet et ve ödüller kazan',
code: 'Yönlendirme Kodunuz',
link: 'Yönlendirme Linkiniz',
code: 'Yönlendirme Kodun',
link: 'Yönlendirme Bağlantın',
count: 'Toplam Davet Edilen',
people: 'Kişi',
errorNoUser: 'Yönlendirme bilgilerini görmek için giriş yapmalısınız.',
errorFetch: 'Yönlendirme bilgileri alınamadı. Lütfen yenilemek için aşağı çekin.',
errorFetch: 'Yönlendirme bilgileri alınamadı. Lütfen yenilemek için çekin.',
copiedCodeTitle: 'Kod Kopyalandı',
copiedCodeMessage: 'Yönlendirme kodunuz panoya kopyalandı.',
copiedLinkTitle: 'Link Kopyalandı',
copiedLinkMessage: 'Yönlendirme linkiniz panoya kopyalandı.'
copiedCodeMessage: 'Yönlendirme kodun panoya kopyalandı.',
copiedLinkTitle: 'Bağlantı Kopyalandı',
copiedLinkMessage: 'Yönlendirme bağlantın panoya kopyalandı.'
},
// Profile Tab - YENİ EKLENDİ
profile: {
profileTab: {
notLoggedIn: 'Profilinizi görüntülemek için lütfen giriş yapın.',
editProfile: 'Profili Düzenle',
walletAddress: 'Cüzdan Adresi',
@@ -2510,29 +2510,29 @@ export const translations = {
statusRejected: 'درخواست شهروندی شما رد شده است. لطفاً اعلان‌ها را بررسی کنید یا برای اطلاعات بیشتر با پشتیبانی تماس بگیرید.',
},
// Referral Tab - YENİ EKLENDİ
referral: {
referralTab: {
title: 'برنامه ارجاع',
subtitle: 'دوستان خود را دعوت کنید و پاداش بگیرید',
code: 'کد ارجاع شما',
link: 'لینک ارجاع شما',
count: 'مجموع دعوتشدگان',
count: 'مجموع دعوت شدگان',
people: 'نفر',
errorNoUser: 'برای مشاهده اطلاعات ارجاع باید وارد شوید.',
errorFetch: 'اطلاعات ارجاع بازیابی نشد. لطفاً برای تازه‌سازی صفحه را به پایین بکشید.',
errorFetch: 'اطلاعات ارجاع دریافت نشد. لطفاً برای تازه کردن بکشید.',
copiedCodeTitle: 'کد کپی شد',
copiedCodeMessage: 'کد ارجاع شما در کلیپبورد کپی شد.',
copiedCodeMessage: 'کد ارجاع شما در کلیپ بورد کپی شد.',
copiedLinkTitle: 'لینک کپی شد',
copiedLinkMessage: 'لینک ارجاع شما در کلیپBورد کپی شد.'
copiedLinkMessage: 'لینک ارجاع شما در کلیپ بورد کپی شد.'
},
// Profile Tab - YENİ EKLENDİ
profile: {
profileTab: {
notLoggedIn: 'لطفاً برای مشاهده پروفایل خود وارد شوید.',
editProfile: 'ویرایش پروفایل',
walletAddress: 'آدرس کیف پول',
changePassword: 'تغییر رمز عبور',
security: 'امنیت و 2FA',
signOutAlertTitle: 'خروج از حساب',
signOutAlertMessage: 'آیا برای خروج از حساب مطمئن هستید؟',
signOutAlertTitle: 'خروج از سیستم',
signOutAlertMessage: 'آیا مطمئن هستید که می خواهید از سیستم خارج شوید؟',
},
// Send Modal - YENİ EKLENDİ
sendModal: {
+39
View File
@@ -0,0 +1,39 @@
import { toast } from 'sonner';
const PINATA_JWT = import.meta.env.VITE_PINATA_JWT;
const PINATA_API = 'https://api.pinata.cloud/pinning/pinFileToIPFS';
export async function uploadToIPFS(file: File): Promise<string> {
if (!PINATA_JWT || PINATA_JWT === 'your_pinata_jwt_here') {
throw new Error('Pinata JWT not configured. Set VITE_PINATA_JWT in .env');
}
const formData = new FormData();
formData.append('file', file);
try {
const response = await fetch(PINATA_API, {
method: 'POST',
headers: {
'Authorization': `Bearer ${PINATA_JWT}`,
},
body: formData,
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
throw new Error(errorData.error || `Upload failed: ${response.statusText}`);
}
const data = await response.json();
return data.IpfsHash; // Returns: Qm...
} catch (error) {
console.error('IPFS upload error:', error);
toast.error('Failed to upload to IPFS');
throw error;
}
}
export function getIPFSUrl(hash: string): string {
return `https://gateway.pinata.cloud/ipfs/${hash}`;
}
+306 -350
View File
@@ -1,416 +1,372 @@
import { ApiPromise } from '@polkadot/api';
import { SubmittableExtrinsic } from '@polkadot/api/types';
import { InjectedAccountWithMeta } from '@polkadot/extension-inject/types';
import { toast } from 'sonner';
import { supabase } from '@/lib/supabase';
/**
* Perwerde (Education) Pallet Integration
*
* This module provides helper functions for interacting with the Perwerde pallet,
* which handles:
* - Course creation and management
* - Student enrollment
* - Course completion tracking
* - Education points/scores
* Course data structure matching blockchain pallet
*/
import type { ApiPromise } from '@polkadot/api';
import type { Option } from '@polkadot/types';
// ============================================================================
// TYPE DEFINITIONS
// ============================================================================
export type CourseStatus = 'Active' | 'Archived';
export interface Course {
id: number;
owner: string;
name: string;
description: string;
contentLink: string;
status: CourseStatus;
createdAt: number;
content_link: string; // IPFS hash
status: 'Active' | 'Archived';
created_at: string;
}
/**
* Enrollment data structure
*/
export interface Enrollment {
student: string;
courseId: number;
enrolledAt: number;
completedAt?: number;
pointsEarned: number;
isCompleted: boolean;
}
export interface StudentProgress {
totalCourses: number;
completedCourses: number;
totalPoints: number;
activeCourses: number;
}
// ============================================================================
// QUERY FUNCTIONS (Read-only)
// ============================================================================
/**
* Get all courses (active and archived)
*/
export async function getAllCourses(api: ApiPromise): Promise<Course[]> {
const nextId = await api.query.perwerde.nextCourseId();
const currentId = (nextId.toJSON() as number) || 0;
const courses: Course[] = [];
for (let i = 0; i < currentId; i++) {
const courseOption = await api.query.perwerde.courses(i);
if (courseOption.isSome) {
const courseData = courseOption.unwrap().toJSON() as any;
courses.push({
id: i,
owner: courseData.owner,
name: hexToString(courseData.name),
description: hexToString(courseData.description),
contentLink: hexToString(courseData.contentLink),
status: courseData.status as CourseStatus,
createdAt: courseData.createdAt,
});
}
}
return courses;
id: string;
student_address: string;
course_id: number;
enrolled_at: string;
completed_at?: string;
points_earned: number;
is_completed: boolean;
}
/**
* Get active courses only
*/
export async function getActiveCourses(api: ApiPromise): Promise<Course[]> {
const allCourses = await getAllCourses(api);
return allCourses.filter((course) => course.status === 'Active');
}
/**
* Get course by ID
*/
export async function getCourseById(api: ApiPromise, courseId: number): Promise<Course | null> {
const courseOption = await api.query.perwerde.courses(courseId);
if (courseOption.isNone) {
return null;
}
const courseData = courseOption.unwrap().toJSON() as any;
return {
id: courseId,
owner: courseData.owner,
name: hexToString(courseData.name),
description: hexToString(courseData.description),
contentLink: hexToString(courseData.contentLink),
status: courseData.status as CourseStatus,
createdAt: courseData.createdAt,
};
}
/**
* Get student's enrolled courses
*/
export async function getStudentCourses(api: ApiPromise, studentAddress: string): Promise<number[]> {
const coursesOption = await api.query.perwerde.studentCourses(studentAddress);
if (coursesOption.isNone || coursesOption.isEmpty) {
return [];
}
return (coursesOption.toJSON() as number[]) || [];
}
/**
* Get enrollment details for a student in a specific course
*/
export async function getEnrollment(
api: ApiPromise,
studentAddress: string,
courseId: number
): Promise<Enrollment | null> {
const enrollmentOption = await api.query.perwerde.enrollments([studentAddress, courseId]);
if (enrollmentOption.isNone) {
return null;
}
const enrollmentData = enrollmentOption.unwrap().toJSON() as any;
return {
student: enrollmentData.student,
courseId: enrollmentData.courseId,
enrolledAt: enrollmentData.enrolledAt,
completedAt: enrollmentData.completedAt || undefined,
pointsEarned: enrollmentData.pointsEarned || 0,
isCompleted: !!enrollmentData.completedAt,
};
}
/**
* Get student's progress summary
*/
export async function getStudentProgress(api: ApiPromise, studentAddress: string): Promise<StudentProgress> {
const courseIds = await getStudentCourses(api, studentAddress);
let completedCourses = 0;
let totalPoints = 0;
for (const courseId of courseIds) {
const enrollment = await getEnrollment(api, studentAddress, courseId);
if (enrollment) {
if (enrollment.isCompleted) {
completedCourses++;
totalPoints += enrollment.pointsEarned;
}
}
}
return {
totalCourses: courseIds.length,
completedCourses,
totalPoints,
activeCourses: courseIds.length - completedCourses,
};
}
/**
* Get Perwerde score for a student (sum of all earned points)
*/
export async function getPerwerdeScore(api: ApiPromise, studentAddress: string): Promise<number> {
try {
// Try to call the get_perwerde_score runtime API
// This might not exist in all versions, fallback to manual calculation
const score = await api.call.perwerdeApi?.getPerwerdeScore(studentAddress);
return score ? (score.toJSON() as number) : 0;
} catch (error) {
// Fallback: manually sum all points
const progress = await getStudentProgress(api, studentAddress);
return progress.totalPoints;
}
}
/**
* Check if student is enrolled in a course
*/
export async function isEnrolled(
api: ApiPromise,
studentAddress: string,
courseId: number
): Promise<boolean> {
const enrollment = await getEnrollment(api, studentAddress, courseId);
return enrollment !== null;
}
/**
* Get course enrollment statistics
*/
export async function getCourseStats(
api: ApiPromise,
courseId: number
): Promise<{
totalEnrollments: number;
completions: number;
averagePoints: number;
}> {
// Note: This requires iterating through all enrollments, which can be expensive
// In production, consider caching or maintaining separate counters
const entries = await api.query.perwerde.enrollments.entries();
let totalEnrollments = 0;
let completions = 0;
let totalPoints = 0;
for (const [key, value] of entries) {
const enrollmentData = value.toJSON() as any;
const enrollmentCourseId = (key.args[1] as any).toNumber();
if (enrollmentCourseId === courseId) {
totalEnrollments++;
if (enrollmentData.completedAt) {
completions++;
totalPoints += enrollmentData.pointsEarned || 0;
}
}
}
return {
totalEnrollments,
completions,
averagePoints: completions > 0 ? Math.round(totalPoints / completions) : 0,
};
}
// ============================================================================
// TRANSACTION FUNCTIONS
// ============================================================================
/**
* Create a new course
* @requires AdminOrigin (only admin can create courses in current implementation)
* Create a new course on blockchain and sync to Supabase
*
* Flow:
* 1. Call blockchain create_course extrinsic
* 2. Wait for block inclusion
* 3. Extract course_id from event
* 4. Insert to Supabase with blockchain course_id
*/
export async function createCourse(
api: ApiPromise,
signer: any,
account: InjectedAccountWithMeta,
name: string,
description: string,
contentLink: string
): Promise<void> {
const tx = api.tx.perwerde.createCourse(name, description, contentLink);
ipfsHash: string
): Promise<number> {
try {
// Convert strings to bounded vecs (Vec<u8>)
const nameVec = Array.from(new TextEncoder().encode(name));
const descVec = Array.from(new TextEncoder().encode(description));
const linkVec = Array.from(new TextEncoder().encode(ipfsHash));
return new Promise((resolve, reject) => {
tx.signAndSend(signer, ({ status, dispatchError }) => {
if (status.isInBlock) {
if (dispatchError) {
reject(dispatchError);
} else {
resolve();
// Create extrinsic
const extrinsic = api.tx.perwerde.createCourse(nameVec, descVec, linkVec);
// Sign and send
const courseId = await new Promise<number>((resolve, reject) => {
let unsub: () => void;
extrinsic.signAndSend(
account.address,
({ status, events, dispatchError }) => {
if (dispatchError) {
if (dispatchError.isModule) {
const decoded = api.registry.findMetaError(dispatchError.asModule);
reject(new Error(`${decoded.section}.${decoded.name}: ${decoded.docs}`));
} else {
reject(new Error(dispatchError.toString()));
}
if (unsub) unsub();
return;
}
if (status.isInBlock || status.isFinalized) {
// Find CourseCreated event
const courseCreatedEvent = events.find(
({ event }) =>
event.section === 'perwerde' && event.method === 'CourseCreated'
);
if (courseCreatedEvent) {
const courseId = courseCreatedEvent.event.data[0].toString();
resolve(parseInt(courseId));
} else {
reject(new Error('CourseCreated event not found'));
}
if (unsub) unsub();
}
}
}
).then((unsubscribe) => {
unsub = unsubscribe;
});
});
});
// Insert to Supabase
const { error: supabaseError } = await supabase.from('courses').insert({
id: courseId,
owner: account.address,
name,
description,
content_link: ipfsHash,
status: 'Active',
created_at: new Date().toISOString(),
});
if (supabaseError) {
console.error('Supabase insert failed:', supabaseError);
toast.error('Course created on blockchain but failed to sync to database');
} else {
toast.success(`Course created with ID: ${courseId}`);
}
return courseId;
} catch (error) {
console.error('Create course error:', error);
toast.error(error instanceof Error ? error.message : 'Failed to create course');
throw error;
}
}
/**
* Enroll in a course
* Enroll student in a course
*/
export async function enrollInCourse(
api: ApiPromise,
signerAddress: string,
account: InjectedAccountWithMeta,
courseId: number
): Promise<void> {
const tx = api.tx.perwerde.enroll(courseId);
try {
const extrinsic = api.tx.perwerde.enroll(courseId);
return new Promise((resolve, reject) => {
tx.signAndSend(signerAddress, ({ status, dispatchError }) => {
if (status.isInBlock) {
if (dispatchError) {
reject(dispatchError);
} else {
resolve();
await new Promise<void>((resolve, reject) => {
let unsub: () => void;
extrinsic.signAndSend(
account.address,
({ status, events, dispatchError }) => {
if (dispatchError) {
if (dispatchError.isModule) {
const decoded = api.registry.findMetaError(dispatchError.asModule);
reject(new Error(`${decoded.section}.${decoded.name}: ${decoded.docs}`));
} else {
reject(new Error(dispatchError.toString()));
}
if (unsub) unsub();
return;
}
if (status.isInBlock || status.isFinalized) {
resolve();
if (unsub) unsub();
}
}
}
).then((unsubscribe) => {
unsub = unsubscribe;
});
});
});
// Insert enrollment to Supabase
const { error: supabaseError } = await supabase.from('enrollments').insert({
student_address: account.address,
course_id: courseId,
enrolled_at: new Date().toISOString(),
is_completed: false,
points_earned: 0,
});
if (supabaseError) {
console.error('Supabase enrollment insert failed:', supabaseError);
toast.error('Enrolled on blockchain but failed to sync to database');
} else {
toast.success('Successfully enrolled in course');
}
} catch (error) {
console.error('Enroll error:', error);
toast.error(error instanceof Error ? error.message : 'Failed to enroll in course');
throw error;
}
}
/**
* Complete a course
* @requires Course owner to call this for student
* Mark course as completed (student self-completes)
*/
export async function completeCourse(
api: ApiPromise,
signer: any,
studentAddress: string,
account: InjectedAccountWithMeta,
courseId: number,
points: number
): Promise<void> {
const tx = api.tx.perwerde.completeCourse(courseId, points);
try {
const extrinsic = api.tx.perwerde.completeCourse(courseId, points);
return new Promise((resolve, reject) => {
tx.signAndSend(signer, ({ status, dispatchError }) => {
if (status.isInBlock) {
if (dispatchError) {
reject(dispatchError);
} else {
resolve();
await new Promise<void>((resolve, reject) => {
let unsub: () => void;
extrinsic.signAndSend(
account.address,
({ status, dispatchError }) => {
if (dispatchError) {
if (dispatchError.isModule) {
const decoded = api.registry.findMetaError(dispatchError.asModule);
reject(new Error(`${decoded.section}.${decoded.name}: ${decoded.docs}`));
} else {
reject(new Error(dispatchError.toString()));
}
if (unsub) unsub();
return;
}
if (status.isInBlock || status.isFinalized) {
resolve();
if (unsub) unsub();
}
}
}
).then((unsubscribe) => {
unsub = unsubscribe;
});
});
});
// Update enrollment in Supabase
const { error: supabaseError } = await supabase
.from('enrollments')
.update({
is_completed: true,
completed_at: new Date().toISOString(),
points_earned: points,
})
.eq('student_address', account.address)
.eq('course_id', courseId);
if (supabaseError) {
console.error('Supabase completion update failed:', supabaseError);
toast.error('Completed on blockchain but failed to sync to database');
} else {
toast.success(`Course completed! Earned ${points} points`);
}
} catch (error) {
console.error('Complete course error:', error);
toast.error(error instanceof Error ? error.message : 'Failed to complete course');
throw error;
}
}
/**
* Archive a course
* @requires Course owner
* Archive a course (admin/owner only)
*/
export async function archiveCourse(
api: ApiPromise,
signer: any,
account: InjectedAccountWithMeta,
courseId: number
): Promise<void> {
const tx = api.tx.perwerde.archiveCourse(courseId);
try {
const extrinsic = api.tx.perwerde.archiveCourse(courseId);
return new Promise((resolve, reject) => {
tx.signAndSend(signer, ({ status, dispatchError }) => {
if (status.isInBlock) {
if (dispatchError) {
reject(dispatchError);
} else {
resolve();
await new Promise<void>((resolve, reject) => {
let unsub: () => void;
extrinsic.signAndSend(
account.address,
({ status, dispatchError }) => {
if (dispatchError) {
if (dispatchError.isModule) {
const decoded = api.registry.findMetaError(dispatchError.asModule);
reject(new Error(`${decoded.section}.${decoded.name}: ${decoded.docs}`));
} else {
reject(new Error(dispatchError.toString()));
}
if (unsub) unsub();
return;
}
if (status.isInBlock || status.isFinalized) {
resolve();
if (unsub) unsub();
}
}
}
).then((unsubscribe) => {
unsub = unsubscribe;
});
});
});
}
// ============================================================================
// HELPER FUNCTIONS
// ============================================================================
// Update course status in Supabase
const { error: supabaseError } = await supabase
.from('courses')
.update({ status: 'Archived' })
.eq('id', courseId);
/**
* Convert hex string to UTF-8 string
*/
function hexToString(hex: any): string {
if (!hex) return '';
// If it's already a string, return it
if (typeof hex === 'string' && !hex.startsWith('0x')) {
return hex;
}
// If it's a hex string, convert it
const hexStr = hex.toString().replace(/^0x/, '');
let str = '';
for (let i = 0; i < hexStr.length; i += 2) {
const code = parseInt(hexStr.substr(i, 2), 16);
if (code !== 0) {
// Skip null bytes
str += String.fromCharCode(code);
if (supabaseError) {
console.error('Supabase archive update failed:', supabaseError);
toast.error('Archived on blockchain but failed to sync to database');
} else {
toast.success('Course archived');
}
}
return str.trim();
}
/**
* Get course difficulty label (based on points threshold)
*/
export function getCourseDifficulty(averagePoints: number): {
label: string;
color: string;
} {
if (averagePoints >= 100) {
return { label: 'Advanced', color: 'red' };
} else if (averagePoints >= 50) {
return { label: 'Intermediate', color: 'yellow' };
} else {
return { label: 'Beginner', color: 'green' };
} catch (error) {
console.error('Archive course error:', error);
toast.error(error instanceof Error ? error.message : 'Failed to archive course');
throw error;
}
}
/**
* Format IPFS link to gateway URL
* Get Perwerde score for a student (from blockchain)
*/
export function formatIPFSLink(ipfsHash: string): string {
if (!ipfsHash) return '';
export async function getPerwerdeScore(
api: ApiPromise,
studentAddress: string
): Promise<number> {
try {
// This would require a custom RPC or query if exposed
// For now, calculate from Supabase
const { data, error } = await supabase
.from('enrollments')
.select('points_earned')
.eq('student_address', studentAddress)
.eq('is_completed', true);
// If already a full URL, return it
if (ipfsHash.startsWith('http')) {
return ipfsHash;
if (error) throw error;
const totalPoints = data?.reduce((sum, e) => sum + e.points_earned, 0) || 0;
return totalPoints;
} catch (error) {
console.error('Get Perwerde score error:', error);
return 0;
}
}
/**
* Fetch all courses from Supabase
*/
export async function getCourses(status?: 'Active' | 'Archived'): Promise<Course[]> {
try {
let query = supabase.from('courses').select('*').order('created_at', { ascending: false });
if (status) {
query = query.eq('status', status);
}
const { data, error } = await query;
if (error) throw error;
return data || [];
} catch (error) {
console.error('Get courses error:', error);
toast.error('Failed to fetch courses');
return [];
}
}
/**
* Fetch student enrollments
*/
export async function getStudentEnrollments(studentAddress: string): Promise<Enrollment[]> {
try {
const { data, error } = await supabase
.from('enrollments')
.select('*')
.eq('student_address', studentAddress)
.order('enrolled_at', { ascending: false });
if (error) throw error;
return data || [];
} catch (error) {
console.error('Get enrollments error:', error);
toast.error('Failed to fetch enrollments');
return [];
}
// If starts with ipfs://, convert to gateway
if (ipfsHash.startsWith('ipfs://')) {
const hash = ipfsHash.replace('ipfs://', '');
return `https://ipfs.io/ipfs/${hash}`;
}
// If it's just a hash, add gateway
return `https://ipfs.io/ipfs/${ipfsHash}`;
}
+375
View File
@@ -0,0 +1,375 @@
import { ApiPromise } from '@polkadot/api';
import { InjectedAccountWithMeta } from '@polkadot/extension-inject/types';
import { toast } from 'sonner';
/**
* Validator pool categories from runtime
*/
export enum ValidatorPoolCategory {
StakeValidator = 'StakeValidator',
ParliamentaryValidator = 'ParliamentaryValidator',
MeritValidator = 'MeritValidator',
}
/**
* Pool member information
*/
export interface PoolMember {
address: string;
category: ValidatorPoolCategory;
joinedAt: number;
}
/**
* Validator set structure
*/
export interface ValidatorSet {
stake_validators: string[];
parliamentary_validators: string[];
merit_validators: string[];
total_count: number;
}
/**
* Performance metrics
*/
export interface PerformanceMetrics {
blocks_produced: number;
blocks_missed: number;
era_points: number;
reputation_score: number;
}
/**
* Join validator pool with specified category
*/
export async function joinValidatorPool(
api: ApiPromise,
account: InjectedAccountWithMeta,
category: ValidatorPoolCategory
): Promise<void> {
try {
// Convert category to runtime enum
const categoryEnum = { [category]: null };
const extrinsic = api.tx.validatorPool.joinValidatorPool(categoryEnum);
await new Promise<void>((resolve, reject) => {
let unsub: () => void;
extrinsic.signAndSend(
account.address,
({ status, dispatchError }) => {
if (dispatchError) {
if (dispatchError.isModule) {
const decoded = api.registry.findMetaError(dispatchError.asModule);
const errorMsg = `${decoded.section}.${decoded.name}`;
// User-friendly error messages
if (errorMsg === 'validatorPool.InsufficientTrustScore') {
reject(new Error('Insufficient trust score. Minimum 500 required.'));
} else if (errorMsg === 'validatorPool.AlreadyInPool') {
reject(new Error('Already in validator pool'));
} else if (errorMsg === 'validatorPool.MissingRequiredTiki') {
reject(new Error('Missing required Tiki citizenship for this category'));
} else {
reject(new Error(errorMsg));
}
} else {
reject(new Error(dispatchError.toString()));
}
if (unsub) unsub();
return;
}
if (status.isInBlock || status.isFinalized) {
toast.success(`Joined ${category} pool successfully`);
resolve();
if (unsub) unsub();
}
}
).then((unsubscribe) => {
unsub = unsubscribe;
});
});
} catch (error) {
console.error('Join validator pool error:', error);
toast.error(error instanceof Error ? error.message : 'Failed to join validator pool');
throw error;
}
}
/**
* Leave validator pool
*/
export async function leaveValidatorPool(
api: ApiPromise,
account: InjectedAccountWithMeta
): Promise<void> {
try {
const extrinsic = api.tx.validatorPool.leaveValidatorPool();
await new Promise<void>((resolve, reject) => {
let unsub: () => void;
extrinsic.signAndSend(
account.address,
({ status, dispatchError }) => {
if (dispatchError) {
if (dispatchError.isModule) {
const decoded = api.registry.findMetaError(dispatchError.asModule);
const errorMsg = `${decoded.section}.${decoded.name}`;
if (errorMsg === 'validatorPool.NotInPool') {
reject(new Error('Not currently in validator pool'));
} else {
reject(new Error(errorMsg));
}
} else {
reject(new Error(dispatchError.toString()));
}
if (unsub) unsub();
return;
}
if (status.isInBlock || status.isFinalized) {
toast.success('Left validator pool successfully');
resolve();
if (unsub) unsub();
}
}
).then((unsubscribe) => {
unsub = unsubscribe;
});
});
} catch (error) {
console.error('Leave validator pool error:', error);
toast.error(error instanceof Error ? error.message : 'Failed to leave validator pool');
throw error;
}
}
/**
* Update validator category
*/
export async function updateValidatorCategory(
api: ApiPromise,
account: InjectedAccountWithMeta,
newCategory: ValidatorPoolCategory
): Promise<void> {
try {
const categoryEnum = { [newCategory]: null };
const extrinsic = api.tx.validatorPool.updateCategory(categoryEnum);
await new Promise<void>((resolve, reject) => {
let unsub: () => void;
extrinsic.signAndSend(
account.address,
({ status, dispatchError }) => {
if (dispatchError) {
if (dispatchError.isModule) {
const decoded = api.registry.findMetaError(dispatchError.asModule);
reject(new Error(`${decoded.section}.${decoded.name}`));
} else {
reject(new Error(dispatchError.toString()));
}
if (unsub) unsub();
return;
}
if (status.isInBlock || status.isFinalized) {
toast.success(`Category updated to ${newCategory}`);
resolve();
if (unsub) unsub();
}
}
).then((unsubscribe) => {
unsub = unsubscribe;
});
});
} catch (error) {
console.error('Update category error:', error);
toast.error(error instanceof Error ? error.message : 'Failed to update category');
throw error;
}
}
/**
* Get validator pool member info
*/
export async function getPoolMember(
api: ApiPromise,
address: string
): Promise<ValidatorPoolCategory | null> {
try {
const member = await api.query.validatorPool.poolMembers(address);
if (member.isNone) {
return null;
}
const category = member.unwrap();
// Parse category enum
if (category.isStakeValidator) {
return ValidatorPoolCategory.StakeValidator;
} else if (category.isParliamentaryValidator) {
return ValidatorPoolCategory.ParliamentaryValidator;
} else if (category.isMeritValidator) {
return ValidatorPoolCategory.MeritValidator;
}
return null;
} catch (error) {
console.error('Get pool member error:', error);
return null;
}
}
/**
* Get total pool size
*/
export async function getPoolSize(api: ApiPromise): Promise<number> {
try {
const size = await api.query.validatorPool.poolSize();
return size.toNumber();
} catch (error) {
console.error('Get pool size error:', error);
return 0;
}
}
/**
* Get current validator set
*/
export async function getCurrentValidatorSet(api: ApiPromise): Promise<ValidatorSet | null> {
try {
const validatorSet = await api.query.validatorPool.currentValidatorSet();
if (validatorSet.isNone) {
return null;
}
const set = validatorSet.unwrap();
return {
stake_validators: set.stakeValidators.map((v: any) => v.toString()),
parliamentary_validators: set.parliamentaryValidators.map((v: any) => v.toString()),
merit_validators: set.meritValidators.map((v: any) => v.toString()),
total_count: set.totalCount.toNumber(),
};
} catch (error) {
console.error('Get validator set error:', error);
return null;
}
}
/**
* Get current era
*/
export async function getCurrentEra(api: ApiPromise): Promise<number> {
try {
const era = await api.query.validatorPool.currentEra();
return era.toNumber();
} catch (error) {
console.error('Get current era error:', error);
return 0;
}
}
/**
* Get performance metrics for a validator
*/
export async function getPerformanceMetrics(
api: ApiPromise,
address: string
): Promise<PerformanceMetrics> {
try {
const metrics = await api.query.validatorPool.performanceMetrics(address);
return {
blocks_produced: metrics.blocksProduced.toNumber(),
blocks_missed: metrics.blocksMissed.toNumber(),
era_points: metrics.eraPoints.toNumber(),
reputation_score: metrics.reputationScore.toNumber(),
};
} catch (error) {
console.error('Get performance metrics error:', error);
return {
blocks_produced: 0,
blocks_missed: 0,
era_points: 0,
reputation_score: 0,
};
}
}
/**
* Get all pool members (requires iterating storage)
*/
export async function getAllPoolMembers(api: ApiPromise): Promise<PoolMember[]> {
try {
const entries = await api.query.validatorPool.poolMembers.entries();
const members: PoolMember[] = entries.map(([key, value]) => {
const address = key.args[0].toString();
const category = value.unwrap();
let categoryType: ValidatorPoolCategory;
if (category.isStakeValidator) {
categoryType = ValidatorPoolCategory.StakeValidator;
} else if (category.isParliamentaryValidator) {
categoryType = ValidatorPoolCategory.ParliamentaryValidator;
} else {
categoryType = ValidatorPoolCategory.MeritValidator;
}
return {
address,
category: categoryType,
joinedAt: 0, // Block number not stored in this version
};
});
return members;
} catch (error) {
console.error('Get all pool members error:', error);
return [];
}
}
/**
* Check if address meets requirements for category
*/
export async function checkCategoryRequirements(
api: ApiPromise,
address: string,
category: ValidatorPoolCategory
): Promise<{ eligible: boolean; reason?: string }> {
try {
// Get trust score
const trustScore = await api.query.trust.trustScores(address);
const score = trustScore.toNumber();
if (score < 500) {
return { eligible: false, reason: 'Trust score below 500' };
}
// Check Tiki for Parliamentary/Merit validators
if (
category === ValidatorPoolCategory.ParliamentaryValidator ||
category === ValidatorPoolCategory.MeritValidator
) {
const tikiScore = await api.query.tiki.tikiScores(address);
if (tikiScore.isNone || tikiScore.unwrap().toNumber() === 0) {
return { eligible: false, reason: 'Tiki citizenship required' };
}
}
return { eligible: true };
} catch (error) {
console.error('Check category requirements error:', error);
return { eligible: false, reason: 'Failed to check requirements' };
}
}
+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>
);
}
@@ -0,0 +1,85 @@
-- Perwerde (Education) Tables
-- Courses Table (ID comes from blockchain)
CREATE TABLE IF NOT EXISTS public.courses (
id BIGINT PRIMARY KEY, -- Blockchain course_id
owner TEXT NOT NULL,
name TEXT NOT NULL,
description TEXT,
content_link TEXT, -- IPFS hash
status TEXT NOT NULL DEFAULT 'Active',
created_at TIMESTAMP WITH TIME ZONE NOT NULL
);
-- Enrollments Table
CREATE TABLE IF NOT EXISTS public.enrollments (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
student_address TEXT NOT NULL,
course_id BIGINT REFERENCES public.courses(id) ON DELETE CASCADE,
enrolled_at TIMESTAMP WITH TIME ZONE NOT NULL,
completed_at TIMESTAMP WITH TIME ZONE,
points_earned INTEGER DEFAULT 0,
is_completed BOOLEAN DEFAULT false,
UNIQUE(student_address, course_id)
);
-- Indexes
CREATE INDEX IF NOT EXISTS idx_courses_status ON public.courses(status);
CREATE INDEX IF NOT EXISTS idx_enrollments_student ON public.enrollments(student_address);
CREATE INDEX IF NOT EXISTS idx_enrollments_course ON public.enrollments(course_id);
-- RLS Policies
-- Courses
ALTER TABLE public.courses ENABLE ROW LEVEL SECURITY;
DROP POLICY IF EXISTS "Anyone can view courses" ON public.courses;
CREATE POLICY "Anyone can view courses"
ON public.courses FOR SELECT
USING (true);
DROP POLICY IF EXISTS "Admins can manage courses" ON public.courses;
CREATE POLICY "Admins can manage courses"
ON public.courses FOR ALL
USING (
EXISTS (
SELECT 1 FROM public.admin_roles
WHERE user_id = auth.uid()
)
);
-- Enrollments
ALTER TABLE public.enrollments ENABLE ROW LEVEL SECURITY;
DROP POLICY IF EXISTS "Users can view their own enrollments" ON public.enrollments;
CREATE POLICY "Users can view their own enrollments"
ON public.enrollments FOR SELECT
USING (
EXISTS (
SELECT 1 FROM public.wallets
WHERE user_id = auth.uid() AND address = student_address
)
);
DROP POLICY IF EXISTS "Users can create their own enrollments" ON public.enrollments;
CREATE POLICY "Users can create their own enrollments"
ON public.enrollments FOR INSERT
WITH CHECK (
EXISTS (
SELECT 1 FROM public.wallets
WHERE user_id = auth.uid() AND address = student_address
)
);
DROP POLICY IF EXISTS "Admins or course owners can update enrollments" ON public.enrollments;
CREATE POLICY "Admins or course owners can update enrollments"
ON public.enrollments FOR UPDATE
USING (
EXISTS (
SELECT 1 FROM public.admin_roles
WHERE user_id = auth.uid()
) OR
EXISTS (
SELECT 1 FROM public.courses c
JOIN public.wallets w ON c.owner = w.address
WHERE c.id = course_id AND w.user_id = auth.uid()
)
);
+1 -1
View File
@@ -27,5 +27,5 @@
"@/*": ["./src/*"]
}
},
"include": ["src"]
"include": ["src", "../shared"]
}
+3 -1
View File
@@ -12,7 +12,9 @@
"@pezkuwi/lib": ["../shared/lib"],
"@pezkuwi/utils": ["../shared/utils"],
"@pezkuwi/theme": ["../shared/theme"],
"@pezkuwi/types": ["../shared/types"]
"@pezkuwi/types": ["../shared/types"],
"@pezkuwi/components/*": ["../shared/components/*"],
"@shared/*": ["../shared/*"]
},
"strict": true,
"noImplicitAny": true,
+3 -1
View File
@@ -31,8 +31,10 @@ export default defineConfig(({ mode }) => ({
"@pezkuwi/utils": path.resolve(__dirname, "../shared/utils"),
"@pezkuwi/theme": path.resolve(__dirname, "../shared/theme"),
"@pezkuwi/types": path.resolve(__dirname, "../shared/types"),
"@pezkuwi/components": path.resolve(__dirname, "../shared/components"),
"@shared": path.resolve(__dirname, "../shared"),
},
dedupe: ['@polkadot/util-crypto', '@polkadot/util', '@polkadot/api', '@polkadot/extension-dapp', '@polkadot/keyring'],
dedupe: ['react', 'lucide-react', 'sonner', '@polkadot/util-crypto', '@polkadot/util', '@polkadot/api', '@polkadot/extension-dapp', '@polkadot/keyring'],
},
optimizeDeps: {
include: ['@polkadot/util-crypto', '@polkadot/util', '@polkadot/api', '@polkadot/extension-dapp', '@polkadot/keyring'],