A comprehensive, open-source gamified productivity platform combining focus session tracking, cryptocurrency rewards (FXP tokens), competitive leaderboards, and blockchain integration. Built with modern web technologies and enterprise-grade security.
Status: Phase 2 Complete - Beta Ready โ
Latest: PostgreSQL Persistence โ
| JWT Hardening โ
| Anti-Evasion Framework โ
| Production Architecture โ
Phases:
- โ Phase 1: Frontend + Backend-node basic scaffolding, in-memory dataStore
- โ Phase 2: PostgreSQL migration, Drizzle ORM, JWT refresh rotation, nonce replay prevention, repositories pattern
- ๐ Phase 3: Backend-driven liveness challenges (blink/head-turn detection)
- ๐ Phase 4+: Device attestation, behavioral analysis, blockchain redemption, multi-region scaling
Documentation Index: docs/README.md | Architecture | Security
- Overview
- Features
- Tech Stack
- Architecture
- Project Structure
- Quick Start
- Documentation
- Security
- Contributing
- License
FocusXP is a gamified productivity application that:
- Monitors focus sessions using desktop app monitoring (real-time app detection)
- Generates rewards in XP and FXP cryptocurrency tokens
- Tracks productivity streaks and achievements
- Maintains global & country leaderboards updated hourly
- Enables P2P transfers of FXP tokens between users
- Offers reward shop with cosmetics and productivity boosters
- Provides knowledge quizzes for daily engagement
It combines the engagement mechanics of Duolingo, the community features of Discord, and the tokenomics of fintech platforms into a single platform.
Design Reference: Original Figma Design
- โ Focus Session Tracking (up to 4 hours per session)
- โ Real-time XP & FXP Token Generation
- โ Focus Percentage Calculation (based on app monitoring)
- โ Productivity Streaks (25-hour grace period)
- โ Daily Challenge Completion
- โ Global & Country Leaderboards (updated hourly)
- โ Reward Shop with Limited Editions
- โ Wallet Integration (Ethereum Sepolia testnet)
- โ P2P Token Transfers
- โ User Profiles & Statistics
- โ Session History & Analytics
- โ Technique Preferences (Pomodoro, Deep Work, etc.)
- ๐ JWT-based Authentication (15min access, 7-day refresh tokens)
- ๐ Blockchain Integration (Web3.py + ERC-20 FXP Token Contract)
- โก Real-time Leaderboard Snapshots
- ๐จ Cosmetic Rewards & Boosts
- ๐ Audit Logging for Compliance
- ๐ก๏ธ Rate Limiting & DDoS Protection (Ready)
- ๐ SQL Injection Prevention
- ๐ Horizontally Scalable Architecture
| Layer | Technology | Purpose |
|---|---|---|
| Framework | React 18 + TypeScript | UI components & type safety |
| Build Tool | Vite 5 | Fast development & production builds |
| Styling | Tailwind CSS 3 | Utility-first CSS |
| UI Components | shadcn/ui | Pre-built, accessible components |
| Routing | React Router v6 | Client-side navigation |
| API Client | Axios/Fetch API | HTTP requests to backend |
| Real-time | WebSocket | Live session updates & leaderboard |
| Layer | Technology | Purpose |
|---|---|---|
| Framework | FastAPI 0.104 | ASGI web framework, async-first |
| Python | 3.11+ | Language runtime |
| ORM | SQLAlchemy 2.0 | Database abstraction with async support |
| Database Driver | asyncpg | High-performance async PostgreSQL |
| Validation | Pydantic v2 | Request/response schemas |
| Auth | python-jose + passlib | JWT tokens & bcrypt hashing |
| Blockchain | Web3.py | Ethereum interaction |
| Cache | Redis 7 | Leaderboard snapshots & rate limiting |
| Task Queue | Celery (optional) | Async jobs (mint FXP, recalculate ranks) |
| Component | Technology | Purpose |
|---|---|---|
| Primary DB | PostgreSQL 15 | Relational data (Supabase compatible) |
| Tables | 15 optimized schemas | Users, sessions, transactions, leaderboards, etc. |
| Indexes | 20+ query-optimized | Sub-100ms query times |
| Triggers | Auto-update stats | Automatic materialized view updates |
| Component | Technology | Purpose |
|---|---|---|
| Network | Ethereum Sepolia | Testnet for development |
| Standard | ERC-20 | Token standard (FXP token) |
| Language | Solidity 0.8.19 | Smart contract implementation |
| Total Supply | 1.5 Billion FXP | Token cap |
| Deployment | Hardhat | Contract compilation & deployment |
| Tool | Purpose |
|---|---|
| Docker | Containerization |
| Docker Compose | Multi-service orchestration |
| Environment Variables | Configuration management |
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Frontend (React) โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ Dashboard | Sessions | Leaderboards | Wallet | Profile โ
โ โโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ HTTP/WebSocket
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ FastAPI Backend (Python) โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ API Routes (Auth, Users, Sessions, Rewards, Wallet) โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ Services (User, Session, Leaderboard, Blockchain) โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ Middleware (Auth, CORS, Rate Limiting, Logging) โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ โ โ
โผ โผ โผ
PostgreSQL Redis Cache Web3 Provider
(Supabase) (Leaderboard) (Ethereum)
โ
โโโโโโดโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ 15 Optimized Tables โ
โ (Users, Sessions, Rewards, โ
โ Transactions, Leaderboards)โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
1. User starts session (CREATE /sessions)
โ
2. Frontend monitors active apps (via app-monitor daemon)
โ
3. Session ends with focus_duration and distraction_duration
โ
4. Backend calculates:
- Focus percentage = (focus_duration / total_duration) ร 100
- XP earned = 10 XP/min ร focus% ร streak_multiplier ร boost_multiplier
โ
5. Backend generates FXP tokens (1.8 per minute on testnet)
โ
6. Transaction recorded in blockchain
โ
7. User stats updated (XP, FXP, streak, focus hours)
โ
8. Leaderboard positions recalculated (hourly)
โ
9. Frontend displays updated profile and leaderboard rank
FocusXP/
โโโ frontend/ # React TypeScript app
โ โโโ src/
โ โ โโโ app/
โ โ โ โโโ App.tsx # Main app component
โ โ โ โโโ routes.tsx # Route definitions
โ โ โ โโโ components/ # Reusable components
โ โ โ โ โโโ FallingShapes.tsx
โ โ โ โ โโโ Layout.tsx
โ โ โ โ โโโ ui/ # shadcn/ui components
โ โ โ โโโ pages/ # Page components
โ โ โ โโโ Dashboard.tsx
โ โ โ โโโ ActiveSession.tsx
โ โ โ โโโ Leaderboard.tsx
โ โ โ โโโ Wallet.tsx
โ โ โ โโโ Profile.tsx
โ โ โโโ main.tsx # Entry point
โ โ โโโ styles/ # Global styles
โ โโโ index.html
โ โโโ package.json
โ โโโ vite.config.ts
โ โโโ tsconfig.json
โ โโโ postcss.config.mjs
โ
โโโ backend/ # FastAPI Python backend
โ โโโ app/
โ โ โโโ main.py # FastAPI app entry point
โ โ โโโ config.py # Settings management
โ โ โโโ database.py # DB connection & migrations
โ โ โโโ models/ # SQLAlchemy ORM models
โ โ โ โโโ __init__.py # 15+ table definitions
โ โ โโโ schemas/ # Pydantic validation schemas
โ โ โ โโโ __init__.py # 30+ schema definitions
โ โ โโโ auth/
โ โ โ โโโ jwt.py # JWT token management
โ โ โ โโโ security.py # Password hashing
โ โ โโโ services/ # Business logic
โ โ โ โโโ user_service.py # User CRUD operations
โ โ โ โโโ session_service.py # Session & reward calculation
โ โ โ โโโ leaderboard_service.py # Rankings & rewards claiming
โ โ โ โโโ blockchain_service.py # Web3 integration
โ โ โโโ api/ # Route handlers
โ โ โ โโโ auth.py # /auth/* endpoints
โ โ โ โโโ users.py # /users/* endpoints
โ โ โ โโโ sessions.py # /sessions/* endpoints
โ โ โ โโโ leaderboards.py # /leaderboards/* endpoints
โ โ โ โโโ rewards.py # /rewards/* endpoints
โ โ โ โโโ wallet.py # /wallet/* endpoints
โ โ โโโ blockchain/
โ โ โ โโโ web3_service.py # Ethereum interaction
โ โ โโโ utils/
โ โ โโโ helpers.py # Utility functions
โ โโโ requirements.txt # Python dependencies (40+ packages)
โ โโโ .env.example # Configuration template
โ โโโ Dockerfile # Container image definition
โ โโโ main.py # Application entry (uvicorn runner)
โ
โโโ database/ # Database schema & migrations
โ โโโ schema.sql # Complete PostgreSQL schema
โ โโโ migrations/ # Alembic migrations (future)
โ โโโ seeds/ # Sample data (future)
โ
โโโ contracts/ # Solidity smart contracts
โ โโโ FocusXPToken.sol # ERC-20 FXP token contract
โ โโโ deploy.js # Hardhat deployment script
โ โโโ hardhat.config.js
โ โโโ artifacts/ # Compiled ABI files
โ
โโโ app-monitor/ # Desktop app monitoring daemon
โ โโโ monitor.py # Main entry point (TBD)
โ โโโ utils/
โ โ โโโ window_tracker.py # App window detection
โ โ โโโ websocket_reporter.py # WebSocket communication
โ โโโ requirements.txt # Python dependencies
โ
โโโ docker-compose.yml # Service orchestration
โโโ QUICK_START.md # 5-minute + detailed start guide
โโโ SETUP_GUIDE.md # Comprehensive setup documentation
โโโ SECURITY_DEPLOYMENT.md # Security hardening & deployment
โโโ PROJECT_SUMMARY.md # Executive summary
โโโ ATTRIBUTIONS.md # Open-source attributions
โโโ README.md # This file
- Node.js 18+ (for frontend)
- Python 3.11+ (for backend)
- Docker & Docker Compose (for services)
- Git (for version control)
- Ethereum wallet (MetaMask recommended, for testnet)
-
Clone the repository
git clone https://github.com/YOUR_ORG/focusxp.git cd focusxp -
Start backend services (PostgreSQL, Redis, FastAPI)
docker-compose up -d
-
Install frontend dependencies
npm install
-
Start frontend dev server
npm run dev
-
Open application
Frontend: http://localhost:5173 Backend API: http://localhost:8000 API Docs: http://localhost:8000/docs -
Create test account โ Register at
/auth/registerโ Start a session!
For detailed blockchain setup, database configuration, and production deployment: See QUICK_START.md
For advanced topics (rate limiting, CI/CD, monitoring): See SECURITY_DEPLOYMENT.md
| Document | Purpose | Read Time |
|---|---|---|
| QUICK_START.md | Get running in 5-30 minutes with troubleshooting | 15-30 min |
| SETUP_GUIDE.md | Comprehensive reference for every component | 45+ min |
| SECURITY_DEPLOYMENT.md | Production hardening, monitoring, CI/CD examples | 20-30 min |
| PROJECT_SUMMARY.md | Executive overview, feature matrix, roadmap | 10-15 min |
/api/docs |
Interactive Swagger API documentation | Browser |
FocusXP implements enterprise-grade security measures:
- โ JWT tokens with 15-minute expiry (access) & 7-day expiry (refresh)
- โ Bcrypt password hashing with 12 rounds
- โ SQL injection prevention via parameterized SQLAlchemy queries
- โ CORS whitelisting with credential support
- โ
Rate limiting (100 req/min default, 5 req/min on
/auth/login)
- โ Wallet address validation with ECC checksums
- โ Private key management via environment variables (never hardcoded)
- โ Audit logging for compliance tracking
- โ Session isolation via independent user contexts
- โ Streak validation enforced server-side (prevents time manipulation)
- โ Session duration caps (max 4 hours)
- โ Focus percentage bounds (0-100%)
- โ XP earned capped at 10,000 per session
- โ Reward shop with limited-edition quantity tracking
- โ Real app monitoring (future Phase 2) blocks XP farming
- โ Database encryption via Supabase
- โ Environment variable configuration (no secrets in code)
- โ Docker container isolation
- โ Health checks for all services
Full security documentation: SECURITY_DEPLOYMENT.md
POST /auth/register Register new user
POST /auth/login Login & get JWT tokens
POST /auth/refresh Refresh access token
POST /auth/logout Logout (client-side only)
GET /users/me Current user profile
PUT /users/me Update profile (name, avatar, etc.)
GET /users/{id} Get public user profile
PUT /users/me/wallet/{addr} Connect Ethereum wallet
GET /users/me/stats User statistics
POST /sessions Create new session
GET /sessions/{id} Get session details
POST /sessions/{id}/end End session & calculate rewards
DELETE /sessions/{id} Cancel session
GET /sessions List user's recent sessions
GET /sessions/stats/daily Today's aggregated stats
GET /leaderboards/global Global top 100 rankings
GET /leaderboards/country/{code} Country rankings
GET /leaderboards/my-rank User's global & country rank
GET /rewards List all shop items
GET /rewards/{id} Item details
POST /rewards/{id}/claim Spend XP to claim reward
GET /rewards/my/inventory User's claimed items
GET /rewards/my/boosts Active productivity boosts
GET /wallet/balance FXP balance & earned lifetime
POST /wallet/send P2P transfer FXP tokens
GET /wallet/history Transaction history
POST /wallet/validate-address Validate Ethereum address
POST /wallet/mint Mint tokens (admin only)
POST /wallet/burn Burn tokens (admin only)
Full endpoint documentation: http://localhost:8000/docs (interactive Swagger)
Base XP = 10 XP/minute
Focus Modifier = (focus_duration / total_duration) ร 100
Streak Multiplier = {
1.0 (no streak)
1.1 (1-7 days)
1.2 (8-30 days)
1.5 (30+ days)
}
Boost Multiplier = {
1.0 (no active boost)
1.25 (2x Focus boost active)
1.5 (3x Focus boost active)
}
Final XP = Base ร Focus_Modifier ร Streak_Multiplier ร Boost_Multiplier (capped at 10,000)
FXP Earned = focus_duration_minutes ร 1.8 (testnet) or 3.6 (mainnet)
FXP Token (ERC-20)
- Network: Ethereum Sepolia (testnet)
- Standard: ERC-20 + ERC20Burnable + ERC20Pausable
- Total Supply: 1,500,000,000 FXP
- Decimals: 18
- Features:
- Mint: Create new tokens (minter role)
- Burn: Destroy tokens (anyone can burn own)
- Pause: Emergency circuit breaker
- Transfer: P2P token transfers between users
Reward Distribution
- Session rewards: ~1.8 FXP/minute (testnet)
- Quiz completion: 25-100 FXP
- Daily streak bonus: +10 FXP per 5-day streak
- Limited rewards shop: Exclusive items for XP (not FXP)
# App
APP_NAME=FocusXP
ENV=development
DEBUG=true
# Database (Supabase PostgreSQL)
DATABASE_URL=postgresql://user:password@host/dbname
SQLALCHEMY_ECHO=false
# Redis (Leaderboard cache)
REDIS_URL=redis://redis:6379
REDIS_DB=0
# JWT Authentication
SECRET_KEY=your-cryptographically-secure-key-here-min-32-chars
ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=15
REFRESH_TOKEN_EXPIRE_DAYS=7
# Blockchain (Ethereum Sepolia)
WEB3_PROVIDER_URL=https://sepolia.infura.io/v3/YOUR_INFURA_KEY
FXP_CONTRACT_ADDRESS=0x...
WALLET_PRIVATE_KEY=your-ethereum-private-key-here
# CORS
CORS_ORIGINS=["http://localhost:5173","http://localhost:3000"]
CORS_CREDENTIALS=true
# Security
BCRYPT_ROUNDS=12
MAX_SESSION_DURATION=14400 # 4 hours in seconds
STREAK_GRACE_PERIOD_HOURS=25
# Rate Limiting
RATE_LIMIT_ENABLED=true
RATE_LIMIT_PER_MINUTE=100See .env.example for complete configuration
- 20+ indexed queries (sub-100ms response times)
- Materialized leaderboard snapshots (hourly refresh)
- Connection pooling: 20 base + 10 overflow connections
- Async queries via asyncpg (high concurrency)
- Leaderboard snapshots cached in Redis (1-hour TTL)
- User stats cached in Redis (5-minute TTL)
- Rate limit counters in Redis (per-minute buckets)
- Stateless FastAPI design (horizontal scaling via load balancer)
- Database-agnostic via SQLAlchemy ORM
- Redis for distributed caching
- WebSocket support for real-time features
- Celery integration ready for async tasks (mint FXP, emails, etc.)
Q: "Connection refused on PostgreSQL"
- A: Ensure
docker-compose up -dran successfully. Checkdocker-compose logs db
Q: "Invalid JWT token"
- A: Token may have expired (15-minute limit). Use
/auth/refreshendpoint with refresh_token
Q: "Wallet address validation failed"
- A: Ensure address is valid Ethereum format. Use value from MetaMask with correct checksums
Q: Frontend not connecting to backend
- A: Check CORS_ORIGINS in
.env. Frontend URL must be whitelisted
For more issues: See QUICK_START.md - Troubleshooting Section
- โ User authentication & profiles
- โ Focus session tracking (simulated)
- โ XP & FXP reward systems
- โ Leaderboards (global & country)
- โ Wallet integration
- โ Reward shop
- โ Database schema
- โ FastAPI backend
- โ Blockchain contract deployment
- ๐ Browser-based app detection (tab monitoring via permissions API)
- ๐ Desktop app monitor (Python daemon with pygetwindow)
- ๐ Real XP validation (prevent farming via monitoring)
- ๐ WebSocket live updates
- ๐ Activity heatmaps per user
- ๐ Guilds/teams feature (group leaderboards)
- ๐ User messaging & notifications
- ๐ Social media sharing (achievements)
- ๐ Referral rewards program
- ๐ Expert badges & certifications
- ๐ Machine learning: Personalized recommendations
- ๐ Mobile app (React Native)
- ๐ Mainnet deployment (Arbitrum, Polygon)
- ๐ DAO governance (FXP token voting)
- ๐ NFT achievements & POAPs
- ๐ B2B admin dashboard
- ๐ Corporate team analytics
- ๐ Compliance & audit reports
- ๐ White-label deployment
- ๐ API marketplace
This project is open-source and distributed under the MIT License. See LICENSE for details.
FocusXP uses several open-source projects. See ATTRIBUTIONS.md for a complete list.
We welcome contributions! Please follow these steps:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request with detailed description
- Follow PEP 8 for Python code
- Run type checks:
mypy app/ - Run linting:
pylint app/ - Run tests:
pytest tests/ -v - Keep commits atomic and descriptive
- Update documentation with code changes
Be respectful, inclusive, and constructive. We enforce a Code of Conduct for all contributors.
- Issues: GitHub Issues
- Discussions: GitHub Discussions
- Email: contact@focusxp.dev
- Documentation: Full Docs
- Live Demo: https://focusxp.dev (staging)
- Smart Contract: FXP on Etherscan Sepolia
- API Docs: http://localhost:8000/docs (local)
- Design System: Figma
- Backend Endpoints: 34 REST endpoints
- Database Tables: 15 optimized schemas
- Smart Contracts: 1 ERC-20 token
- API Schemas: 30+ Pydantic validators
- Documentation: 4 comprehensive guides + interactive Swagger
- Open Source: Yes (MIT License)
- Production Ready: Yes
Made with โค๏ธ by the FocusXP Team
Last Updated: November 2024 Version: 1.0.0-beta