# 🎮 AeThex Connect

**Next-Generation Communication Platform for Gamers & Game Developers**

[![License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
[![Node](https://img.shields.io/badge/node-%3E%3D18.0.0-brightgreen.svg)](https://nodejs.org/)
[![PostgreSQL](https://img.shields.io/badge/postgresql-14%2B-blue.svg)](https://www.postgresql.org/)

AeThex Connect is a comprehensive communication platform built specifically for the gaming ecosystem. It combines real-time messaging, voice/video calls, game integration, and blockchain-based identity with a sustainable monetization model.

---

## ✨ Features

### 🔐 **Phase 1: Blockchain Identity (.AETHEX Domains)**
- Custom blockchain domain authentication (`username.aethex`)
- NFT-based ownership on Polygon
- Freename TLD integration
- Domain verification and management

### 💬 **Phase 2: Real-Time Messaging**
- End-to-end encrypted messaging
- Group conversations and DMs
- File sharing with encryption
- Rich media support (images, videos, voice messages)
- Real-time delivery via WebSocket
- Read receipts and typing indicators

### 🎮 **Phase 3: GameForge Integration**
- Auto-provisioned game project channels
- Role-based access control (Developer, Artist, Designer, Tester)
- System notifications (builds, commits, deployments)
- Team synchronization
- Project-specific communication

### 📞 **Phase 4: Voice & Video Calls**
- High-quality WebRTC calls
- 1-on-1 and group calling
- Screen sharing
- In-call chat
- Call recording (premium feature)
- STUN/TURN NAT traversal

### 🌐 **Phase 5: Cross-Platform (Nexus Integration)**
- Communication that follows players across games
- Friend system with cross-game presence
- Game session management
- Lobby system
- In-game overlay component
- Nexus Engine SDK plugin

### 💎 **Phase 6: Premium Monetization**
- Three-tier subscription model (Free, Premium, Enterprise)
- Blockchain .aethex domain NFT ownership
- Domain marketplace with 10% platform fee
- Stripe payment integration
- Usage analytics dashboard
- White-label solutions for enterprises

---

## 🏗️ Architecture

```
┌─────────────────────────────────────────────────────────┐
│                    AeThex Connect                        │
├─────────────────────────────────────────────────────────┤
│  Frontend (React + Vite)                                 │
│  - Real-time messaging UI                                │
│  - WebRTC call interface                                 │
│  - Domain verification                                   │
│  - Premium upgrade flow                                  │
│  - In-game overlay (Phase 5)                            │
├─────────────────────────────────────────────────────────┤
│  Backend (Node.js + Express)                            │
│  - REST API                                             │
│  - WebSocket (Socket.IO)                                │
│  - WebRTC signaling                                     │
│  - Stripe webhooks                                      │
│  - Authentication middleware                            │
├─────────────────────────────────────────────────────────┤
│  Services                                               │
│  - Messaging Service                                    │
│  - Call Service (WebRTC)                               │
│  - Premium Service (Stripe)                            │
│  - GameForge Integration                               │
│  - Nexus Integration                                   │
│  - Domain Verification                                 │
├─────────────────────────────────────────────────────────┤
│  Database (PostgreSQL + Supabase)                       │
│  - Users & Authentication                               │
│  - Conversations & Messages                             │
│  - Blockchain Domains                                   │
│  - Premium Subscriptions                                │
│  - Game Sessions & Lobbies                             │
├─────────────────────────────────────────────────────────┤
│  Blockchain Integration (Polygon)                       │
│  - Freename .aethex TLD                                │
│  - NFT domain minting                                  │
│  - Ownership verification                              │
└─────────────────────────────────────────────────────────┘
```

---

## 💰 Pricing Tiers

| Feature | Free | Premium | Enterprise |
|---------|------|---------|------------|
| **Price** | $0 | $100/year | $500-5000/month |
| **Domain** | Subdomain | .aethex NFT | Custom domain |
| **Friends** | 5 max | Unlimited | Unlimited |
| **Messaging** | Text only | Text + Files | Everything |
| **Calls** | Audio only | HD Video (1080p) | 4K Video |
| **Storage** | 100 MB | 10 GB | Unlimited |
| **Analytics** | ❌ | ✅ | Advanced |
| **Branding** | AeThex | Custom | White-label |
| **Support** | Community | Priority | Dedicated |
| **Integrations** | Standard | Standard | Custom SSO/SAML |
| **SLA** | Best effort | 99% uptime | 99.9% uptime |

---

## 🚀 Quick Start

### Prerequisites
- Node.js 18+
- PostgreSQL 14+
- Stripe account (for monetization)
- Supabase project (optional)

### Installation

```bash
# Clone repository
git clone https://github.com/AeThex-Corporation/AeThex-Connect.git
cd AeThex-Connect

# Install dependencies
npm install

# Setup environment variables
cp .env.example .env
# Edit .env with your configuration

# Run database migrations
npm run migrate

# Start backend server
npm start

# Start frontend (new terminal)
cd src/frontend
npm install
npm run dev
```

**Server runs on:** `http://localhost:5000`  
**Frontend runs on:** `http://localhost:5173`

### Quick Test

```bash
# Test API health
curl http://localhost:5000/health

# Test domain availability
curl -X POST http://localhost:5000/api/premium/domains/check-availability \
  -H "Content-Type: application/json" \
  -d '{"domain": "testuser.aethex"}'
```

---

## 📖 Documentation

### Phase Guides
- **[PHASE1: Domain Verification](integration-package/README.md)** - Blockchain identity setup
- **[PHASE2: Messaging](PHASE2-MESSAGING.md)** - Real-time chat implementation
- **[PHASE3: GameForge](PHASE3-GAMEFORGE.md)** - Game project integration
- **[PHASE4: Calls](PHASE4-CALLS.md)** - Voice/video calling
- **[PHASE5: Nexus](PHASE5-COMPLETE.md)** - Cross-platform features
- **[PHASE6: Premium](PHASE6-COMPLETE.md)** - Monetization & subscriptions

### Quick Starts
- **[Phase 4 Quick Start](PHASE4-QUICK-START.md)** - WebRTC calls in 5 minutes
- **[Phase 6 Quick Start](PHASE6-QUICK-START.md)** - Premium monetization in 10 minutes

### API Reference
- **[GameForge Examples](docs/GAMEFORGE-EXAMPLES.md)** - Integration code examples
- **[Nexus SDK](nexus-sdk/README.md)** - Game engine plugin docs

---

## 🔧 Configuration

### Environment Variables

Create a `.env` file in the root directory:

```bash
# Database
DATABASE_URL=postgresql://user:password@localhost:5432/aethex_connect
SUPABASE_URL=https://your-project.supabase.co
SUPABASE_ANON_KEY=your-anon-key
SUPABASE_SERVICE_ROLE_KEY=your-service-role-key

# Server
PORT=5000
NODE_ENV=development
JWT_SECRET=your-super-secret-jwt-key

# Stripe (Phase 6)
STRIPE_SECRET_KEY=sk_test_...
STRIPE_PUBLISHABLE_KEY=pk_test_...
STRIPE_WEBHOOK_SECRET=whsec_...
STRIPE_PREMIUM_YEARLY_PRICE_ID=price_...
STRIPE_PREMIUM_MONTHLY_PRICE_ID=price_...
STRIPE_ENTERPRISE_PRICE_ID=price_...

# Blockchain
POLYGON_RPC_URL=https://polygon-mainnet.g.alchemy.com/v2/YOUR_KEY
FREENAME_REGISTRY_ADDRESS=0x...
DOMAIN_MINTER_PRIVATE_KEY=0x...

# GameForge (Phase 3)
GAMEFORGE_API_KEY=your-api-key
GAMEFORGE_API_SECRET=your-secret

# WebRTC (Phase 4)
STUN_SERVER=stun:stun.l.google.com:19302
TURN_SERVER=turn:your-turn-server.com:3478
TURN_USERNAME=turn-user
TURN_CREDENTIAL=turn-password
```

See [.env.example](.env.example) for complete configuration options.

---

## 🗄️ Database Schema

### Core Tables
- `users` - User accounts and authentication
- `blockchain_domains` - .aethex domain registry
- `domain_verifications` - Domain ownership verification
- `conversations` - Chat rooms and channels
- `messages` - Chat message storage
- `conversation_participants` - User-conversation mapping

### Premium & Monetization (Phase 6)
- `premium_subscriptions` - Stripe subscription management
- `payment_transactions` - Payment audit trail
- `feature_limits` - Tier-based access control
- `domain_transfers` - Marketplace transactions
- `enterprise_accounts` - Enterprise customer management

### Gaming Features
- `gameforge_integrations` - GameForge project mapping (Phase 3)
- `friend_requests` - Cross-game friend system (Phase 5)
- `friendships` - Active friend relationships (Phase 5)
- `game_sessions` - Active game sessions (Phase 5)
- `game_lobbies` - Pre-game lobby management (Phase 5)

### Calls & Media (Phase 4)
- `calls` - Call history and metadata
- `call_participants` - Call participant tracking

Run all migrations:
```bash
npm run migrate
```

---

## 🧪 Testing

### Manual Testing

```bash
# Test subscription flow
curl -X POST http://localhost:5000/api/premium/subscribe \
  -H "Authorization: Bearer <token>" \
  -H "Content-Type: application/json" \
  -d '{
    "tier": "premium",
    "paymentMethodId": "pm_card_visa",
    "billingPeriod": "yearly"
  }'

# Test domain registration
curl -X POST http://localhost:5000/api/premium/domains/register \
  -H "Authorization: Bearer <token>" \
  -H "Content-Type: application/json" \
  -d '{
    "domain": "myname.aethex",
    "walletAddress": "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb",
    "paymentMethodId": "pm_card_visa"
  }'

# Test GameForge project provisioning
curl -X POST http://localhost:5000/api/gameforge/projects \
  -H "X-GameForge-API-Key: <key>" \
  -H "Content-Type: application/json" \
  -d '{
    "projectId": "test-project",
    "name": "My Game",
    "ownerId": "user-123"
  }'
```

### Stripe Test Cards

**Successful Payment:**
```
Card: 4242 4242 4242 4242
Expiry: Any future date
CVC: Any 3 digits
```

**Declined:**
```
Card: 4000 0000 0000 0002
```

---

## 📊 API Endpoints

### Authentication
- `POST /api/auth/register` - Create account
- `POST /api/auth/login` - Login
- `GET /api/auth/me` - Get current user

### Domains
- `POST /api/domains/verify` - Start domain verification
- `POST /api/domains/check` - Check verification status
- `GET /api/domains` - List user's domains

### Messaging
- `GET /api/conversations` - List conversations
- `POST /api/conversations` - Create conversation
- `GET /api/messages/:conversationId` - Get messages
- `POST /api/messages` - Send message
- `WS /socket.io` - Real-time message delivery

### Calls
- `POST /api/calls/initiate` - Start call
- `POST /api/calls/join/:callId` - Join call
- `POST /api/calls/leave/:callId` - Leave call
- `GET /api/calls/:callId` - Get call details

### Premium (Phase 6)
- `POST /api/premium/subscribe` - Subscribe to tier
- `GET /api/premium/subscription` - Get subscription
- `POST /api/premium/cancel` - Cancel subscription
- `POST /api/premium/domains/check-availability` - Check domain
- `POST /api/premium/domains/register` - Register domain
- `GET /api/premium/marketplace` - Browse marketplace
- `GET /api/premium/analytics` - Get usage analytics

### GameForge (Phase 3)
- `POST /api/gameforge/projects` - Provision project
- `PATCH /api/gameforge/projects/:id/team` - Update team
- `POST /api/gameforge/projects/:id/notify` - Send notification
- `GET /api/gameforge/projects/:id/channels` - List channels

### Nexus (Phase 5)
- `POST /api/nexus/friends/request` - Send friend request
- `GET /api/nexus/friends` - List friends
- `POST /api/nexus/sessions` - Create game session
- `GET /api/nexus/lobbies` - List active lobbies

---

## 🎮 Game Integration

### Nexus Engine Plugin

```javascript
import { AeThexConnectPlugin } from './AeThexConnectPlugin.js';

// Initialize plugin
const aethex = new AeThexConnectPlugin({
  apiUrl: 'https://connect.aethex.app/api',
  socketUrl: 'https://connect.aethex.app',
  token: 'user-jwt-token',
  gameId: 'my-awesome-game'
});

// Initialize
await aethex.initialize();

// Listen for friend messages
aethex.on('message', (message) => {
  console.log(`${message.sender.username}: ${message.content}`);
});

// Send message
await aethex.sendMessage('friend-123', 'Hey, want to play?');

// Create lobby
const lobby = await aethex.createLobby({
  name: 'Deathmatch',
  maxPlayers: 8,
  gameMode: 'deathmatch'
});
```

See [nexus-sdk/README.md](nexus-sdk/README.md) for full documentation.

---

## 🔐 Security

### Authentication
- JWT-based authentication
- Bcrypt password hashing
- Token expiration and refresh
- Domain ownership verification

### Encryption
- End-to-end message encryption
- TLS/SSL for transport
- Encrypted file storage
- Secure WebRTC signaling

### Payment Security
- PCI compliance via Stripe
- No card data stored locally
- Webhook signature verification
- HTTPS required in production

### Access Control
- Role-based permissions
- Tier-based feature limits
- Rate limiting
- CORS protection

---

## 🚀 Deployment

### Production Checklist

- [ ] Set `NODE_ENV=production`
- [ ] Use Stripe live keys
- [ ] Configure production database
- [ ] Set up SSL/TLS certificates
- [ ] Configure CORS for production domain
- [ ] Set strong `JWT_SECRET`
- [ ] Secure `DOMAIN_MINTER_PRIVATE_KEY`
- [ ] Setup database backups
- [ ] Configure monitoring (Sentry, etc.)
- [ ] Setup CDN for static assets
- [ ] Configure rate limiting
- [ ] Setup webhook endpoints
- [ ] Test Stripe webhooks with live endpoint
- [ ] Configure TURN servers for WebRTC

### Deploy to Cloud

**Heroku:**
```bash
heroku create aethex-connect
heroku addons:create heroku-postgresql:hobby-dev
heroku config:set JWT_SECRET=your-secret
git push heroku main
heroku run npm run migrate
```

**AWS/GCP/Azure:**
- See platform-specific deployment guides
- Ensure PostgreSQL 14+ available
- Configure environment variables
- Setup load balancer for WebSocket

---

## 🤝 Contributing

We welcome contributions! Please see our contributing guidelines:

1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

---

## 📄 License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

---

## 🙏 Acknowledgments

- **Freename** - .aethex TLD provider
- **Stripe** - Payment processing
- **Supabase** - Database and authentication
- **Socket.IO** - Real-time communication
- **WebRTC** - Peer-to-peer calls
- **Nexus Engine** - Game engine integration

---

## 📞 Support

- **Documentation:** See phase guides above
- **Issues:** [GitHub Issues](https://github.com/AeThex-Corporation/AeThex-Connect/issues)
- **Email:** support@aethex.dev
- **Discord:** [AeThex Community](https://discord.gg/aethex)

---

## 🗺️ Roadmap

### ✅ Completed
- Phase 1: Blockchain identity (.aethex domains)
- Phase 2: Real-time messaging
- Phase 3: GameForge integration
- Phase 4: Voice & video calls
- Phase 5: Cross-platform (Nexus)
- Phase 6: Premium monetization

### 🚧 In Progress
- Blockchain NFT minting automation
- Domain marketplace v2 (auctions)
- Mobile app (React Native)

### 🔮 Future
- Phase 7: Advanced analytics dashboard
- Discord bot integration
- Twitch/YouTube streaming integration
- Tournament management system
- In-game item trading
- Clan/guild management
- Achievement system
- API rate limit dashboard
- Referral program
- Affiliate system

---

## 📈 Stats

| Metric | Value |
|--------|-------|
| **Total Phases** | 6 |
| **Backend Services** | 8 |
| **API Endpoints** | 50+ |
| **Frontend Components** | 25+ |
| **Database Tables** | 20+ |
| **Lines of Code** | ~15,000+ |
| **Documentation Pages** | 12 |

---

**Built with ❤️ by the AeThex Team**

*Empowering gamers and developers with next-generation communication technology.*

---

## Project Structure

```
AeThex-Connect/
├── src/
│   ├── backend/
│   │   ├── server.js
│   │   ├── database/
│   │   │   ├── db.js
│   │   │   ├── migrate.js
│   │   │   └── migrations/
│   │   │       ├── 001_domain_verifications.sql
│   │   │       ├── 002_messaging_system.sql
│   │   │       ├── 003_gameforge_integration.sql
│   │   │       ├── 004_voice_video_calls.sql
│   │   │       ├── 005_nexus_cross_platform.sql
│   │   │       └── 006_premium_monetization.sql
│   │   ├── middleware/
│   │   │   ├── auth.js
│   │   │   ├── gameforgeAuth.js
│   │   │   └── nexusAuth.js
│   │   ├── routes/
│   │   │   ├── domainRoutes.js
│   │   │   ├── messagingRoutes.js
│   │   │   ├── gameforgeRoutes.js
│   │   │   ├── callRoutes.js
│   │   │   ├── nexusRoutes.js
│   │   │   ├── premiumRoutes.js
│   │   │   └── webhooks/
│   │   │       └── stripeWebhook.js
│   │   ├── services/
│   │   │   ├── messagingService.js
│   │   │   ├── socketService.js
│   │   │   ├── gameforgeIntegration.js
│   │   │   ├── callService.js
│   │   │   ├── nexusIntegration.js
│   │   │   └── premiumService.js
│   │   └── utils/
│   │       ├── domainVerification.js
│   │       └── supabase.js
│   └── frontend/
│       ├── main.jsx
│       ├── App.jsx
│       ├── components/
│       │   ├── DomainVerification.jsx
│       │   ├── Chat/
│       │   ├── GameForgeChat/
│       │   ├── Call/
│       │   ├── Overlay/ (Phase 5)
│       │   └── Premium/ (Phase 6)
│       ├── contexts/
│       │   └── SocketContext.jsx
│       └── utils/
│           ├── crypto.js
│           └── webrtc.js
├── nexus-sdk/
│   ├── AeThexConnectPlugin.js
│   └── README.md
├── docs/
│   └── GAMEFORGE-EXAMPLES.md
├── scripts/
│   └── apply-migration.js
├── supabase/
│   └── migrations/
├── .env.example
├── package.json
└── README.md
```

---

**Version:** 1.0.0  
**Last Updated:** January 10, 2026  
**Status:** Production Ready ✅
