A real-time multiplayer Crash game with cryptocurrency integration, built with Node.js, Express, Socket.IO, and MongoDB.
Crypto Crash is a multiplayer gambling game where players bet in USD, which gets converted to cryptocurrency (BTC/ETH) using real-time prices. Players watch a multiplier increase exponentially and must cash out before the game "crashes" to win. The game features:
- Real-time multiplayer gameplay with WebSocket connections
- Cryptocurrency integration with live BTC/ETH prices from CoinGecko API
- Provably fair crash algorithm with transparent seed and hash verification
- Wallet system with USD, BTC, and ETH balances
- Transaction logging for all bets and cashouts
- Modern responsive UI with real-time charts and animations
- Rounds start every 10 seconds with a 3-second betting period
- Multiplier increases exponentially from 1x
- Provably fair crash points using cryptographic hashing
- Real-time multiplier updates every 100ms
- Automatic round management and state tracking
- Real-time BTC and ETH price fetching from CoinGecko API
- USD to crypto conversion at current market rates
- Wallet balances in USD, BTC, and ETH
- Transaction history with price tracking
- Fallback prices when API is unavailable
- Live multiplier updates
- Player bet and cashout notifications
- Round start/crash events
- Connected player count
- Real-time crypto price updates
- Input validation and sanitization
- Rate limiting on API endpoints
- Provably fair crash algorithm
- Atomic database transactions
- Error handling and logging
- Node.js - Runtime environment
- Express.js - Web framework
- Socket.IO - Real-time WebSocket communication
- MongoDB - NoSQL database
- Mongoose - MongoDB ODM
- Axios - HTTP client for API calls
- Winston - Logging
- Joi - Input validation
- Helmet - Security middleware
- Vanilla JavaScript - No framework dependencies
- Socket.IO Client - Real-time communication
- Chart.js - Real-time charts
- CSS3 - Modern styling with animations
- Font Awesome - Icons
- Node.js (v14 or higher)
- MongoDB (v4.4 or higher)
- npm or yarn
git clone <repository-url>
cd crypto-crash-gamenpm installCreate a .env file in the root directory:
cp env.example .envEdit the .env file with your configuration:
# Server Configuration
PORT=3000
NODE_ENV=development
# MongoDB Configuration
MONGODB_URI=mongodb://localhost:27017/crypto-crash
# Crypto API Configuration
COINGECKO_API_URL=https://api.coingecko.com/api/v3
# Game Configuration
GAME_ROUND_DURATION=10000
MULTIPLIER_UPDATE_INTERVAL=100
MAX_CRASH_MULTIPLIER=100
GROWTH_FACTOR=0.01
# Security
JWT_SECRET=your_jwt_secret_here
SESSION_SECRET=your_session_secret_here
# Rate Limiting
RATE_LIMIT_WINDOW_MS=900000
RATE_LIMIT_MAX_REQUESTS=100
# Logging
LOG_LEVEL=infoMake sure MongoDB is running on your system:
# On macOS with Homebrew
brew services start mongodb-community
# On Ubuntu/Debian
sudo systemctl start mongod
# On Windows
net start MongoDBRun the database setup script to create sample data:
npm run setup# Development mode with auto-restart
npm run dev
# Production mode
npm startThe application will be available at http://localhost:3000
Get current game state and active round information.
Response:
{
"status": "waiting",
"currentRound": {
"roundId": "1234567890-abc123",
"status": "waiting",
"startTime": "2024-01-01T00:00:00.000Z",
"crashPoint": 2.5,
"currentMultiplier": 1.0,
"totalBets": 1500,
"totalCashouts": 800,
"totalWinners": 3,
"totalLosers": 2,
"seed": "abc123...",
"hash": "def456..."
}
}Place a bet in the current round.
Request:
{
"playerId": "player1",
"username": "CryptoKing",
"usdAmount": 100,
"currency": "btc"
}Response:
{
"success": true,
"betData": {
"playerId": "player1",
"username": "CryptoKing",
"usdAmount": 100,
"cryptoAmount": 0.0016,
"currency": "btc",
"priceAtTime": 62500
},
"playerBalance": {
"usd": 900,
"btc": 0.001,
"eth": 0.05
}
}Cash out during an active round.
Request:
{
"playerId": "player1",
"username": "CryptoKing"
}Response:
{
"success": true,
"multiplier": 2.5,
"payoutCrypto": 0.004,
"payoutUsd": 250,
"playerBalance": {
"usd": 900,
"btc": 0.005,
"eth": 0.05
}
}Get round history with pagination.
Query Parameters:
limit(optional): Number of rounds to return (default: 10)page(optional): Page number (default: 1)
Response:
{
"rounds": [
{
"roundId": "1234567890-abc123",
"status": "crashed",
"crashPoint": 2.5,
"totalBets": 1500,
"totalCashouts": 800,
"totalWinners": 3,
"totalLosers": 2,
"startTime": "2024-01-01T00:00:00.000Z",
"endTime": "2024-01-01T00:00:10.000Z"
}
],
"pagination": {
"page": 1,
"limit": 10,
"total": 50,
"pages": 5
}
}Get player wallet balance with USD equivalents.
Response:
{
"playerId": "player1",
"username": "CryptoKing",
"wallet": {
"btc": 0.001,
"eth": 0.05,
"usd": 1000,
"btcUsd": 62.5,
"ethUsd": 150,
"totalUsd": 1212.5
},
"statistics": {
"totalBets": 2500,
"totalWins": 3200,
"totalLosses": 800
},
"prices": {
"btc": 62500,
"eth": 3000
}
}Create a new player wallet.
Request:
{
"playerId": "newplayer",
"username": "NewPlayer"
}Get player transaction history.
Query Parameters:
limit(optional): Number of transactions (default: 20)page(optional): Page number (default: 1)
Simulate a deposit to player wallet.
Request:
{
"playerId": "player1",
"amount": 1000,
"currency": "usd"
}Get current cryptocurrency prices.
Response:
{
"success": true,
"prices": {
"btc": 62500,
"eth": 3000
},
"timestamp": "2024-01-01T00:00:00.000Z"
}Convert between USD and cryptocurrency.
Query Parameters:
amount: Amount to convertfromCurrency: Source currency (usd, btc, eth)toCurrency: Target currency (usd, btc, eth)
Response:
{
"success": true,
"conversion": {
"fromAmount": 100,
"fromCurrency": "usd",
"toAmount": 0.0016,
"toCurrency": "btc",
"rate": 62500
}
}Authenticate player with the game.
socket.emit('authenticate', {
playerId: 'player1',
username: 'CryptoKing'
});Place a bet in the current round.
socket.emit('placeBet', {
usdAmount: 100,
currency: 'btc'
});Cash out during an active round.
socket.emit('cashout', {});Authentication successful.
socket.on('authenticated', (data) => {
console.log('Connected players:', data.connectedPlayers);
});Current game state update.
socket.on('gameState', (state) => {
console.log('Game status:', state.status);
});New round started.
socket.on('roundStart', (data) => {
console.log('Round ID:', data.roundId);
console.log('Seed:', data.seed);
console.log('Hash:', data.hash);
});Real-time multiplier update.
socket.on('multiplierUpdate', (data) => {
console.log('Multiplier:', data.multiplier);
console.log('Elapsed time:', data.elapsedTime);
});Round crashed event.
socket.on('roundCrashed', (data) => {
console.log('Crash point:', data.crashPoint);
console.log('Final multiplier:', data.finalMultiplier);
});Player placed a bet.
socket.on('betPlaced', (data) => {
console.log('Player:', data.username);
console.log('Amount:', data.usdAmount);
console.log('Currency:', data.currency);
});Player cashed out.
socket.on('cashoutProcessed', (data) => {
console.log('Player:', data.username);
console.log('Multiplier:', data.multiplier);
console.log('Payout:', data.payoutUsd);
});The crash point is generated using a provably fair algorithm:
- Seed Generation: A random 32-byte seed is generated for each round
- Hash Creation: The seed is combined with the round ID and hashed using SHA-256
- Random Value: The first 8 bytes of the hash are converted to a random number
- Crash Point: The random number is converted to a crash point using the formula:
crash_point = max(1, (1 / (1 - random_value)) * (1 - house_edge)) - House Edge: A 1% house edge is applied to ensure profitability
Players can verify the crash point using the provided seed and round ID. The algorithm is deterministic and can be independently verified.
{
playerId: String,
username: String,
wallet: {
btc: Number,
eth: Number,
usd: Number
},
totalBets: Number,
totalWins: Number,
totalLosses: Number,
createdAt: Date,
lastActive: Date
}{
roundId: String,
status: String, // 'waiting', 'active', 'crashed'
startTime: Date,
endTime: Date,
crashPoint: Number,
seed: String,
hash: String,
maxMultiplier: Number,
bets: [BetSchema],
totalBets: Number,
totalCashouts: Number,
totalWinners: Number,
totalLosers: Number,
houseProfit: Number
}{
transactionId: String,
playerId: String,
username: String,
transactionType: String, // 'bet', 'cashout', 'deposit'
roundId: String,
currency: String,
usdAmount: Number,
cryptoAmount: Number,
priceAtTime: Number,
multiplier: Number,
transactionHash: String,
status: String,
balanceBefore: Object,
balanceAfter: Object,
timestamp: Date
}curl http://localhost:3000/api/game/statecurl -X POST http://localhost:3000/api/game/bet \
-H "Content-Type: application/json" \
-d '{
"playerId": "player1",
"username": "CryptoKing",
"usdAmount": 100,
"currency": "btc"
}'curl -X POST http://localhost:3000/api/game/cashout \
-H "Content-Type: application/json" \
-d '{
"playerId": "player1",
"username": "CryptoKing"
}'curl http://localhost:3000/api/wallet/balance/player1curl http://localhost:3000/api/crypto/pricesYou can test WebSocket functionality using the browser console or a WebSocket client:
// Connect to WebSocket
const socket = io('http://localhost:3000');
// Authenticate
socket.emit('authenticate', {
playerId: 'testplayer',
username: 'TestPlayer'
});
// Listen for events
socket.on('authenticated', (data) => {
console.log('Authenticated:', data);
});
socket.on('gameState', (state) => {
console.log('Game state:', state);
});
socket.on('multiplierUpdate', (data) => {
console.log('Multiplier:', data.multiplier);
});NODE_ENV=production
PORT=3000
MONGODB_URI=mongodb://your-production-mongodb-url
COINGECKO_API_URL=https://api.coingecko.com/api/v3
JWT_SECRET=your-secure-jwt-secret
SESSION_SECRET=your-secure-session-secret# Install PM2
npm install -g pm2
# Start the application
pm2 start server.js --name crypto-crash
# Save PM2 configuration
pm2 save
# Setup PM2 to start on boot
pm2 startupFROM node:16-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
EXPOSE 3000
CMD ["npm", "start"]This project is licensed under the MIT License.
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests if applicable
- Submit a pull request
For support or questions, please open an issue on GitHub or contact the development team.
- Additional cryptocurrencies (LTC, BCH, etc.)
- Advanced charting with technical indicators
- Social features (chat, leaderboards)
- Mobile app development
- Advanced betting options (auto-cashout)
- Tournament mode
- Affiliate system
- Advanced analytics dashboard