A next-generation decentralized lottery application built on EVM-compatible blockchains, featuring zero centralization, enhanced randomness, automated draws, and a modern web interface powered by the DecentralizedLottery smart contract.
- Zero Centralization: Fully decentralized lottery with no admin controls or manual interventions
- Enhanced Randomness: Advanced random number generation optimized for fast block times
- Automated Draws: Time-based automatic draw execution (every 7 days)
- Real-time Updates: Live jackpot and countdown with analytics-ready data hooks
- Transparent Prizes: On-chain prize calculation and distribution with rollover mechanics
- Gas Optimized: Efficient contract design for minimal transaction costs
- Modern UI: React-based responsive web interface with Kaspa branding
- Live Data: Real-time jackpot display and countdown timer
- Wallet Integration: Seamless connection with Kaspa-compatible wallets
- Error Handling: Comprehensive error boundaries and user feedback
- Mobile Responsive: Optimized for all device sizes
- Production Ready: Industry-standard security and optimization practices
- High Performance: Gas-optimized contract interactions and efficient algorithms
- Analytics Ready: Comprehensive event logging for Web3 UI integration
- Security First: Reentrancy protection, emergency pause, and robust validation
- EVM Compatible: Works on Kasplex, Igra, Hardhat, and other EVM networks
- Connect Wallet: Click "Connect Wallet" and select your EVM-compatible wallet
- View Current Draw: See live jackpot amount and countdown timer
- Purchase Tickets: Navigate to "Play" page and buy tickets (0.1 KAS each)
- Select Numbers: Choose 5 numbers from 1-35 for each ticket
- Wait for Draw: Draws occur automatically every 7 days
- Check Results: View results on the "Draw" page with detailed analytics
- Claim Prizes: Winners can claim prizes directly from the interface
- Frontend: React 18 + TypeScript + Vite
- Styling: Tailwind CSS with modern design system
- Web3: Wagmi v2 + RainbowKit + Ethers.js v6
- Smart Contract: DecentralizedLottery.sol (Solidity 0.8.19 + OpenZeppelin)
- State Management: Zustand + React Query
- Notifications: Sonner toast system
- Networks: Kasplex, Igra Labs, Hardhat (EVM compatible)
- Node.js 18+ and npm/pnpm
- MetaMask browser extension
- Kasplex testnet KAS tokens
- Git
-
Clone the repository
git clone https://github.com/your-username/kasdraw.git cd KasDraw -
Install dependencies (pnpm recommended)
pnpm install # or npm install -
Configure environment
cp .env.example .env # Edit .env with your configuration -
Start development server
npm run dev
-
Open browser Navigate to
http://localhost:5175
# 1. Start local Hardhat node
npx hardhat node
# 2. Deploy contracts (in another terminal)
npx hardhat run scripts/deploy.js --network localhost
# 3. Populate with test data
npx hardhat run scripts/purchase-tickets.js --network localhost
# 4. Start frontend development server
npm run dev
# 5. Open browser to http://localhost:5175-
Configure Hardhat
# Ensure .env file has your private key PRIVATE_KEY=your_private_key_here -
Compile contracts
npx hardhat compile
-
Deploy DecentralizedLottery
npx hardhat run scripts/deployDecentralizedLottery.js --network igra
-
Update contract address
- Copy the deployed contract address
- Update
VITE_CONTRACT_ADDRESSin.env - Restart the development server
After deployment, verify the contract on the Igra Labs block explorer for transparency.
- Price: 0.1 KAS per ticket
- Numbers: Select 5 unique numbers from 1-35
- Multiple Tickets: Purchase multiple tickets in one transaction
- Tier 1 (5/5 matches): 50% of prize pool (Jackpot)
- Tier 2 (4/5 matches): 25% of prize pool
- Tier 3 (3/5 matches): 15% of prize pool
- Tier 4 (2/5 matches): 10% of prize pool
- Rollover: Unclaimed prizes roll over to next draw
- Zero Admin Fees: 100% decentralized with no admin extraction
- Frequency: Every 7 days (604,800 seconds)
- Execution: Fully automated public execution
- Incentive: Dynamic executor rewards (0.1% of jackpot, min 0.1 KAS, max 10 KAS)
- Transparency: All draws recorded on blockchain with comprehensive analytics
KasDraw/
├── contracts/
│ └── DecentralizedLottery.sol # Main lottery contract
├── scripts/
│ └── deployDecentralizedLottery.js # Deployment script
├── test/
│ └── DecentralizedLottery.test.js # Comprehensive test suite
├── src/
│ ├── components/ # React components
│ ├── pages/ # Page components
│ ├── hooks/ # Custom React hooks
│ ├── config/ # Configuration files
│ └── utils/ # Utility functions
├── public/ # Static assets
├── LotteryContractAudit.md # Security audit report
└── DecentralizedLottery_README.md # Technical documentation
npm run dev- Start development servernpm run build- Build for productionnpm run preview- Preview production buildnpm run lint- Run ESLintnpx hardhat compile- Compile smart contractsnpx hardhat test- Run DecentralizedLottery test suitenpx hardhat run scripts/deployDecentralizedLottery.js --network <network>- Deploy contract
# Smart contract deployment
PRIVATE_KEY=your_private_key_here
# Frontend configuration
VITE_CONTRACT_ADDRESS=your_deployed_contract_address
VITE_RPC_URL=your_network_rpc_url
VITE_CHAIN_ID=your_network_chain_id
# Example configurations:
# Kasplex Testnet: VITE_CHAIN_ID=2600
# Igra Labs: VITE_CHAIN_ID=2600
# Hardhat Local: VITE_CHAIN_ID=31337
# Note: DecentralizedLottery contract with zero centralization
# Features: 0.1 KAS tickets, enhanced randomness, gas optimization
# Networks: EVM-compatible (Kasplex, Igra, Hardhat)Important: For AI agents and local development, a network.md file contains comprehensive network information including:
- Complete network configurations for all 3 supported networks (Hardhat, Kasplex, Igra Labs)
- Deployment credentials and wallet addresses
- Current contract addresses for each network
- Deployment scripts and commands
- Environment variable templates
network.md file contains sensitive information (private keys) and is:
- Excluded from Git: Added to
.gitignoreto prevent accidental commits - Local Only: Should never be shared or pushed to repositories
- AI Agent Reference: Provides consistent network information for automated deployments
For Contributors: If you need network configuration details, refer to the local network.md file or contact the project maintainers.
We use a two-branch development strategy to ensure code stability:
mainbranch: Production-ready, stable code onlydevbranch: Active development and testing
- Development Work: All new features and changes are made on the
devbranch - Testing: Thoroughly test changes on
devbranch - Merge to Main: Only tested, working code is merged from
devtomain - Rollback Safety: If issues arise, we can reset
devfrommainand start over
# Switch to dev branch for development
git checkout dev
# Create feature branch from dev (optional)
git checkout -b feature/new-feature dev
# Push changes to dev branch
git push origin dev
# Switch back to main (stable)
git checkout main
# Reset dev branch from main if needed
git checkout dev
git reset --hard main
git push --force-with-lease origin dev- Active Development:
devbranch - Production:
mainbranch - Contract Address: Updated in both branches
KasDraw uses a sophisticated dual-validation timing system that combines both blockchain timestamps and block numbers to ensure accurate and tamper-proof draw intervals.
1. Dual Validation System
- Timestamp Validation: Uses
block.timestampfor human-readable time tracking - Block Validation: Uses block numbers for additional security and consistency
- Combined Logic: Both conditions must be met for draw execution
2. On-Chain Data Sources
- Primary Source: Smart contract state (
canExecuteDrawPublic()function) - Real-time Updates: Frontend polls contract every 5-10 seconds
- Block-based Accuracy: Leverages blockchain's immutable block progression
3. Timer Accuracy & Reliability
- Precision: Accurate to the blockchain block time (~15 seconds on most networks)
- Tamper-proof: Cannot be manipulated by external parties
- Network Independent: Works consistently across different network conditions
- Fail-safe: Multiple validation layers prevent premature execution
Smart Contract Timer Logic:
function canExecuteDrawPublic() external view returns (
bool canExecute,
uint256 timeRemaining,
uint256 nextDrawTime,
uint256 blocksRemaining,
uint256 nextDrawBlock
) {
bool timeReached = block.timestamp >= nextDrawTime;
bool blockReached = block.number >= nextDrawBlock;
bool canExec = timeReached && blockReached;
uint256 timeRem = timeReached ? 0 : nextDrawTime - block.timestamp;
uint256 blockRem = blockReached ? 0 : nextDrawBlock - block.number;
return (canExec, timeRem, nextDrawTime, blockRem, nextDrawBlock);
}Frontend Timer Integration:
- Live Updates:
refetchInterval: 5000msfor real-time countdown - State Management: React hooks manage timer state and updates
- Error Handling: Graceful fallbacks for network issues
- Visual Feedback: Real-time countdown display with blockchain validation indicators
- Contract State: Smart contract calculates next draw time and block
- Frontend Polling: React app queries contract every 5 seconds
- Data Processing: Hook processes raw blockchain data into readable format
- UI Updates: Countdown timer updates in real-time
- Validation: Multiple checks ensure execution readiness
Blockchain-Native Timing:
- Uses immutable blockchain timestamps
- Cannot be manipulated by external actors
- Consistent across all network participants
Dual Validation:
- Timestamp AND block number must both be reached
- Prevents edge cases and timing attacks
- Ensures reliable 3.5-day intervals
Real-time Synchronization:
- Frontend stays synchronized with blockchain state
- Automatic retry mechanisms for failed requests
- Graceful handling of network interruptions
- ReentrancyGuard: Prevents reentrancy attacks
- Pausable: Emergency pause functionality
- Ownable: Admin access control
- Input Validation: Comprehensive number validation
- Safe Math: Overflow protection with Solidity 0.8+
- 🆕 Block-Based Timing: Enhanced security with block number validation
- 🆕 Dual Validation: Both time and block-based draw execution controls
- 🆕 Frontend Security: Improved UI state management prevents premature draw execution
- 🆕 Smart Contract Protection: Multiple layers of validation prevent unauthorized draws
KasDraw has undergone a comprehensive security audit. For detailed security analysis, vulnerability assessment, and recommendations, see:
Audit Summary:
- Overall Security Rating: HIGH
- Critical Vulnerabilities: None identified
- High-Risk Issues: None identified
- Medium-Risk Issues: 1 (RNG methodology - mitigated by Kasplex L2 speed)
- Status: Approved for testnet operation and well-positioned for mainnet deployment
KasDraw uses a sophisticated random number generation system that combines multiple entropy sources for better randomness distribution:
- Purpose: Ensures uniform distribution of selected numbers
- Process: Selects 5 unique numbers from 1-35 without replacement
- Guarantee: Each number has equal probability of selection
- Enhanced Odds: Improved winning chances with smaller number pool
// Multiple blockchain variables combined for entropy
uint256 baseEntropy = uint256(keccak256(abi.encodePacked(
block.timestamp, // Current block time
block.difficulty, // Network difficulty
block.number, // Current block number
block.coinbase, // Miner address
msg.sender, // Function caller
currentDrawId, // Draw identifier
totalTicketsSold, // Ticket sales count
address(this).balance, // Contract balance
gasleft() // Remaining gas
)));⚠️ Medium Risk: Uses on-chain variables for randomness- Mitigation: Multiple entropy sources reduce predictability
- Enhancement: Additional entropy generated for each number selection
- Future: Consider Chainlink VRF for production deployment
- Initialize: Create array of all possible numbers (1-49)
- Generate Base Entropy: Combine multiple blockchain variables
- Select Numbers: Use Fisher-Yates algorithm with enhanced entropy
- Sort Results: Return numbers in ascending order for consistency
- ✅ Uniform Distribution: Each number has equal selection probability
- ✅ No Duplicates: Algorithm guarantees unique number selection
- ✅ Enhanced Entropy: Multiple sources reduce predictability
- ✅ Gas Efficient: Optimized for blockchain execution
⚠️ Miner Influence: Potential manipulation on some networks⚠️ Predictability: Advanced actors might predict some variables- 💡 Recommendation: Upgrade to Chainlink VRF for maximum security
- Chain ID: 167012
- RPC URL: https://rpc.kasplex.org
- Currency: KAS
- Block Explorer: Kasplex Explorer
- Open MetaMask
- Add Custom Network
- Enter Kasplex testnet details
- Import test KAS tokens
The admin dashboard provides:
- Draw Management: Execute lottery draws
- Financial Overview: Monitor jackpots and fees
- Player Statistics: View participation metrics
- Emergency Controls: Pause/unpause functionality
- Responsive Design: Mobile-first approach
- Kaspa Theming: Turquoise and blue color scheme
- Real-time Updates: Live jackpot and countdown
- Transaction Feedback: Clear success/error messages
- Accessibility: WCAG compliant design
- 🔒 Critical Security Fixes: Fixed flawed prize calculation logic
- ⚡ Gas Optimization: Optimized
getDrawWinnersfunction for better performance - 🎯 Decentralized Execution: Added
executeDrawPublic()for community-driven draws - 🤖 Automation System: Comprehensive automated draw execution with monitoring
- 💰 Executor Incentives: 0.1 KAS reward for triggering draws
- 📊 Enhanced Events: Improved logging and transparency
- 📚 Documentation: Complete automation guide and setup instructions
- Block-Based Timing: Enhanced draw execution security with block number validation
- Dual Validation System: Both timestamp and block-based controls for draw execution
- Frontend Security: Improved UI state management prevents premature draw button activation
- Smart Contract Protection: Multiple validation layers prevent unauthorized draw execution
- Enhanced canExecuteDrawPublic: Returns comprehensive timing and block information
- UI Responsiveness: Fixed white page issues with better error handling and auto-refresh
- Contract Redeployment: New secure contract deployed at
0x5FbDB2315678afecb367f032d93F642f64180aa3
- Ticket Price Updated: Changed from 0.1 KAS to 10 KAS for enhanced prize pools
- Results Page Fixed: Resolved white screen issue with comprehensive error handling
- Security Audit Completed: Full security review with HIGH security rating
- Enhanced Error Handling: Improved RPC connection resilience and user feedback
- Simplified UI: Streamlined Results page for better user experience
- Enhanced Jackpot Display: Redesigned jackpot section with vibrant Kaspa.org-inspired colors
- Improved Visibility: Larger, more prominent jackpot numbers with gradient text effects
- Better Contrast: Enhanced color scheme for better readability
- Animated Elements: Added subtle animations and glow effects for visual appeal
- Color Palette Update: Refreshed CSS variables with Kaspa.org-inspired theme
- Responsive Design: Improved mobile and desktop jackpot display
- Performance: Optimized rendering and reduced bundle size
npm run testnpx hardhat test- Wallet connection
- Ticket purchase flow
- Number selection validation
- Prize claiming
- Admin functions
- Mobile responsiveness
MIT License - see LICENSE file for details
- Fork the repository
- Create a feature branch
- Commit your changes
- Push to the branch
- Open a Pull Request
For support and questions:
- Create an issue on GitHub
- Check the documentation
- Review the smart contract code
- ✅ Frontend: Complete and functional with enhanced security
- ✅ Smart Contract: Deployed with block-based timing security
- ✅ Web3 Integration: Fully implemented with improved error handling
- ✅ Local Development: Ready and tested
- ✅ Security Enhancements: Block-based timing and dual validation implemented
- ⏳ Testnet Deployment: Ready for deployment
- ⏳ Production Deployment: Pending final testing
Built with ❤️ for the Kaspa community