[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"project-3465":3},{"id":4,"name":5,"fullName":6,"owner":7,"repo":5,"description":8,"homepage":9,"htmlUrl":10,"language":11,"languages":10,"totalLinesOfCode":10,"stars":12,"forks":13,"watchers":14,"openIssues":15,"contributorsCount":16,"subscribersCount":16,"size":16,"stars1d":16,"stars7d":14,"stars30d":17,"stars90d":16,"forks30d":16,"starsTrendScore":16,"compositeScore":18,"rankGlobal":10,"rankLanguage":10,"license":19,"archived":20,"fork":20,"defaultBranch":21,"hasWiki":22,"hasPages":20,"topics":23,"createdAt":10,"pushedAt":10,"updatedAt":36,"readmeContent":37,"aiSummary":38,"trendingCount":16,"starSnapshotCount":16,"syncStatus":14,"lastSyncTime":39,"discoverSource":40},3465,"lets-bet","nutcas3\u002Flets-bet","nutcas3","Tier-1 betting platform for Kenya, Nigeria, Ghana. Sports betting, crash games, M-Pesa\u002FFlutterwave payments, real-time WebSocket odds, BCLB compliance. Go microservices with NATS.","",null,"Go",141,57,2,1,0,37,49.99,"MIT License",false,"main",true,[24,25,26,27,28,29,30,31,32,33,34,35],"bclb-compliance","betting-platform","crash-game","flutterwave","golang","kyc","microservices","payment-gateway","provably-fair","real-time","sports-betting","websocket","2026-06-12 04:00:17","# Betting Platform - Production-Ready Architecture\n\nA **Tier-1 betting platform** built for **Kenya, Nigeria, and Ghana** with support for:\n- **Sports Betting** (Single, Multi, System bets)\n- **Crash Games** (Aviator-style with Provably Fair algorithm)\n- **M-Pesa & Flutterwave** payment integration\n- **Real-time odds** via WebSocket\n- **BCLB Compliance** (KYC via Smile ID, Tax calculations, Geolocation)\n- **Event-driven architecture** with NATS messaging\n\n---\n\n## Architecture Overview\n\n### Multi-Tenant Microservices\n```\n┌─────────────────────────────────────────────────────────────┐\n│                     API GATEWAY (Port 8080)                  │\n│  HTTP\u002FREST + WebSocket | Authentication | Rate Limiting      │\n└─────────────────────────────────────────────────────────────┘\n         │              │              │              │\n    ┌────▼────┐    ┌───▼────┐    ┌───▼─────┐   ┌───▼─────┐\n    │ WALLET  │    │ ENGINE │    │ GAMES   │   │SETTLEMENT│\n    │ Service │    │Service │    │ Service │   │ Service  │\n    └────┬────┘    └───┬────┘    └───┬─────┘   └───┬─────┘\n         │              │              │              │\n    ┌────▼──────────────▼──────────────▼──────────────▼────┐\n    │         PostgreSQL (Multi-tenant with country_code)   │\n    └───────────────────────────────────────────────────────┘\n                          │\n              ┌───────────┼───────────┐\n              │           │           │\n         ┌────▼────┐ ┌───▼────┐ ┌───▼─────┐\n         │  Redis  │ │  NATS  │ │Cloudflare│\n         │ (Cache) │ │ (Queue)│ │  (CDN)   │\n         └─────────┘ └────────┘ └──────────┘\n```\n\n### Tech Stack\n- **Backend:** Go 1.26+ (high concurrency, low latency)\n- **Database:** PostgreSQL 15 (ACID transactions with optimistic locking)\n- **Cache:** Redis 7 (live odds, sessions, leaderboards)\n- **Queue:** NATS (event-driven architecture with JetStream support)\n- **WebSocket:** Gorilla WebSocket (real-time crash games)\n- **Payments:** Safaricom Daraja API (M-Pesa), Flutterwave (NG\u002FGH)\n- **KYC:** Smile ID SDK (Kenya identity verification)\n- **Observability:** Prometheus metrics, structured logging\n- **Geolocation:** MaxMind GeoLite2 + CDN header fallback\n\n---\n\n## Project Structure\n\n```\nbetting-platform\u002F\n|-- cmd\u002F                    # Service entry points\n|   |-- gateway\u002F            # Public-facing API (HTTP + WebSocket)\n|   |-- wallet\u002F             # Balance, deposits, withdrawals\n|   |-- engine\u002F             # Betting logic and odds processing\n|   |-- settlement\u002F         # Winner payouts\n|   `-- games\u002F              # Crash game engine\n|-- internal\u002F\n|   |-- core\u002F               # GLOBAL CORE (country-agnostic)\n|   |   |-- domain\u002F         # Entities (User, Bet, Transaction, Game)\n|   |   `-- usecase\u002F        # Business logic (PlaceBet, ProvablyFair, Tax, Wallet)\n|   |-- infrastructure\u002F     # Shared infrastructure\n|   |   |-- config\u002F         # Environment-based configuration\n|   |   |-- database\u002F       # PostgreSQL connection & migrations\n|   |   |-- http\u002F           # HTTP handlers, middleware, validation\n|   |   |-- events\u002F         # NATS event bus wrapper\n|   |   |-- kyc\u002F            # Smile ID integration\n|   |   |-- logging\u002F        # Structured logging\n|   |   |-- metrics\u002F        # Prometheus RED metrics\n|   |   `-- server\u002F         # Graceful HTTP server\n|   |-- tenant\u002F             # COUNTRY-SPECIFIC ADAPTERS\n|   |   `-- ke\u002F             # Kenya: M-Pesa, BCLB tax (15% GGR + 20% WHT)\n|   `-- migrations\u002F        # Database migration files\n|-- deployments\u002F            # Docker + Kubernetes\n|   `-- docker\u002F             # Multi-service Dockerfile\n|-- docker-compose.yml      # Local development environment\n|-- go.mod\n|-- go.sum\n|-- Makefile\n`-- README.md\n```\n\n---\n\n## Key Features\n\n### Core Betting Engine\n- **Atomic Wallet Service**: Transaction-safe balance operations with optimistic locking\n- **PlaceBet State Machine**: Validate user, apply tax, reserve funds, persist bet in single transaction\n- **Tax Engine**: Country-aware tax calculations (Kenya: 15% stake tax + 20% WHT)\n- **Provably Fair**: Cryptographically secure crash game with verification endpoints\n\n### Payment & Compliance\n- **M-Pesa Integration**: STK Push deposits + B2C withdrawals with callback handling\n- **KYC Verification**: Smile ID SDK integration for Kenyan identity verification\n- **Geolocation**: MaxMind GeoLite2 + CDN header fallback with country fencing\n- **Event Bus**: NATS messaging for inter-service communication\n\n### Observability & Reliability\n- **Prometheus Metrics**: RED metrics per handler with Go\u002Fprocess collectors\n- **Structured Logging**: JSON-formatted logs with context propagation\n- **Health Checks**: Liveness + readiness with Postgres\u002FRedis dependency checks\n- **Graceful Shutdown**: Signal-driven with 15s drain window\n\n### Development Experience\n- **Configuration Management**: Environment-based config with validation\n- **Middleware Stack**: Request ID, recovery, logging, CORS, rate limiting, metrics\n- **Hot Reload**: Support for live configuration updates where applicable\n- **Docker Support**: Multi-service builds with GeoLite2 database included\n\n---\n\n## Quick Start\n\n### 1. Prerequisites\n- Go 1.26+\n- Docker & Docker Compose\n- PostgreSQL 15 (via Docker)\n- Redis 7 (via Docker)\n- NATS Server (via Docker)\n\n### 2. Local Development Setup\n```bash\n# Clone the repository\ngit clone https:\u002F\u002Fgithub.com\u002Fnutcas3\u002Flets-bet.git\ncd lets-bet\n\n# Start infrastructure (Postgres, Redis, NATS)\ndocker-compose up -d\n\n# Run database migrations (up)\n.\u002Fbin\u002Fmigrate -dir .\u002Fmigrations -action up\n\n# Or use Makefile\nmake migrate-up\n\n# Build all services\ngo build .\u002F...\n\n# Start gateway service (example)\nPORT=8080 go run cmd\u002Fgateway\u002Fmain.go\n\n# Start wallet service (example)\nPORT=8081 go run cmd\u002Fwallet\u002Fmain.go\n\n# Start games service (example)\nPORT=8082 go run cmd\u002Fgames\u002Fmain.go\n```\n\n### 3. Test the API\n```bash\n# Health check\ncurl http:\u002F\u002Flocalhost:8080\u002Fhealthz\n\n# Metrics endpoint\ncurl http:\u002F\u002Flocalhost:8080\u002Fmetrics\n\n# KYC verification (Smile ID)\ncurl -X POST http:\u002F\u002Flocalhost:8080\u002Fapi\u002Fkyc\u002Fverify-user \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\"user_id\":\"uuid\",\"id_type\":\"ALIEN_ID\",\"id_number\":\"12345678\"}'\n\n# Provably fair commitment\ncurl -X POST http:\u002F\u002Flocalhost:8080\u002Fapi\u002Ffairness\u002Fcommitment \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\"server_seed\":\"your-server-seed\"}'\n\n# Place a bet\ncurl -X POST http:\u002F\u002Flocalhost:8080\u002Fapi\u002Fbets \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer \u003Cjwt>\" \\\n  -d '{\"bet_type\":\"single\",\"stake\":100,\"selections\":[{\"odds\":2.5}]}'\n```\n\n### 4. Connect to Crash Game WebSocket\n```javascript\nconst ws = new WebSocket('ws:\u002F\u002Flocalhost:8080\u002Fws\u002Fgames\u002Fcrash-game-id');\n\nws.onmessage = (event) => {\n  const data = JSON.parse(event.data);\n  console.log('Multiplier:', data.current_multiplier);\n};\n\n\u002F\u002F Place a bet\nws.send(JSON.stringify({\n  action: 'place_bet',\n  amount: 100\n}));\n\n\u002F\u002F Cashout\nws.send(JSON.stringify({\n  action: 'cashout'\n}));\n```\n\n---\n\n## M-Pesa Integration (Kenya)\n\n### Deposit Flow (STK Push)\n```go\n\u002F\u002F User requests deposit of KES 500\nmpesaClient.InitiateDeposit(ctx, \"0712345678\", 500, \"DEP-123\")\n\n\u002F\u002F M-Pesa sends prompt to user's phone\n\u002F\u002F User enters PIN\n\u002F\u002F Callback received at \u002Fapi\u002Fmpesa\u002Fcallback\n\u002F\u002F Wallet credited automatically\n```\n\n### Withdrawal Flow (B2C)\n```go\n\u002F\u002F User requests withdrawal of KES 1000\nmpesaClient.InitiateWithdrawal(ctx, \"0712345678\", 1000, \"WTD-456\")\n\n\u002F\u002F Wallet debited immediately\n\u002F\u002F M-Pesa processes payout\n\u002F\u002F Money sent to user's M-Pesa in ~30 seconds\n```\n\n### Configuration\n```bash\n# Environment variables for M-Pesa\nMPESA_CONSUMER_KEY=your_consumer_key\nMPESA_CONSUMER_SECRET=your_consumer_secret\nMPESA_SHORTCODE=174379  # Your Paybill\u002FTill number\nMPESA_PASSKEY=your_passkey\nMPESA_ENVIRONMENT=sandbox  # or production\n```\n\n---\n\n## BCLB Compliance (Kenya)\n\n### Required Features\n- **KYC Verification**: Smile ID integration for National ID validation  \n- **Self-Exclusion**: Users can ban themselves for 1-12 months  \n- **Deposit Limits**: Daily\u002Fweekly\u002Fmonthly caps enforced  \n- **Tax Deduction**: 15% stake tax + 20% WHT on winnings  \n- **Audit Log**: Every transaction stored with balance snapshots  \n- **Geolocation**: Country fencing with MaxMind + CDN headers  \n\n### Tax Engine Implementation\n```go\n\u002F\u002F Kenya Tax Regime (15% GGR + 20% WHT)\ntaxEngine := tax.Default()\n\n\u002F\u002F Stake tax collected upfront\nstakeBreak := taxEngine.ApplyStakeTax(\"KE\", decimal.NewFromInt(1000))\n\u002F\u002F StakeTax: KES 150, NetStake: KES 850\n\n\u002F\u002F Winnings tax on payout\npayoutBreak := taxEngine.ApplyPayoutTax(\"KE\", grossPayout, stake)\n\u002F\u002F WinningsTax: 20% of (winnings - threshold)\n```\n\n---\n\n## Database Migrations\n\nThis project uses [golang-migrate](https:\u002F\u002Fgithub.com\u002Fgolang-migrate\u002Fmigrate) for database schema management.\n\n### Migration Format\nMigrations follow the golang-migrate naming convention:\n- Up migrations: `YYYYMMDDHHMMSS_description.up.sql`\n- Down migrations: `YYYYMMDDHHMMSS_description.down.sql`\n\n### Running Migrations\n\n```bash\n# Apply all pending migrations\n.\u002Fbin\u002Fmigrate -dir .\u002Fmigrations -action up\n\n# Rollback one migration\n.\u002Fbin\u002Fmigrate -dir .\u002Fmigrations -action down -steps 1\n\n# Check current migration version\n.\u002Fbin\u002Fmigrate -dir .\u002Fmigrations -action version\n\n# Apply specific number of migrations\n.\u002Fbin\u002Fmigrate -dir .\u002Fmigrations -action up -steps 2\n```\n\n### Using Makefile\n\n```bash\nmake migrate-up      # Apply all pending migrations\nmake migrate-down    # Rollback one migration\nmake migrate-version # Check current version\n```\n\n### Using golang-migrate CLI\n\n```bash\n# Install golang-migrate CLI\ngo install -tags 'postgres' github.com\u002Fgolang-migrate\u002Fmigrate\u002Fv4\u002Fcmd\u002Fmigrate@latest\n\n# Run migrations directly\nmigrate -path .\u002Fmigrations -database \"postgres:\u002F\u002Fuser:pass@localhost:5432\u002Fdbname?sslmode=disable\" up\n```\n\n### Creating New Migrations\n\n1. Create up migration: `YYYYMMDDHHMMSS_new_feature.up.sql`\n2. Create down migration: `YYYYMMDDHHMMSS_new_feature.down.sql`\n3. Place both files in `.\u002Fmigrations\u002F` directory\n\n---\n\n## Database Schema Highlights\n\n### Atomic Wallet Operations\n```sql\n-- Wallet updates use FOR UPDATE + optimistic locking\nBEGIN;\nSELECT id, balance, version FROM wallets \nWHERE user_id = '...' FOR UPDATE;\n\nUPDATE wallets \nSET balance = balance - 100, version = version + 1\nWHERE id = '...' AND version = 5;\n\nINSERT INTO transactions (...)\nVALUES (balance_before, balance_after, ...);\nCOMMIT;\n```\n\n### Transaction Audit Trail\n```sql\n-- Every movement creates an audit record\nSELECT amount, balance_before, balance_after, type\nFROM transactions \nWHERE user_id = '...' \nORDER BY created_at DESC;\n```\n\n### Multi-Tenant Design\n```sql\n-- Every table has country_code for isolation\nSELECT * FROM bets WHERE country_code = 'KE';\nSELECT * FROM transactions WHERE country_code = 'NG';\n```\n\n---\n\n## Deployment\n\n### Production (AWS)\n```bash\n# Build Docker images\nmake docker-build\n\n# Deploy to Kenya region (af-south-1)\ncd deployments\u002Fke-prod\nterraform apply\n\n# Deploy to Nigeria region (eu-west-2)\ncd deployments\u002Fng-prod\nterraform apply\n```\n\n### Environment Variables\n```bash\n# Service Configuration\nSERVICE_NAME=gateway\nENVIRONMENT=development\nPORT=8080\n\n# Database\nDATABASE_HOST=localhost\nDATABASE_PORT=5432\nDATABASE_NAME=betting_db\nDATABASE_USER=postgres\nDATABASE_PASSWORD=postgres\nDATABASE_SSL_MODE=disable\n\n# Redis\nREDIS_HOST=localhost\nREDIS_PORT=6379\nREDIS_PASSWORD=\n\n# NATS\nNATS_URL=nats:\u002F\u002Flocalhost:4222\n\n# KYC (Smile ID)\nSMILE_ID_API_KEY=your_api_key\nSMILE_ID_PARTNER_ID=your_partner_id\nSMILE_ID_ENV=sandbox\n\n# M-Pesa (Kenya)\nMPESA_CONSUMER_KEY=your_consumer_key\nMPESA_CONSUMER_SECRET=your_consumer_secret\nMPESA_SHORTCODE=174379\nMPESA_PASSKEY=your_passkey\nMPESA_ENVIRONMENT=sandbox\n\n# Tax Configuration\nTAX_GGR_RATE=0.15\nTAX_WHT_RATE=0.20\nTAX_THRESHOLD=500\n\n# Geolocation\nALLOWED_COUNTRIES=KE,NG,GH\n\n# Logging\nLOG_LEVEL=info\nLOG_FORMAT=json\n```\n\n---\n\n## Performance Benchmarks\n\n| Metric | Target | Status |\n|--------|--------|--------|\n| Bet Placement | \u003C 200ms | **Implemented** |\n| Wallet Update | \u003C 50ms | **Implemented** |\n| WebSocket Latency | \u003C 100ms | **Implemented** |\n| Concurrent Users | 100,000+ | **Implemented** |\n| M-Pesa Payout | \u003C 60s | **Implemented** |\n| KYC Verification | \u003C 500ms | **Implemented** |\n| Provably Fair Verify | \u003C 100ms | **Implemented** |\n\n---\n\n## Implementation Status\n\n### Phase 1: Core Infrastructure (Completed)\n- [x] Multi-tenant architecture with country isolation\n- [x] Database schema with optimistic locking\n- [x] M-Pesa integration with callbacks\n- [x] Crash game engine with provably fair algorithm\n- [x] Atomic wallet service with transaction support\n- [x] Tax engine (15% GGR + 20% WHT)\n- [x] KYC integration via Smile ID SDK\n- [x] Geolocation middleware with MaxMind\n- [x] NATS event bus with JetStream support\n- [x] Prometheus metrics and structured logging\n- [x] Graceful shutdown and health checks\n\n### Phase 2: Production Hardening (Completed)\n- [x] PostgreSQL repository implementations\n- [x] Redis caching layer\n- [x] JWT authentication middleware\n- [x] Redis-backed distributed rate limiting\n- [x] Load testing infrastructure\n- [x] OpenTelemetry tracing integration\n- [x] Security vulnerability fixes (XSS, integer overflow)\n- [x] Code quality improvements (131 commits of refactoring)\n\n### Phase 3: Advanced Features (Completed)\n- [x] Live sports betting with real-time odds\n- [x] Flutterwave integration (Nigeria & Ghana)\n- [x] Jackpot system with automated draws\n- [x] Virtual sports simulation engine\n- [x] Admin dashboard with compliance monitoring\n- [x] Multi-tenant payment processing\n\n### Phase 4: Regulatory & Security (Completed)\n- [x] BCLB compliance framework\n- [x] Security audit implementation\n- [x] Penetration testing tools\n- [x] GDPR compliance suite\n- [x] Responsible gaming controls\n- [x] AML monitoring system\n\n---\n\n## Recent Security & Code Quality Improvements\n\n### Security Enhancements (Latest Release)\n- **XSS Protection**: Fixed cross-site scripting vulnerabilities in HTTP handlers using secure JSON encoding\n- **Integer Overflow**: Added bounds checking for score conversions to prevent overflow attacks\n- **Input Validation**: Enhanced request validation middleware across all endpoints\n- **Audit Logging**: Complete audit trails for compliance and security monitoring\n\n### Code Quality Improvements\n- **131 Commits of Refactoring**: Systematic code organization and cleanup\n- **Clean Architecture**: Separated concerns with domain-driven design\n- **Type Safety**: Enhanced type definitions and interface contracts\n- **Error Handling**: Consistent error patterns and proper error propagation\n- **Documentation**: Updated inline documentation and API specifications\n\n### Development Infrastructure\n- **Go 1.26.1**: Updated to latest Go version with modern features\n- **CI\u002FCD Pipeline**: Automated testing, security scanning, and deployment\n- **Docker Optimization**: Multi-stage builds with distroless runtime\n- **Monitoring**: Enhanced observability with metrics and structured logging\n\n---\n\n## Support\n\nFor technical questions or deployment assistance, open an issue or contact the development team.\n\n---\n\n## License\n\nProprietary - All rights reserved\n","这是一个为肯尼亚、尼日利亚和加纳设计的一级博彩平台，支持体育博彩、碰运气游戏以及M-Pesa\u002FFlutterwave支付方式。项目采用Go语言构建微服务架构，并利用NATS实现事件驱动的消息传递机制。它提供包括单注、多注及系统投注在内的多种体育博彩选项，以及基于可验证公平算法的碰运气游戏。此外，该平台通过WebSocket实现实时赔率更新，并符合BCLB合规要求（如KYC认证、税收计算和地理位置服务）。适用于需要高度并发处理能力且对实时性有较高要求的在线博彩业务场景。","2026-06-11 02:54:37","CREATED_QUERY"]