Project Documentation
π 1. Overview
Merrick Investments PLC. β Cryptocurrency Investment Simulator: Comprehensive Project Overview
Project Purpose and Core Value Proposition
Merrick Investments PLC. is a high-fidelity cryptocurrency investment simulator designed to replicate real-world trading and portfolio management in a controlled, educational, and risk-free environment. Unlike traditional crypto exchanges, this platform does not execute real blockchain transactions. Instead, it simulates market behavior, investment growth, and transactional workflows using live market data from multiple API providers (CoinGecko, CryptoCompare) with robust fallback mechanisms. The platform serves dual purposes: as a financial modeling tool for users to practice investment strategies and as a management dashboard for administrators to oversee user activity, configure profit systems, and enforce platform-wide policies.
The system is built with Next.js 14 and leverages modern web technologies to deliver a responsive, secure, and visually polished user experience. It emphasizes real-time data visualization, automated profit generation, and granular administrative control, making it suitable for educational institutions, financial training programs, or internal corporate investment simulations. The inclusion of multi-currency support, transaction logging, and role-based access control ensures scalability and usability across diverse user bases.
Core Problem Solved
The primary challenge Merrick Investments PLC. addresses is the lack of accessible, realistic cryptocurrency investment simulators that combine real-time market data, automated profit modeling, and comprehensive administrative oversight. Many existing platforms either:
- Use static or delayed price feeds,
- Lack automation in profit generation,
- Fail to provide detailed transaction histories,
- Or do not offer robust admin tools for managing user accounts and system parameters.
This project solves these issues by:
- Delivering live market data with triple-layered fallback pricing to ensure reliability,
- Automating daily profit increments based on admin-defined rates,
- Enabling multi-asset deposits (BTC, ETH, SOL, USDT, fiat) with transparent conversion tracking,
- Providing a full admin suite for user management, role assignment, and system configuration,
- Ensuring secure authentication and data integrity through NextAuth.js and MongoDB.
The result is a production-grade simulation environment that closely mirrors real-world crypto investing while maintaining full control and visibility for administrators.
Architectural Design and Workflow
The application follows a client-server architecture with a Next.js 14 App Router frontend and a Node.js-based API layer that interacts with MongoDB for data persistence. Authentication is handled via NextAuth.js, supporting email/password login with role-based session management. User roles include standard users and administrators, with elevated permissions for managing deposits, withdrawals, and system settings.
Key workflows include:
- User Registration & Login: Secure onboarding with password reset support.
- Dashboard Interaction: Real-time balance updates, interactive charts (using Chart.js), and transaction history.
- Deposit & Withdrawal Processing: Users initiate transactions, which are logged and tracked in pending or completed states.
- Automated Profit Generation: Daily increments are calculated server-side and applied to user balances.
- Admin Oversight: Admins can view all users, adjust balances, toggle profit systems, and manage system-wide settings.
The system uses Axios for API calls with multi-provider fallback logic to ensure price data availability even if primary APIs fail. Images are stored via Cloudinary, and transaction receipts are dynamically generated with crypto-to-USD conversions.
Security and User Experience Considerations
Security is implemented through NextAuth.js with session encryption, MongoDB data encryption at rest, and SMTP-based email notifications for critical actions. The UI is fully responsive, employing Tailwind CSS and Vanilla CSS with glassmorphism aesthetics for a modern, intuitive interface.
Key UX features include:
- Interactive charts with real-time price updates,
- Clickable transaction rows that reveal detailed receipts,
- Responsive design optimized for mobile, tablet, and desktop,
- Customizable user profiles with image uploads,
- Error handling with user-friendly feedback.
The platform is designed to be ad-blocker resistant through server-side price fetching and robust API fallbacks, ensuring consistent performance.
Tech Stack at a Glance
| Category | Technology | Purpose |
|---|---|---|
| Framework | Next.js 14 (App Router) | Full-stack React framework with server components and routing |
| Language | TypeScript | Strongly typed JavaScript for scalability and maintainability |
| Database | MongoDB (Mongoose ODM) | NoSQL database for storing user data, transactions, and settings |
| Authentication | NextAuth.js | Secure session management and role-based access control |
| Styling | Tailwind CSS, Vanilla CSS | Responsive, modern UI with glassmorphism effects |
| Charts & Visualization | Chart.js, React-ChartJS-2 | Real-time market data visualization |
| API Integration | Axios | HTTP client with multi-provider fallback logic |
| Market Data Sources | CoinGecko, CryptoCompare | Real-time cryptocurrency pricing with redundancy |
| Image Management | Cloudinary | Cloud-based image storage and CDN delivery |
| Email & Notifications | Nodemailer (SMTP) | Sending transaction confirmations and system alerts |
| Testing | Playwright (E2E) | End-to-end testing of authentication and transaction flows |
| Environment | Node.js | JavaScript runtime for server-side logic |
| Version Control | Git (implied) | Source code management and collaboration |
Conclusion
Merrick Investments PLC. represents a sophisticated fusion of financial simulation, real-time data engineering, and enterprise-grade administration. By combining Next.js 14βs modern web capabilities with MongoDBβs flexible data model and NextAuth.jsβs robust security, the platform delivers a secure, scalable, and visually compelling investment simulator. Its emphasis on automation, fallback resilience, and admin control sets it apart from conventional crypto tools, making it ideal for educational, training, or internal financial modeling use cases. The project demonstrates best practices in full-stack development, API design, and user experienceβpositioning it as a reference implementation for similar simulation platforms.
π 2. Project Structure
Directory Structure
The codebase contains the following primary files and directories:
.gitignore.vscode/settings.jsonREADME.mddelete_tests.bate2e/auth.spec.tsjest.config.jsjest.setup.jslegal.txtnext-auth.d.tsnext.config.mjspackage-lock.jsonpackage.jsonplaywright.config.tspostcss.config.jssrc/app/admin/investments/page.tsxsrc/app/admin/layout.tsxsrc/app/admin/page.tsxsrc/app/admin/settings/page.tsxsrc/app/admin/users/[id]/investments/page.tsxsrc/app/admin/users/[id]/page.tsx
Generated via local analysis.
ποΈ 3. Architecture & Data Flow
Deep Architecture Analysis: Merrick Investments PLC. Cryptocurrency Investment Platform
1. Deep-Dive Architecture Reasoning
1.1 System Overview
Merrick Investments PLC. is a Next.js 14 application using the App Router architecture, implementing a monorepo-style structure with clear separation between frontend, backend, and shared components. The system follows a hybrid architecture combining:
- Serverless API Routes (Next.js API endpoints)
- Server Components (React Server Components)
- Client Components (interactive UI elements)
- Edge Functions (via middleware)
- Database Layer (MongoDB with Mongoose ODM)
1.2 Core Architecture Patterns
1.2.1 Domain-Driven Design (DDD) with Modular Monolith
The codebase exhibits modular monolith characteristics with clear domain separation:
- User Domain: Authentication, profiles, transactions
- Investment Domain: Portfolio management, deposits, profit tracking
- Admin Domain: User management, system settings, investment controls
- Shared Kernel: Common utilities, models, and types
1.2.2 Clean Architecture Layers
The architecture follows Clean Architecture principles with:
- Presentation Layer: React components (both server and client)
- Application Layer: API routes, business logic handlers
- Domain Layer: Core models (User, Investment, Transaction)
- Infrastructure Layer: Database connections, external APIs
1.2.3 CQRS (Command Query Responsibility Segregation)
The API structure demonstrates CQRS patterns:
- Commands (POST/PUT/DELETE routes) handle state mutations
- Queries (GET routes) handle data retrieval
- Separate read/write models (e.g.,
Usermodel vs. profile DTOs)
1.2.4 Repository Pattern
The database access follows the Repository Pattern through:
- Centralized
lib/db.tsconnection management - Model-specific repositories (implicit in Mongoose models)
- Separation of database concerns from business logic
1.2.5 Strategy Pattern for Price Fetching
The pricing system implements a Strategy Pattern for resilient price fetching:
// In lib/prices.ts
const providers = [coinGecko, cryptoCompare, staticPrices];
let lastPrice = null;
export async function getPrice(currency: string): Promise<number> {
for (const provider of providers) {
try {
const price = await provider.getPrice(currency);
lastPrice = price;
return price;
} catch (error) {
console.error(`Price provider ${provider.name} failed`, error);
}
}
return lastPrice; // Fallback to last known price
}
1.2.6 Observer Pattern for State Changes
The investment system uses an Observer Pattern for:
- Daily profit increments
- Transaction state changes
- Balance updates Implemented via:
- Database change streams (MongoDB)
- React state management
- Next.js revalidation triggers
1.3 Authentication Architecture
1.3.1 NextAuth.js Integration
The authentication system uses NextAuth.js with:
- Custom Credentials Provider (username/password)
- Session Management with JWT
- Role-Based Access Control (RBAC)
- Edge Middleware for route protection
Key authentication flows:
- Login: Credentials β Session creation β JWT
- Protected Routes: Middleware checks session
- Role-Based UI: Components render differently based on
session.user.role
1.3.2 Password Reset Flow
Implements a Token-Based Reset Pattern:
- User requests reset β Token generated (JWT with expiry)
- Token sent via email (Nodemailer)
- User clicks link β Server validates token β Allows password change
- Token invalidated after use
1.4 Data Flow Architecture
1.4.1 Transaction Processing Pipeline
- Client Request β API Route (Next.js)
- Validation Layer β Zod schemas
- Business Logic β Service layer
- Database Transaction β Mongoose operations
- State Update β Revalidation triggers
- Notification β Email/SMTP (if applicable)
1.4.2 Investment System Architecture
The investment system follows a Saga Pattern for complex operations:
- Deposit β Creates transaction β Updates balance β Triggers profit calculation
- Daily Increment β Scheduled job β Updates investments β Credits profits
- Withdrawal β Validates balance β Creates transaction β Updates balance
1.5 Frontend Architecture
1.5.1 Hybrid Rendering Strategy
The frontend uses a hybrid rendering approach:
- Server Components for:
- Layouts
- Data fetching
- SEO-critical content
- Client Components for:
- Interactive elements (modals, charts)
- State management
- Browser APIs
1.5.2 State Management
Uses a multi-tier state management approach:
- React Context (AuthProvider.tsx) for authentication state
- Component State (useState/useReducer) for local UI state
- URL State for shareable views (e.g., transaction filters)
- Server State via React Server Components
1.5.3 Charting Architecture
The CryptoChart component implements:
- Adapter Pattern for charting libraries
- Responsive Design with Tailwind
- Real-time Updates via WebSocket or polling
- Fallback Static Charts when APIs fail
1.6 Admin System Architecture
1.6.1 RBAC Implementation
The admin system uses a Role-Based Access Control pattern:
- Roles:
user,admin,superadmin - Permissions: Fine-grained via middleware checks
- UI Components: Conditionally rendered based on permissions
1.6.2 Bulk Operations
Admin operations implement:
- Command Pattern for bulk actions
- Batch Processing for large datasets
- Progress Tracking via UI feedback
1.7 Resilience Patterns
1.7.1 Circuit Breaker Pattern
The pricing system implements circuit breakers:
// In lib/prices.ts
const circuitBreakers = {
coinGecko: { failureCount: 0, timeout: 30000 },
cryptoCompare: { failureCount: 0, timeout: 30000 }
};
async function withCircuitBreaker(provider, fn) {
if (circuitBreakers[provider].failureCount > 5) {
if (Date.now() - circuitBreakers[provider].lastFailure < circuitBreakers[provider].timeout) {
throw new Error(`${provider} service unavailable`);
}
circuitBreakers[provider].failureCount = 0;
}
try {
const result = await fn();
circuitBreakers[provider].failureCount = 0;
return result;
} catch (error) {
circuitBreakers[provider].failureCount++;
circuitBreakers[provider].lastFailure = Date.now();
throw error;
}
}
1.7.2 Retry Mechanism
API calls implement exponential backoff:
// In lib/api.ts
async function fetchWithRetry(url, options, retries = 3, backoff = 1000) {
try {
const response = await fetch(url, options);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return await response.json();
} catch (error) {
if (retries <= 0) throw error;
await new Promise(res => setTimeout(res, backoff));
return fetchWithRetry(url, options, retries - 1, backoff * 2);
}
}
1.8 Testing Architecture
1.8.1 Test Pyramid Implementation
The test suite follows:
- Unit Tests: Jest for pure functions and components
- Integration Tests: Jest for API routes
- E2E Tests: Playwright for user flows
- Contract Tests: API route tests against models
1.8.2 Test Isolation
Tests use:
- Test Databases (in-memory MongoDB for unit tests)
- Mock Services (for external APIs)
- Fixtures (for consistent test data)
2. Data Flow & State Transitions
| Origin | Action | Logic Handler | Resulting State |
|---|---|---|---|
| User Browser | Navigate to /auth/login | Next.js routing | Loads login page |
| User Browser | Submit login form | NextAuth credentials provider | Validates credentials β Creates session β Redirects to /dashboard |
| User Browser | Click "Deposit" button | DepositModal component | Opens deposit modal |
| User Browser | Submit deposit form | /api/deposit route | Validates amount β Creates transaction β Updates user balance β Sends confirmation email |
| User Browser | Navigate to /dashboard/transactions | Transactions page component | Fetches transactions β Renders transaction list |
| Cron Job (Vercel) | Daily at 00:00 UTC | /api/invest route | Calculates daily profits β Updates all investments β Credits user balances |
| Admin Browser | Navigate to /admin/users | Admin users page | Fetches all users β Renders user list |
| Admin Browser | Click "Toggle Daily Increments" | /api/admin/users/[id] route | Updates user settings β Triggers profit calculation |
| Admin Browser | Upload profile image | /api/upload route | Processes image β Uploads to Cloudinary β Updates user profile |
| User Browser | Click "Reset Password" | /auth/forgot-password page | Generates reset token β Sends email β Shows confirmation |
| User Browser | Submit new password | /api/auth/reset-password route | Validates token β Updates password β Invalidates token |
| External API (CoinGecko) | Price update | lib/prices.ts | Updates cached prices β Triggers chart re-render |
| Database (MongoDB) | Investment document update | Mongoose middleware | Updates investment β Triggers balance recalculation |
| User Browser | Click transaction row | TransactionDetailModal | Fetches transaction details β Opens modal with receipt |
| User Browser | Navigate to /dashboard/investments | Investments page | Fetches investments β Calculates current value β Renders portfolio |
3. Mermaid.js Architecture Diagram
Diagram Explanation:
-
Client Layer:
- Top-level components organized by route
- AuthProvider wraps the entire application for session management
- Interactive components (modals, charts) are client-side
-
Authentication:
- Centralized auth configuration (
auth.ts) - NextAuth configuration with custom providers
- Session management via JWT
- Centralized auth configuration (
-
Data Layer:
- MongoDB connection management (
lib/db.ts) - Mongoose models for all domain entities
- Clear separation of concerns between models
- MongoDB connection management (
-
API Routes:
- Organized by domain (auth, user, admin, etc.)
- Each route handles its own validation and business logic
- Price fetching is centralized in
lib/prices.ts
-
External Services:
- Multiple price providers for resilience
- Email service for notifications
- Cloudinary for file storage
-
Middleware:
- Route protection for admin and sensitive endpoints
- Authentication validation
-
Testing:
- E2E tests with Playwright
- API tests with Jest
- Component tests with Jest
This architecture demonstrates a well-structured, maintainable system following modern React/Next.js patterns with clear separation of concerns and robust error handling.
π System Architecture Diagram
π οΈ 4. Function Breakdowns
Core Functionality
Based on the file tree, this project implements logic across 17 key source files including .vscode/settings.json, README.md, e2e/auth.spec.ts.
Generated via local analysis.