A comprehensive user engagement and rewards platform built on Solana blockchain, featuring social media integration, squad-based governance, and token reward distribution.
- Overview
- Key Features
- Tech Stack
- Prerequisites
- Installation
- Configuration
- Running the Application
- Project Structure
- Core Features Documentation
- API Documentation
- Testing
- Deployment
- Contributing
- Troubleshooting
- License
DeFAI Rewards is a cutting-edge platform that combines social engagement, blockchain technology, and community governance to create a comprehensive rewards ecosystem. Users can earn points through various activities, participate in squad-based governance, and receive token rewards based on their contributions.
- Social Engagement Rewards: Earn points for X (Twitter) activities and referrals
- Squad-Based Governance: Create and join squads to participate in collective decision-making
- Token Distribution: Fair and transparent token reward system with proposal voting
- Blockchain Integration: Built on Solana for fast, low-cost transactions
- Real-time Notifications: Stay updated with WebSocket-powered notifications
- X (Twitter) OAuth Integration: Secure authentication using social accounts
- Multi-Wallet Support: Connect and manage multiple Solana wallets
- Profile Management: Customizable user profiles with social links
- Multi-Action Point System: Earn points for:
- Initial platform connection
- Social media engagement
- Following official accounts
- Successful referrals
- Daily check-ins
- Quest completion
- Dynamic Leaderboard: Real-time ranking system
- Airdrop Eligibility: Automatic calculation based on activity
- Squad Creation: Form teams with up to 100 members
- Tiered Progression: Three tiers based on collective points
- Squad Governance: Leaders can create proposals for token distribution
- Invitation System: Private invite links with expiration
- Democratic Voting: Weight-based voting system
- Proposal Lifecycle: Active → Closed → Archived workflow
- Real-time Progress: Visual indicators for quorum and approval
- Automated Processing: Cron jobs for proposal execution
- Token Escrow: Secure token holding and distribution
- NFT Integration: Support for Core NFT assets
- Crossmint Integration: Simplified wallet creation and management
- Multi-RPC Support: Fallback RPC endpoints for reliability
- Framework: Next.js 14 (App Router)
- Language: TypeScript
- Styling: Tailwind CSS
- UI Components: Shadcn/ui
- State Management: Zustand
- Form Handling: React Hook Form with Zod validation
- API: Next.js API Routes
- Authentication: NextAuth.js
- Database: MongoDB with Mongoose ODM
- Real-time: Server-Sent Events (SSE)
- Queue System: RabbitMQ (optional)
- Caching: Redis
- Network: Solana
- Wallet Integration: Solana Wallet Adapter
- NFT Standard: Metaplex
- Smart Contracts: Anchor Framework
- Deployment: Vercel/AWS/Docker
- CDN: Fleek for decentralized storage
- Monitoring: OpenTelemetry
- Analytics: Custom event tracking
- Node.js v18.x or later
- npm/yarn/pnpm package manager
- MongoDB instance (local or Atlas)
- Solana wallet for testing
- X (Twitter) Developer Account
- Clone the repository
git clone https://github.com/defai/tokenEscrowFE.git
cd tokenEscrowFE- Install dependencies
npm install
# or
yarn install
# or
pnpm install- Setup environment variables
cp .env.example .env.local- Configure MongoDB indexes
// Connect to your MongoDB instance and run:
use defaiaffiliate;
db.users.createIndex({ xUserId: 1 }, { unique: true, sparse: true });
db.users.createIndex({ walletAddress: 1 }, { unique: true, sparse: true });
db.users.createIndex({ referralCode: 1 }, { unique: true, sparse: true });
db.squads.createIndex({ name: 1 }, { unique: true });
db.proposals.createIndex({ squadId: 1, status: 1 });Create a .env.local file with the following variables:
# Database Configuration
MONGODB_URI=mongodb+srv://username:password@cluster.mongodb.net/?retryWrites=true&w=majority
MONGODB_DB_NAME=defaiaffiliate
# Authentication
NEXTAUTH_SECRET=your-secret-key # Generate: openssl rand -base64 32
NEXTAUTH_URL=http://localhost:3000
# X (Twitter) OAuth
X_CLIENT_ID=your-x-client-id
X_CLIENT_SECRET=your-x-client-secret
X_CALLBACK_URL=http://localhost:3000/api/x/connect/callback
X_TOKEN_ENCRYPTION_KEY=32-byte-hex-string # Generate: openssl rand -hex 32
DEFAI_REWARDS_X_USER_ID=twitter-user-id # Get from tweeterid.com
# Solana Configuration
NEXT_PUBLIC_RPC=https://api.mainnet-beta.solana.com
NEXT_PUBLIC_SOLANA_NETWORK=mainnet-beta
NEXT_PUBLIC_DEFAI_TOKEN_MINT_ADDRESS=token-mint-address
NEXT_PUBLIC_DEFAI_TOKEN_DECIMALS=6
# Crossmint Integration
NEXT_PUBLIC_CROSSMINT_CLIENT_SIDE=your-client-key
NEXT_PUBLIC_CROSSMINT_API_KEY=your-api-key
CROSSMINT_AUDIENCE=your-audience-id
# Redis Configuration (Optional)
REDIS_URL=redis://localhost:6379
# Admin Configuration
ADMIN_X_IDS=comma,separated,handles
ADMIN_WALLET_ADDRESSES=comma,separated,addresses
# Feature Flags
NEXT_PUBLIC_MIN_DEFAI_BALANCE=100
NEXT_PUBLIC_REQUIRED_DEFAI_AMOUNT=5000# Frontend Settings
NEXT_PUBLIC_SQUAD_POINTS_TO_CREATE_PROPOSAL=10000
NEXT_PUBLIC_MIN_POINTS_TO_VOTE=500
NEXT_PUBLIC_PROPOSAL_BROADCAST_THRESHOLD=1000
NEXT_PUBLIC_PROPOSALS_PER_PAGE=10
# Backend/Cron Settings
CRON_PROPOSAL_PASS_THRESHOLD=0
CRON_PROPOSAL_ARCHIVE_DELAY_DAYS=7
CRON_SECRET=your-cron-secretnpm run dev
# Application runs on http://localhost:3000npm run build
npm run startdocker build -t defai-rewards .
docker run -p 3000:3000 --env-file .env.local defai-rewardstokenEscrowFE/
├── src/
│ ├── app/ # Next.js 14 App Router pages
│ │ ├── api/ # API routes
│ │ ├── admin/ # Admin dashboard pages
│ │ ├── profile/ # User profile pages
│ │ ├── squads/ # Squad management pages
│ │ └── proposals/ # Proposal voting pages
│ ├── components/ # React components
│ │ ├── layout/ # Layout components
│ │ ├── proposals/ # Proposal-specific components
│ │ ├── squads/ # Squad-specific components
│ │ └── ui/ # Shadcn UI components
│ ├── lib/ # Core libraries and utilities
│ │ ├── auth.ts # NextAuth configuration
│ │ ├── mongodb.ts # Database connection
│ │ └── encryption.ts # Token encryption utilities
│ ├── hooks/ # Custom React hooks
│ ├── store/ # Zustand state management
│ ├── types/ # TypeScript type definitions
│ └── utils/ # Utility functions
├── scripts/ # Utility scripts
│ ├── cron/ # Cron job scripts
│ └── migration/ # Database migration scripts
├── public/ # Static assets
├── tests/ # Test files
│ ├── e2e/ # End-to-end tests
│ └── unit/ # Unit tests
└── docs/ # Additional documentation
- User clicks "Connect with X"
- OAuth redirect to Twitter
- Callback handles token exchange
- User session created with NextAuth
- MongoDB user record created/updated
- Initial connection: 100 points
- Social share: 50 points
- Follow @defAIRewards: 200 points
- Successful referral: 500 points
- Daily check-in: 10 points
- Quest completion: Variable
- Tier 1: 1,000 points, max 10 members
- Tier 2: 5,000 points, max 50 members
- Tier 3: 10,000 points, max 100 members
- Proposals require minimum squad points to create
- Voting weight equals user's points
- Votes: Upvote (+1), Downvote (-1), Abstain (0)
- Quorum: Minimum participation threshold
- Pass threshold: Net positive votes
POST /api/auth/wallet-login- Wallet-based authenticationGET /api/x/connect/initiate- Start X OAuth flowGET /api/x/connect/callback- Handle OAuth callbackPOST /api/x/connect/disconnect- Disconnect X account
GET /api/users/my-details- Get current user detailsGET /api/users/my-points- Get user points breakdownGET /api/users/leaderboard- Get top usersPOST /api/users/link-wallet- Link Solana wallet
POST /api/squads/create- Create new squadPOST /api/squads/join- Join squadGET /api/squads/my-squad- Get user's squadPOST /api/squads/invitations/send- Send invitation
GET /api/proposals/active- Get active proposalsPOST /api/proposals/[id]/vote- Submit voteGET /api/proposals/[id]- Get proposal details
npm run test# Install Playwright
npx playwright install
# Run tests
npm run test:e2e
# Run in headed mode
npm run test:e2e -- --headednpm run test:coverage- Connect GitHub repository to Vercel
- Configure environment variables in Vercel dashboard
- Set up cron jobs in
vercel.json:
{
"crons": [
{
"path": "/api/cron/process-proposals",
"schedule": "0 */6 * * *"
},
{
"path": "/api/cron/quest-lifecycle",
"schedule": "0 0 * * *"
}
]
}# Build image
docker build -t defai-rewards:latest .
# Run container
docker run -d \
--name defai-rewards \
-p 3000:3000 \
--env-file .env.production \
defai-rewards:latest- Set production environment variables
- Configure MongoDB indexes
- Set up SSL certificates
- Configure CORS policies
- Enable rate limiting
- Set up monitoring and alerts
- Configure backup strategies
- Test all OAuth flows
- Verify WebSocket connections
- Run security audit
We welcome contributions! Please follow these guidelines:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit changes (
git commit -m 'Add amazing feature') - Push to branch (
git push origin feature/amazing-feature) - Open a Pull Request
- Write TypeScript with strict mode enabled
- Follow ESLint and Prettier configurations
- Write tests for new features
- Update documentation as needed
- Ensure all tests pass before submitting PR
MongoDB Connection Failed
- Verify connection string format
- Check IP whitelist in MongoDB Atlas
- Ensure database user has correct permissions
X OAuth Error
- Verify X_CALLBACK_URL matches app configuration
- Check X_CLIENT_ID and X_CLIENT_SECRET
- Ensure redirect URIs are properly configured
500 Internal Server Error
- Check server logs for detailed error
- Verify all environment variables are set
- Check MongoDB connection
- Ensure X_TOKEN_ENCRYPTION_KEY is 32-byte hex
WebSocket Connection Issues
- Verify NEXT_PUBLIC_WEBSOCKET_URL
- Check CORS configuration
- Ensure SSL certificates are valid
Enable debug logging:
DEBUG=* npm run devThis project is licensed under the MIT License - see the LICENSE file for details.
For support and questions:
- Create an issue on GitHub
- Join our Discord community
- Follow @defAIRewards on X
Built with ❤️ by the DeFAI team
