eco-core
v1.0.0
Published
A high-performance, production-ready MongoDB-based economy system for bots and applications.
Maintainers
Readme
eco-core
A high-performance, optimized MongoDB-based economy system for bots and applications
Features • Quick Start • API Reference • Examples • Configuration
🚀 Features
| Category | Features | |----------|----------| | 💰 Core Economy | Wallet & Bank System, Money Transfers, Bank Interest | | 🎁 Rewards | Daily/Weekly/Monthly Rewards, Streak Bonuses, Work System | | 🎁 Gift System | Send/Receive Gifts, Message Support, Privacy Controls | | 🎮 Gaming | Gambling Games (Coinflip, Dice, Slots), Achievement System | | 🛒 Commerce | Shop System, Inventory Management | | 📊 Analytics | Leaderboards, Statistics, User Rankings, Economy Health | | ⚙️ Management | User Settings, Bulk Operations, Admin Tools | | 🛡️ Security | Rate Limiting, Input Validation, Transaction Safety | | ⚡ Performance | In-Memory Caching, Connection Pooling, Optimized Queries |
📦 Installation
npm install eco-coreRequirements:
- Node.js 16.0.0 or higher
- MongoDB database
- Mongoose 8.0.0 or higher
🏃♂️ Quick Start
1. Basic Setup
import EconomySystem from 'eco-core';
// Create economy instance
const economy = new EconomySystem();
// Connect to MongoDB
await economy.connect('mongodb://localhost:27017/economy');
// Your economy system is ready!2. Essential Operations
// Get user balance
const balance = await economy.balance('user123', 'server456');
console.log(`Wallet: ${balance.wallet}, Bank: ${balance.bank}`);
// Give money to user
await economy.give('user123', 'server456', 100, 'Welcome bonus');
// Transfer between users
await economy.transfer('user123', 'user789', 'server456', 50, 'Gift');
// Daily reward
const reward = await economy.daily('user123', 'server456');
console.log(`Earned ${reward.totalReward} coins!`);3. Advanced Features
// Work system
const workResult = await economy.work('user123', 'server456');
console.log(`Worked and earned ${workResult.reward} coins!`);
// Gambling
const gamble = await economy.coinflip('user123', 'server456', 100, 'heads');
console.log(gamble.won ? 'Won!' : 'Lost!');
// Shop system
await economy.buyItem('user123', 'server456', 'sword_01', 'Iron Sword', 100, 1);
// Bank interest
const interest = await economy.collectInterest('user123', 'server456');
console.log(`Collected ${interest.interest} coins in interest!`);📚 API Reference
🔌 Connection Management
connect(uri, options)
Connect to MongoDB database with optimized settings.
await economy.connect('mongodb://localhost:27017/economy', {
useNewUrlParser: true,
useUnifiedTopology: true,
maxPoolSize: 20, // Optimized connection pooling
minPoolSize: 5, // Minimum connections ready
maxIdleTimeMS: 30000, // Connection idle timeout
bufferMaxEntries: 0, // Disable mongoose buffering
bufferCommands: false // Disable command buffering
});disconnect()
Safely disconnect from MongoDB.
await economy.disconnect();💰 Core Economy Functions
balance(userID, groupID)
Get or create user balance information.
Returns: { wallet, bank, bankCapacity, totalWealth, bankUsage, level, experience, nextLevelXP, streak, totalEarned, totalSpent }
const balance = await economy.balance('user123', 'server456');
console.log(`Total wealth: ${balance.totalWealth}`);
console.log(`Bank usage: ${balance.bankUsage}%`);give(userID, groupID, amount, reason)
Add money to user's wallet.
const result = await economy.give('user123', 'server456', 100, 'Event reward');deduct(userID, groupID, amount, reason)
Remove money from user's wallet.
const result = await economy.deduct('user123', 'server456', 50, 'Item purchase');transfer(fromUserID, toUserID, groupID, amount, reason)
Transfer money between users with transaction safety.
const result = await economy.transfer('user123', 'user789', 'server456', 100, 'Gift');🏦 Bank Operations
deposit(userID, groupID, amount)
Deposit money to bank. Use 'all' to deposit entire wallet.
// Deposit specific amount
await economy.deposit('user123', 'server456', 500);
// Deposit all wallet money
await economy.deposit('user123', 'server456', 'all');withdraw(userID, groupID, amount)
Withdraw money from bank. Use 'all' to withdraw everything.
// Withdraw specific amount
await economy.withdraw('user123', 'server456', 200);
// Withdraw all bank money
await economy.withdraw('user123', 'server456', 'all');addBankCapacity(userID, groupID, capacity)
Increase user's bank storage capacity.
await economy.addBankCapacity('user123', 'server456', 1000);collectInterest(userID, groupID)
Collect daily interest on bank deposits (5% daily rate).
const result = await economy.collectInterest('user123', 'server456');
console.log(`Collected ${result.interest} coins in interest!`);🎁 Reward Systems
daily(userID, groupID, baseReward)
Claim daily reward with streak bonus (10% per day).
const result = await economy.daily('user123', 'server456', 100);
console.log(`Earned ${result.totalReward} coins (${result.streakBonus} bonus)`);
console.log(`Current streak: ${result.streak} days`);⚡ Performance Features
balance(userID, groupID) - Cached
Get user balance with intelligent caching (2-minute TTL).
// First call: Database query
const balance1 = await economy.balance('user123', 'server456');
// Subsequent calls within 2 minutes: Cached response
const balance2 = await economy.balance('user123', 'server456'); // ~90% fasterleaderboard(groupID, limit, type) - Cached
Get leaderboard with caching (5-minute TTL).
// Cached leaderboard - much faster for repeated queries
const leaderboard = await economy.leaderboard('server456', 10, 'total');profile(userID, groupID) - Cached
Get user profile with caching (2-minute TTL).
// Cached profile data
const profile = await economy.profile('user123', 'server456');weekly(userID, groupID, baseReward)
Claim weekly reward (7-day cooldown).
const result = await economy.weekly('user123', 'server456', 500);monthly(userID, groupID, baseReward)
Claim monthly reward (30-day cooldown).
const result = await economy.monthly('user123', 'server456', 2000);💼 Work System
work(userID, groupID, baseReward)
Work to earn money with 30-minute cooldown and reward variance.
const result = await economy.work('user123', 'server456', 50);
console.log(`Earned ${result.reward} coins (base: ${result.baseReward}, variance: ${result.variance})`);🎰 Gambling System
coinflip(userID, groupID, bet, choice)
Play coin flip game (50% win rate, 2x payout).
const result = await economy.coinflip('user123', 'server456', 100, 'heads');
console.log(`Flipped ${result.result}, ${result.won ? 'Won' : 'Lost'} ${result.winnings} coins`);dice(userID, groupID, bet, prediction)
Play dice game. Predict 1-6, win 6x payout.
const result = await economy.dice('user123', 'server456', 50, 3);
console.log(`Rolled ${result.roll}, predicted ${result.prediction}, ${result.won ? 'Won' : 'Lost'} ${result.winnings} coins`);slots(userID, groupID, bet)
Play slots game (10% win rate, 5x payout).
const result = await economy.slots('user123', 'server456', 25);
if (result.won) console.log(`Jackpot! Won ${result.winnings} coins!`);🛒 Shop System
buyItem(userID, groupID, itemID, name, price, quantity)
Buy items from shop.
const result = await economy.buyItem('user123', 'server456', 'sword_01', 'Iron Sword', 100, 1);
console.log(`Bought ${result.quantity} ${result.name} for ${result.totalCost} coins`);sellItem(userID, groupID, itemID, sellPrice, quantity)
Sell items to shop.
const result = await economy.sellItem('user123', 'server456', 'sword_01', 80, 1);
console.log(`Sold ${result.soldQuantity} ${result.itemName} for ${result.totalEarnings} coins`);📊 Leaderboards & Analytics
leaderboard(groupID, limit, type)
Get leaderboard for a group.
Types: 'wallet', 'bank', 'total', 'level', 'experience'
const topUsers = await economy.leaderboard('server456', 10, 'total');
topUsers.forEach((user, index) => {
console.log(`${index + 1}. ${user.userID}: ${user.totalWealth} coins`);
});getStats(groupID)
Get comprehensive economy statistics.
const stats = await economy.getStats('server456');
console.log(`Total users: ${stats.totalUsers}`);
console.log(`Total wealth: ${stats.totalWealth}`);
console.log(`Average level: ${stats.avgLevel}`);getAnalytics(groupID)
Get detailed economy analytics and health metrics.
const analytics = await economy.getAnalytics('server456');
console.log(`Economy health: ${analytics.economyHealth}%`);
console.log(`Wealth distribution: ${analytics.wealthDistribution}`);getUserRank(userID, groupID, type)
Get user's ranking in a group.
const rank = await economy.getUserRank('user123', 'server456', 'total');
console.log(`Rank: ${rank.rank}/${rank.totalUsers} (${rank.percentile}th percentile)`);🏅 Achievement System
addAchievement(userID, groupID, achievementID, name, description, reward)
Add achievement to user with optional reward.
const result = await economy.addAchievement(
'user123',
'server456',
'first_win',
'First Victory',
'Win your first game',
500
);
console.log(`Achievement unlocked: ${result.achievement.name}`);getAchievements(userID, groupID)
Get all user achievements.
const achievements = await economy.getAchievements('user123', 'server456');
console.log(`Total achievements: ${achievements.totalAchievements}`);hasAchievement(userID, groupID, achievementID)
Check if user has specific achievement.
const hasAchievement = await economy.hasAchievement('user123', 'server456', 'first_win');
console.log(`Has first win achievement: ${hasAchievement.hasAchievement}`);📦 Inventory Management
addItem(userID, groupID, itemID, name, quantity, value)
Add item to user inventory.
await economy.addItem('user123', 'server456', 'sword_01', 'Iron Sword', 1, 100);removeItem(userID, groupID, itemID, quantity)
Remove item from user inventory.
await economy.removeItem('user123', 'server456', 'sword_01', 1);getInventory(userID, groupID)
Get user's complete inventory.
const inventory = await economy.getInventory('user123', 'server456');
console.log(`Total items: ${inventory.totalItems}, Total value: ${inventory.totalValue}`);🎁 Gift System
sendGift(fromUserID, toUserID, groupID, itemID, itemName, quantity, message, fromUserName)
Send a gift to another user with optional message.
const result = await economy.sendGift(
'user123', // Sender
'user789', // Recipient
'server456', // Group
'sword_01', // Item ID
'Iron Sword', // Item name
1, // Quantity
'Happy birthday!', // Message
'Aeon' // Sender name
);
console.log(`Gift sent! Fee: ${result.fee} coins`);openGift(userID, groupID, giftID)
Open a received gift to add items to inventory.
const result = await economy.openGift('user789', 'server456', 'gift_1234567890_abc123');
console.log(`Opened gift from ${result.fromUserName}: ${result.quantity}x ${result.itemName}`);
console.log(`Message: ${result.message}`);getGifts(userID, groupID, includeOpened)
Get user's gifts (unopened by default).
// Get only unopened gifts
const gifts = await economy.getGifts('user789', 'server456');
console.log(`Unopened gifts: ${gifts.unopenedCount}/${gifts.totalCount}`);
// Get all gifts including opened ones
const allGifts = await economy.getGifts('user789', 'server456', true);deleteGift(userID, groupID, giftID)
Delete an unopened gift.
await economy.deleteGift('user789', 'server456', 'gift_1234567890_abc123');
console.log('Gift deleted successfully');Gift System Features:
- ✅ Rate Limiting: Maximum 10 gifts per day per user
- ✅ Message Support: Up to 200 characters with sanitization
- ✅ Fee System: 2% fee based on item value
- ✅ Privacy Controls: Users can disable gifts in settings
- ✅ Experience Rewards: Senders get XP for generosity
⚙️ Settings & Management
updateSettings(userID, groupID, settings)
Update user settings and preferences.
await economy.updateSettings('user123', 'server456', {
notifications: true,
privacy: 'public',
currency: 'coins'
});getSettings(userID, groupID)
Get user settings.
const settings = await economy.getSettings('user123', 'server456');🔧 Admin Operations
bulkGive(operations, groupID)
Give money to multiple users at once.
const result = await economy.bulkGive([
{ userID: 'user1', amount: 100, reason: 'Event reward' },
{ userID: 'user2', amount: 200, reason: 'Event reward' }
], 'server456');
console.log(`Successfully gave money to ${result.successfulOperations} users`);resetGroup(groupID, options)
Reset all users in a group (admin function).
const result = await economy.resetGroup('server456', {
resetWallet: true,
resetBank: true,
resetLevel: false,
resetStreak: false
});🎯 Examples
Express API Server
import express from 'express';
import EconomySystem from 'eco-core';
const app = express();
const economy = new EconomySystem();
app.use(express.json());
// Connect to database
await economy.connect(process.env.MONGODB_URI);
// Get user balance
app.get('/api/balance/:userID/:groupID', async (req, res) => {
try {
const balance = await economy.balance(req.params.userID, req.params.groupID);
res.json({ success: true, data: balance });
} catch (error) {
res.status(500).json({ success: false, error: error.message });
}
});
// Daily reward
app.post('/api/daily/:userID/:groupID', async (req, res) => {
try {
const result = await economy.daily(req.params.userID, req.params.groupID);
res.json({ success: true, data: result });
} catch (error) {
res.status(400).json({ success: false, error: error.message });
}
});
// Transfer money
app.post('/api/transfer', async (req, res) => {
try {
const { fromUserID, toUserID, groupID, amount, reason } = req.body;
const result = await economy.transfer(fromUserID, toUserID, groupID, amount, reason);
res.json({ success: true, data: result });
} catch (error) {
res.status(400).json({ success: false, error: error.message });
}
});
// Get leaderboard
app.get('/api/leaderboard/:groupID', async (req, res) => {
try {
const { limit = 10, type = 'total' } = req.query;
const leaderboard = await economy.leaderboard(req.params.groupID, parseInt(limit), type);
res.json({ success: true, data: leaderboard });
} catch (error) {
res.status(500).json({ success: false, error: error.message });
}
});
// Send gift
app.post('/api/gift', async (req, res) => {
try {
const { fromUserID, toUserID, groupID, itemID, itemName, quantity, message, fromUserName } = req.body;
const result = await economy.sendGift(fromUserID, toUserID, groupID, itemID, itemName, quantity, message, fromUserName);
res.json({ success: true, data: result });
} catch (error) {
res.status(400).json({ success: false, error: error.message });
}
});
// Open gift
app.post('/api/gift/open', async (req, res) => {
try {
const { userID, groupID, giftID } = req.body;
const result = await economy.openGift(userID, groupID, giftID);
res.json({ success: true, data: result });
} catch (error) {
res.status(400).json({ success: false, error: error.message });
}
});
app.listen(3000, () => {
console.log('Economy API running on port 3000');
});⚙️ Configuration
Default Constants
The system uses these default values which you can customize:
import { COOLDOWNS, REWARDS, GAMBLING } from 'eco-core';
console.log('Cooldowns:', COOLDOWNS);
console.log('Rewards:', REWARDS);
console.log('Gambling:', GAMBLING);Cooldowns:
- Daily: 24 hours
- Weekly: 7 days
- Monthly: 30 days
- Work: 30 minutes
- Robbery: 1 hour
Rewards:
- Daily base: 100 coins
- Weekly base: 500 coins
- Monthly base: 2000 coins
- Streak multiplier: 10% per day
- Work base: 50 coins
- Work variance: ±30 coins
- Bank interest: 5% daily
Gambling:
- Coinflip win rate: 50%
- Dice range: 1-6
- Slots win rate: 10%
- Slots multiplier: 5x
Cache Configuration
The system includes intelligent caching with these default settings:
const CACHE_CONFIG = {
LEADERBOARD_TTL: 5 * 60 * 1000, // 5 minutes
STATS_TTL: 10 * 60 * 1000, // 10 minutes
USER_PROFILE_TTL: 2 * 60 * 1000, // 2 minutes
MAX_CACHE_SIZE: 1000 // Maximum cache entries
};Cache Features:
- Automatic TTL: Cache entries expire automatically
- LRU Eviction: Least recently used entries removed when cache is full
- Smart Invalidation: Cache cleared when data changes
- Memory Efficient: Optimized for high-traffic applications
Database Schema
The economy system uses this MongoDB schema:
{
groupID: String, // Server/group identifier
userID: String, // User identifier
wallet: Number, // Current wallet balance
bank: Number, // Current bank balance
bankCapacity: Number, // Maximum bank storage (default: 2500)
daily: Date, // Last daily claim
weekly: Date, // Last weekly claim
monthly: Date, // Last monthly claim
workTime: Date, // Last work timestamp
lastInterestCollection: Date, // Last interest collection
streak: Number, // Current daily streak
totalEarned: Number, // Lifetime earnings
totalSpent: Number, // Lifetime spending
level: Number, // User level
experience: Number, // User experience
inventory: Array, // User items
achievements: Array, // Unlocked achievements
gifts: Array, // Received gifts
settings: Object // User preferences
}🛡️ Error Handling
All methods include comprehensive error handling:
try {
const result = await economy.give('user123', 'server456', 100);
if (result.success) {
console.log('✅ Money given successfully!');
} else {
console.log('❌ Operation failed:', result.message);
}
} catch (error) {
console.error('💥 Economy operation failed:', error.message);
}Common Error Types
- Validation Errors: Invalid parameters (userID, amount, etc.)
- Cooldown Errors: Trying to claim rewards too early
- Insufficient Funds: Not enough money for operations
- Rate Limit Errors: Too many operations in short time
- Database Errors: Connection or query issues
🚦 Rate Limiting
Built-in protection against API abuse:
- Give operations: 5 per minute per user per group
- Transfer operations: 3 per minute per user per group
- Other operations: No rate limiting by default
Rate-limited operations return:
{
success: false,
message: 'Rate limit exceeded',
timeLeft: '45s',
timeLeftMs: 45000
}📈 Performance Tips
- Built-in Caching: The system automatically caches frequently accessed data
- Connection Pooling: Optimized MongoDB connections for high-traffic applications
- Lean Queries: Use
.lean()for read-only operations when possible - Bulk Operations: Use
bulkGive()for mass operations - Cache-Friendly: Repeated balance/profile queries are automatically cached
- Error Handling: Always wrap operations in try-catch blocks
- Rate Limiting: Built-in protection against API abuse
🔧 Troubleshooting
Common Issues
Connection Problems:
// Check MongoDB connection
await economy.connect('mongodb://localhost:27017/economy');
console.log('Connected successfully');User Not Found:
// Users are created automatically on first balance check
const balance = await economy.balance('user123', 'server456');Cooldown Issues:
// Check if user exists and has cooldown data
const profile = await economy.profile('user123', 'server456');
console.log('Last daily claim:', profile.daily);📝 Changelog
[1.0.0]
✨ Added
- Wallet & Bank System with customizable capacity
- Daily/Weekly/Monthly reward systems with streak bonuses
- Work system with cooldowns and reward variance
- Gambling system (coinflip, dice, slots) with configurable odds
- Shop system for buying and selling items
- Bank interest system with daily collection
- Achievement system with rewards and tracking
- User settings management and privacy controls
- Advanced analytics and user rankings
- Bulk operations for admin efficiency
- Leaderboards (wallet, bank, total wealth, level, experience)
- Inventory management system
- User leveling and experience system
- Comprehensive statistics and economy health metrics
- Rate limiting for critical operations
- Transaction safety for transfers
- Input sanitization and validation
- Multi-group support for multiple servers
- Performance optimized with proper indexing
- Error handling and data validation
🤝 Contributing
We welcome contributions! Here's how you can help:
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Development Setup
# Clone the repository
git clone https://github.com/Aeon-San/eco-core.git
# Install dependencies
npm install
# Run tests
npm test
# Run linter
npm run lint
# Build the project
npm run build📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
🆘 Support
Need help? Here are your options:
- 📖 Documentation: Check this README and the GitHub repository
- 🔍 Issues: Search existing issues
- 🐛 Bug Report: Create a new issue for bugs
- 💡 Feature Request: Suggest new features via issues
Community
- GitHub: eco-core
- Issues: Report problems
- Discussions: Community chat
Made with ❤️ by Aeon
⭐ Star this repository if it helped you!
