# CLAUDE.md - AI Assistant Guide for PezkuwiChain Web App Projects **Last Updated:** 2025-11-17 **Production Status:** ~95% Complete **Active Network:** Beta Testnet (`wss://rpc.pezkuwichain.io:9944`) --- ## 🎯 Quick Start for AI Assistants This is a **production-grade blockchain monorepo** for PezkuwiChain with live validators running on VPS. Exercise extreme caution when making changes that could affect blockchain operations. ### Critical Rules (READ FIRST!) ⚠️ **NEVER DO THESE WITHOUT EXPLICIT USER PERMISSION:** 1. **DO NOT** restart or stop VPS validators (7 validators currently finalizing blocks) 2. **DO NOT** modify chain specs (`/root/pezkuwi-sdk/chain-specs/beta/beta-testnet-raw.json`) 3. **DO NOT** change blockchain base paths or validator configurations 4. **DO NOT** commit `.env` files or secrets to git 5. **DO NOT** deploy to production without testing locally first 6. **DO NOT** make assumptions about blockchain operations - **ALWAYS ASK** ### VPS Infrastructure - **IP:** 37.60.230.9 - **Validators:** 7 running (ports 30333-30339, RPC 9944-9950) - **Frontend:** Nginx serving at `/var/www/pezkuwichain/web/dist/` - **Blockchain:** LIVE on Beta Testnet - handle with care --- ## 📁 Repository Structure ``` pezkuwi-web-app-projects/ ├── web/ # Main React web app (Vite + TypeScript) - 90% complete ├── mobile/ # React Native Expo app - 50% complete ├── pezkuwi-sdk-ui/ # Polkadot.js SDK UI (branded clone) - 47MB ├── shared/ # Shared code library (types, utils, blockchain, i18n) ├── README.md # Project overview ├── PRODUCTION_READINESS.md # Production status report └── CLAUDE_README_KRITIK.md # CRITICAL operational guidelines (Turkish) ``` ### Directory Breakdown | Directory | Size | Status | Purpose | |-----------|------|--------|---------| | `web/` | 3.8MB | 90% | Main production web application | | `mobile/` | 737KB | 50% | iOS/Android mobile app | | `pezkuwi-sdk-ui/` | 47MB | Active | Polkadot.js Apps clone | | `shared/` | 402KB | 100% | Shared libraries & utilities | --- ## 🛠️ Tech Stack ### Web Application (`/web/`) | Category | Technology | Version | Purpose | |----------|-----------|---------|---------| | **Framework** | React | 18.3.1 | UI framework | | **Language** | TypeScript | 5.5.3 | Type safety | | **Build Tool** | Vite | 5.4.1 | Fast bundler with HMR | | **Blockchain** | Polkadot.js API | 16.4.9 | Blockchain integration | | **Backend** | Supabase | 2.49.4 | Auth & Database | | **UI Library** | shadcn/ui | Latest | Radix UI components | | **Styling** | Tailwind CSS | 3.4.11 | Utility-first CSS | | **State** | React Context | - | Global state management | | **Data Fetching** | TanStack Query | 5.56.2 | Server state caching | | **Routing** | React Router | 6.26.2 | Client-side routing | | **i18n** | i18next | 23.7.6 | 6-language support | | **Forms** | React Hook Form | 7.53.0 | Form management | | **Validation** | Zod | 3.23.8 | Schema validation | | **Charts** | Recharts | 2.12.7 | Data visualization | | **Icons** | Lucide React | 0.462.0 | Icon library | | **Notifications** | Sonner | 1.5.0 | Toast notifications | ### Mobile Application (`/mobile/`) | Category | Technology | Version | Purpose | |----------|-----------|---------|---------| | **Framework** | React Native | 0.81.5 | Mobile framework | | **Runtime** | Expo | 54.0.23 | Development platform | | **Navigation** | React Navigation | 7.x | Native navigation | | **Blockchain** | Polkadot.js API | 16.5.2 | Blockchain integration | | **Storage** | AsyncStorage | 2.2.0 | Persistent storage | | **Security** | Expo SecureStore | 15.0.7 | Encrypted storage | | **Biometrics** | expo-local-authentication | 17.0.7 | Fingerprint/FaceID | | **i18n** | i18next | 25.6.2 | Multi-language | ### Shared Library (`/shared/`) - **Language:** TypeScript (100% typed) - **Runtime:** Platform-agnostic (Node.js + Browser + React Native) - **Dependencies:** Minimal (Polkadot.js only) --- ## 🔑 Key Files & Entry Points ### Web Application **Entry Points:** - `web/src/main.tsx` - React root render - `web/src/App.tsx` - Provider hierarchy & routing - `web/index.html` - HTML template **Configuration:** - `web/vite.config.ts` - Vite bundler config with path aliases - `web/tailwind.config.ts` - Tailwind with Kurdistan color theme - `web/tsconfig.json` - TypeScript strict mode + path mappings - `web/postcss.config.js` - PostCSS for Tailwind **State Management (6 Contexts):** - `contexts/PolkadotContext.tsx` - Blockchain API connection - `contexts/WalletContext.tsx` - Wallet state & multi-token balances - `contexts/AuthContext.tsx` - Supabase authentication - `contexts/AppContext.tsx` - Global application state - `contexts/WebSocketContext.tsx` - Real-time blockchain updates - `contexts/IdentityContext.tsx` - User identity & KYC status **Backend:** - `src/lib/supabase.ts` - Supabase client initialization - `supabase/migrations/*.sql` - Database schema migrations (9 files) ### Mobile Application **Entry Points:** - `mobile/index.ts` - Expo registerRootComponent - `mobile/App.tsx` - Root with i18n initialization - `mobile/src/navigation/AppNavigator.tsx` - Navigation setup ### Shared Library **Core Files:** - `shared/blockchain/endpoints.ts` - Network endpoint configurations - `shared/blockchain/polkadot.ts` - Polkadot.js utilities - `shared/constants/index.ts` - KNOWN_TOKENS, KURDISTAN_COLORS, LANGUAGES - `shared/i18n/index.ts` - i18n configuration - `shared/types/blockchain.ts` - Blockchain type definitions - `shared/lib/wallet.ts` - Wallet utilities & formatters **Business Logic Libraries:** - `shared/lib/citizenship-workflow.ts` - KYC & citizenship workflow - `shared/lib/tiki.ts` - 70+ government roles (Hemwelatî, Parlementer, etc.) - `shared/lib/perwerde.ts` - Education platform logic - `shared/lib/p2p-fiat.ts` - P2P fiat trading system (production-ready) - `shared/lib/staking.ts` - Staking operations - `shared/lib/multisig.ts` - Multisig treasury operations - `shared/lib/validator-pool.ts` - Validator pool management --- ## 🚀 Development Workflows ### Web Development ```bash # Navigate to web directory cd web # Install dependencies npm install # Start development server (localhost:8081) npm run dev # Build for production npm run build # Preview production build npm run preview # Lint code npm run lint ``` **Environment Setup:** 1. Copy `.env.example` to `.env` 2. Set `VITE_NETWORK=local` (or testnet/beta/mainnet) 3. Configure Supabase credentials: - `VITE_SUPABASE_URL` - `VITE_SUPABASE_ANON_KEY` 4. Set blockchain endpoint (optional, defaults to beta) ### Mobile Development ```bash # Navigate to mobile directory cd mobile # Install dependencies npm install # Start Expo development server npm start # Run on Android emulator npm run android # Run on iOS simulator npm run ios # Run in web browser npm run web ``` ### Deploying to Production (Web) ```bash # 1. Build locally cd /home/mamostehp/pwap/web npm run build # 2. Deploy to VPS rsync -avz dist/ pezkuwi-vps:/var/www/pezkuwichain/web/dist/ # 3. Reload Nginx (no restart needed) ssh pezkuwi-vps "systemctl reload nginx" ``` **Important:** Always test locally with `npm run build && npm run preview` before deploying to VPS. --- ## 📂 Code Organization Patterns ### Component Structure **Web Components:** ``` web/src/components/ ├── ui/ # shadcn/ui primitives (50+ components) │ ├── button.tsx │ ├── card.tsx │ ├── dialog.tsx │ └── ... ├── auth/ # Authentication components ├── citizenship/ # Citizenship/KYC UI ├── dex/ # DEX/Swap interface ├── delegation/ # Delegation management ├── forum/ # Forum components ├── governance/ # Governance interface ├── p2p/ # P2P fiat trading ├── perwerde/ # Education platform ├── staking/ # Staking dashboard └── wallet/ # Wallet components ``` **Pattern:** Feature-based organization with co-located types and utilities. ### File Naming Conventions - **Components:** PascalCase (`StakingDashboard.tsx`) - **Utilities:** camelCase (`wallet.ts`, `formatting.ts`) - **Types:** PascalCase interfaces/types (`WalletAccount`, `TokenInfo`) - **Constants:** UPPER_SNAKE_CASE exports (`ASSET_IDS`, `KURDISTAN_COLORS`) ### Import Patterns **Path Aliases (Web):** ```typescript // Local imports import { Component } from '@/components/ui/component'; import { useWallet } from '@/contexts/WalletContext'; // Shared library imports import { formatBalance } from '@pezkuwi/lib/wallet'; import { WalletAccount } from '@pezkuwi/types'; import { KURDISTAN_COLORS } from '@pezkuwi/constants'; import { translations } from '@pezkuwi/i18n'; ``` **Import Order (Follow This!):** 1. React imports 2. External libraries 3. Shared imports (`@pezkuwi/*`) 4. Local imports (`@/`) 5. Types 6. Styles/assets **Example:** ```typescript import React, { useState, useEffect } from 'react'; import { useNavigate } from 'react-router-dom'; import { useQuery } from '@tanstack/react-query'; import { formatBalance } from '@pezkuwi/lib/wallet'; import { WalletAccount } from '@pezkuwi/types'; import { ASSET_IDS } from '@pezkuwi/constants'; import { useWallet } from '@/contexts/WalletContext'; import { Card } from '@/components/ui/card'; import type { PoolInfo } from '@/types/dex'; import '@/styles/dashboard.css'; ``` ### TypeScript Conventions **Strict Mode Enabled:** ```json { "strict": true, "noImplicitAny": true, "strictNullChecks": true, "noUnusedLocals": true, "noUnusedParameters": true } ``` **Type Patterns:** - Use `interface` for object shapes - Use `type` for unions, intersections, and complex types - Use `enum` for fixed sets of values - Use `as const` for literal types - Avoid `any` - use `unknown` and type guards instead --- ## ⛓️ Blockchain Integration ### Network Endpoints ```typescript // shared/blockchain/endpoints.ts const ENDPOINTS = { MAINNET: 'wss://mainnet.pezkuwichain.io', BETA: 'wss://rpc.pezkuwichain.io:9944', // Currently active STAGING: 'wss://staging.pezkuwichain.io', TESTNET: 'wss://testnet.pezkuwichain.io', LOCAL: 'ws://127.0.0.1:9944' }; // Default for development DEFAULT_ENDPOINT = 'ws://127.0.0.1:9944'; ``` ### Asset System **⚠️ CRITICAL: wUSDT uses 6 decimals, not 12!** ```typescript // Native token (no Asset ID) HEZ - Accessed via system.account.data.free // Assets pallet (12 decimals except wUSDT) ASSET_IDS = { WHEZ: 0, // Wrapped HEZ - 12 decimals PEZ: 1, // Utility token - 12 decimals WUSDT: 2, // Wrapped USDT - 6 decimals ⚠️ } // Display mapping (internal vs user-facing) TOKEN_DISPLAY_SYMBOLS = { 'wHEZ': 'HEZ', // Show as HEZ to users 'wUSDT': 'USDT', // Show as USDT to users 'PEZ': 'PEZ' // Keep as PEZ } ``` ### Polkadot.js Connection Pattern ```typescript import { ApiPromise, WsProvider } from '@polkadot/api'; // Initialize API const provider = new WsProvider(endpoint); const api = await ApiPromise.create({ provider }); await api.isReady; // Query native balance const { data } = await api.query.system.account(address); const balance = data.free.toString(); // Query asset balance const assetData = await api.query.assets.account(ASSET_IDS.PEZ, address); const amount = assetData.unwrap().balance.toString(); ``` ### Transaction Pattern ```typescript // Simple transaction const extrinsic = api.tx.balances.transfer(dest, amount); const hash = await extrinsic.signAndSend(account, { signer }); // With event handling const result = await new Promise((resolve, reject) => { let unsub; api.tx.module.method(params) .signAndSend(account, { signer }, ({ 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) { // Extract data from events const event = events.find(e => e.event.section === 'module' && e.event.method === 'EventName' ); resolve(event.data[0].toString()); if (unsub) unsub(); } }) .then(unsubscribe => { unsub = unsubscribe; }); }); ``` ### Custom Pallets 1. **pallet-tiki** - Governance roles (70+ roles: Hemwelatî, Parlementer, Serok, Wezir, etc.) 2. **pallet-identity-kyc** - Zero-knowledge citizenship & KYC 3. **pallet-perwerde** - Education platform (courses, enrollments, certificates) 4. **pallet-validator-pool** - Validator pool categories & staking 5. **pallet-welati** - P2P fiat trading with escrow --- ## 🎨 UI Patterns & Styling ### shadcn/ui Components Located in `web/src/components/ui/` - 50+ components built on Radix UI primitives. **Component Variants (CVA Pattern):** ```typescript import { cva } from 'class-variance-authority'; const buttonVariants = cva( 'inline-flex items-center justify-center rounded-md font-medium', { variants: { variant: { default: 'bg-kurdish-green text-white', destructive: 'bg-kurdish-red text-white', outline: 'border border-input bg-background', }, size: { default: 'h-10 px-4 py-2', sm: 'h-9 px-3', lg: 'h-11 px-8', } }, defaultVariants: { variant: 'default', size: 'default', } } ); ``` ### Kurdistan Color System **Primary Colors:** ```typescript KURDISTAN_COLORS = { kesk: '#00A94F', // Green (Kesk) - Primary brand color sor: '#EE2A35', // Red (Sor) - Danger/error zer: '#FFD700', // Yellow/Gold (Zer) - Warning/accent spi: '#FFFFFF', // White (Spî) res: '#000000', // Black (Reş) } ``` **Tailwind Usage:** ```css bg-kurdish-green bg-kurdish-green-dark bg-kurdish-green-light text-kurdish-red border-kurdish-yellow ``` --- ## 🌍 Internationalization (i18n) ### Supported Languages | Code | Language | Direction | Status | |------|----------|-----------|--------| | `en` | English | LTR | ✅ Complete | | `tr` | Türkçe (Turkish) | LTR | ✅ Complete | | `kmr` | Kurmancî (Kurdish Kurmanji) | LTR | ✅ Complete | | `ckb` | سۆرانی (Kurdish Sorani) | RTL | ✅ Complete | | `ar` | العربية (Arabic) | RTL | ✅ Complete | | `fa` | فارسی (Persian) | RTL | ✅ Complete | ### Translation Files - **Web:** `web/src/i18n/locales/*.ts` (TypeScript modules - local imports) - **Mobile:** `mobile/src/i18n/locales/*.ts` - **Shared:** `shared/i18n/locales/*.json` (JSON files) **⚠️ Important:** Web uses `.ts` files with local imports, not shared JSON files. This was changed to fix loading issues. ### RTL Support ```typescript import { isRTL } from '@pezkuwi/i18n'; // Detect RTL languages const isRightToLeft = isRTL(currentLanguage); // true for ckb, ar, fa // Apply direction document.dir = isRightToLeft ? 'rtl' : 'ltr'; ``` ### Usage Pattern ```typescript import { useTranslation } from 'react-i18next'; function Component() { const { t, i18n } = useTranslation(); return (