Skip to content

feat: Add ASDF lottery system with activity requirement (v121.0)#1

Open
zeyxx wants to merge 18 commits intosollama58:mainfrom
zeyxx:feature/referral-asdf-rewards
Open

feat: Add ASDF lottery system with activity requirement (v121.0)#1
zeyxx wants to merge 18 commits intosollama58:mainfrom
zeyxx:feature/referral-asdf-rewards

Conversation

@zeyxx
Copy link

@zeyxx zeyxx commented Dec 4, 2025

  • Weekly lottery for ASDF holders (>=0.00552% of supply)
  • Activity-based eligibility: tickets = baseTickets * (activeDays/7)
  • On-chain verification for holding duration and ASDF balance
  • Secure random selection using crypto.randomInt()
  • Mutex protection against concurrent draws
  • Admin panel for manual draws
  • Full documentation in CHANGELOG.md

🤖 Generated with Claude Code

zeyxx and others added 18 commits December 4, 2025 14:30
- Weekly lottery for ASDF holders (>=0.00552% of supply)
- Activity-based eligibility: tickets = baseTickets * (activeDays/7)
- On-chain verification for holding duration and ASDF balance
- Secure random selection using crypto.randomInt()
- Mutex protection against concurrent draws
- Admin panel for manual draws
- Full documentation in CHANGELOG.md

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
- Add missing file path constants (PAYOUT_HISTORY_FILE, SENTIMENT_VOTES_FILE, etc.)
- Add missing payoutHistory variable declaration
- Add missing /api/admin/broadcast endpoint
- Add missing updateBroadcast function in control panel
- Update version numbers to 143.0

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
- Add broadcast and hourlySentiment to cachedPublicState response
- Add missing sentiment UI element references in frontend (broadcastContainer, sentBarFill, etc.)
- Call loadAndInit() on server startup (was missing, caused SERVICE_UNAVAILABLE)

These fixes are essential for the frontend to properly display:
- Admin broadcast messages
- Hourly sentiment meter
- Lottery information

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
- Add fee-funded lottery prize pool system
  - 20% of platform fees accumulate towards pool
  - 1,000,000 ASDF threshold to unlock draws
  - Progress bar UI in frontend lottery section

- Fix frontend issues
  - Remove duplicate code in poll() function
  - Fix API URL detection for GitHub Codespaces
  - Add missing UI elements (imgSentUp, imgSentDown)
  - Add modal close on backdrop click + Escape key

- Fix control panel
  - Add admin password prompt on load
  - Add missing functions (fetchLogs, fetchPayouts, etc.)
  - Fix history modal functionality

- Add dotenv for environment configuration
- Add comprehensive README documentation

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
552 SYMMETRY Referral System:
- User rebate: 0.552% of bet amount (rewards active users)
- Referrer reward: 0.448% of bet amount (incentivizes growth)
- Total: 1% of bet volume redistributed in ASDF

Key Features:
- Rewards paid in ASDF (forces holding)
- Proportional claim: can only claim up to your ASDF balance
- Live ASDF price via Jupiter API for conversion
- Manual claim endpoint with flywheel mechanics

New Endpoints:
- GET /api/referral/stats - Full stats with pending/claimable
- POST /api/referral/claim - Claim rewards (proportional to holding)
- Updated admin stats endpoint

Flywheel: bet → accumulate ASDF → must hold to claim → buy more → claim more

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Backend:
- Add REFERRAL_CONFIG with 552 SYMMETRY percentages
- Add referralData structure for tracking rewards
- Add getASDF_Price() via Jupiter API
- Add transferASDF() for SPL token transfers
- Add processReferralRewards() in closeFrame
- Add endpoints: /api/referral/{code,register,stats,claim}
- Proportional claim: claimable = min(pending, balance)

Frontend:
- Add referral section with code display + copy
- Add pending/balance/claimable rewards grid
- Add claim button with tx link
- Add stats (users, volume, claimed)
- Add register with code section
- Add fetchReferralStats() with 30s polling
- Integrate with wallet connect/disconnect

Dependencies:
- Add @solana/spl-token for token transfers

Philosophy: Gambler-Holder alignment flywheel
- Filleul earns 0.552% of bets in ASDF
- Parrain earns 0.448% of bets in ASDF
- Must hold ASDF to claim rewards

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
- Add getFirstASDF_Transaction() using Helius API with sortOrder: "asc"
- Fetch actual first transaction timestamp from token account history
- Cache firstSeenHolding with source tracking ('onchain')
- Remove eligibility loss reset to preserve holding history
- Fix calculateTickets to use pre-calculated weeksHolding

Fixes inaccurate weeks holding display that showed 0 for existing holders.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Resolved conflicts to integrate upstream changes while preserving:
- Lottery system with on-chain weeksHolding calculation (Helius API)
- Referral Flywheel System (552 SYMMETRY pattern)
- All new UI enhancements from upstream (balance validation, sentiment UI)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Replace Jupiter API with direct on-chain price calculation:
- Read ASDF/SOL reserves from PumpSwap pool token accounts
- Calculate price as quoteReserve/baseReserve (SOL per ASDF)
- Add startup validation for HELIUS_API_KEY and pool accessibility
- Include pool reserves in external stats cache
- Add priceAvailable indicator to referral stats API

Pool: DuhRX5JTPtsWU5n44t8tcFEfmzy2Eu27p4y6z8Rhf2bb

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
- Update backend version to v147.0
- Add Referral Flywheel and On-chain price to feature list
- Add CHANGELOG entry for PumpSwap on-chain price integration

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
- Fix ASDF_MINT in find_asdf_pools.js and find_pumpswap_pool.js
  (was: 2ezxCB7S2TdqJ1uLPD54KZnPB8RMvG2oSYNQLUmCpump)
  (now: 9zB5wRarXMj86MymwLumSKA1Dx35zPqqKfcZtK1Spump)
- Add .env.example documenting all environment variables

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
## Centralized Configuration
- NEW: config.js with all constants (addresses, economy, rate limits)
- server.js imports from config for maintainability

## Enhanced Security
- NEW: claimLimiter (3 req/5min) for /api/referral/claim
- NEW: registerLimiter (5 req/min) for /api/referral/register
- Rate limit configs externalized to config.js

## Monitoring Endpoints
- NEW: /api/health - Service health status (RPC, PumpSwap, Pyth)
- NEW: /api/metrics - Prometheus-compatible metrics

## Documentation
- README: Security section + monitoring docs
- CHANGELOG: v148.0 entry
- package.json: Version sync to 1.48.0

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Replace HTTP polling with WebSocket streaming for near-instant UI updates:

## Backend (server.js)
- WebSocket server on same port (3000) with HTTP upgrade
- Client tracking with Map, heartbeat ping/pong (30s)
- Broadcast events: STATE (500ms), PRICE (~10s), FRAME_CLOSE
- wsBroadcast() and wsBroadcastToUser() helpers
- WebSocket metrics in /api/health and /api/metrics

## Frontend (frontend.html)
- Auto-connecting WebSocket client with exponential backoff
- processStateUpdate() handler for WS STATE events
- Automatic auth when wallet connects
- Fallback to polling (10s) when WS connected, 2s otherwise

## Performance
- Update latency: 2-4s → ~500ms
- Requests/min/client: 120 → ~6 (fallback only)
- Server CPU: ~80% reduction expected

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Add proper shutdown handling for SIGTERM/SIGINT signals:

## Backend (server.js)
- gracefulShutdown() function with ordered cleanup:
  1. Notify all WebSocket clients (SERVER_SHUTDOWN event)
  2. Stop accepting new connections
  3. Save system state (gameState, lottery, referral)
  4. Wait for pending payouts (max 5s)
  5. Clean exit

- Handle uncaught exceptions (log + graceful shutdown)
- Handle unhandled rejections (log only, recoverable)

## Frontend (frontend.html)
- SERVER_SHUTDOWN event handler
- Shows "MAINTENANCE" status with yellow indicator
- Displays maintenance overlay message

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
## New User APIs
- GET /api/user/history - Paginated bet history with stats
- GET /api/user/stats - User statistics (wins, lottery, referral)
- GET /api/user/badges - Achievements system (11 badges)

## Achievements System
- FIRST_BET, FIRST_WIN, WIN_STREAK_3
- WINS_10/50/100, FRAMES_100
- VOLUME_1/10, REFERRER_5, HODLER
- WebSocket BADGE_EARNED event on unlock

## Price Alerts (WebSocket)
- SET_PRICE_ALERT, REMOVE_PRICE_ALERT, LIST_PRICE_ALERTS
- PRICE_ALERT_TRIGGERED event when price hits target
- Max 5 alerts per client

## Admin Dashboard Stats
- GET /api/admin/stats - Comprehensive stats endpoint
- Overview, daily/weekly, frame stats, lottery, system metrics

## Rate Limit Headers
- Standard (RateLimit-*) and legacy (X-RateLimit-*) headers
- retryAfter field in error responses

## Golden Ratio Referrer Decay
- PHI constant: 1.618033988749895
- Rate: 0.448% → 0.277% → 0.171% → 0.106% → ...
- Formula: baseRate / φ^floor(log_φ(n+1))
- Prevents farming, rewards organic growth

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
## Feature Flags System
All new features can now be enabled/disabled via config.js:
- WEBSOCKET_ENABLED: Real-time updates (fallback to HTTP polling)
- LOTTERY_ENABLED: Weekly ASDF lottery system
- REFERRAL_ENABLED: Referral rewards with Golden Ratio decay
- BADGES_ENABLED: Achievement/badge system
- EXTERNAL_TRACKER_ENABLED: External wallet tracking
- SENTIMENT_ENABLED: Daily sentiment voting

## Backend Modularization (server.js)
- Conditional WebSocket server initialization
- Conditional module loading (lottery, referral)
- Conditional API endpoints (404 when disabled)
- Conditional payout processing
- Conditional state broadcasting
- Features exposed in /api/state for frontend detection

## Frontend Modularization (frontend.html)
- safeFetch() wrapper with fallback for disabled features
- updateFeatureVisibility() to hide/show UI sections
- Feature guards on fetchLotteryEligibility/fetchReferralStats
- Section IDs: lottery-section, referral-section

## Documentation
- DEPLOYMENT.md: Complete guide for progressive feature activation

## Default State
All features OFF by default for safe initial deployment.
Creator can enable progressively without breaking production.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Changed from hardcoded value to calculated formula:
PHI: (1 + Math.sqrt(5)) / 2

Benefits:
- Self-documenting (shows φ definition)
- Maximum JS precision guaranteed
- No risk of typos in magic numbers

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant