NexaFX is a Web3-powered currency exchange platform that supports real-time fiat and crypto conversions. The backend is built using NestJS and interfaces with smart contracts written in Rust on the Stellar network.
flowchart TD
subgraph Client
Web[Web App]
Mobile[Mobile App]
API[API Consumers]
end
subgraph Backend
Gateway[API Gateway]
Auth[Auth Module]
Users[Users Module]
Currencies[Currencies Module]
Transactions[Transactions Module]
ExchangeRates[Exchange Rates Module]
Admin[Admin Module]
Notifications[Notifications Module]
end
subgraph Database
PostgreSQL[(PostgreSQL)]
Redis[(Redis Cache)]
end
subgraph External
Stellar[Stellar Network]
Mailgun[Mailgun]
Firebase[Firebase]
RateProvider[Exchange Rate Provider]
end
Web --> Gateway
Mobile --> Gateway
API --> Gateway
Gateway --> Auth
Gateway --> Users
Gateway --> Currencies
Gateway --> Transactions
Gateway --> ExchangeRates
Gateway --> Admin
Gateway --> Notifications
Auth --> PostgreSQL
Users --> PostgreSQL
Currencies --> PostgreSQL
Transactions --> PostgreSQL
ExchangeRates --> Redis
Notifications --> PostgreSQL
Transactions --> Stellar
Notifications --> Mailgun
Notifications --> Firebase
ExchangeRates --> RateProvider
- JWT-based authentication and authorization
- Role-based access control (Admin, User, Tutor)
- Multi-currency exchange system
- Blockchain integration with Stellar smart contracts
- Real-time and historical transactions tracking
- Modular, scalable NestJS architecture
- Exportable transaction data (CSV, Excel, PDF)
nexafx-backend/
โโโ src/
โ โโโ admin/ # Admin panel and controls
โ โโโ audit-logs/ # Audit trail and logging
โ โโโ auth/ # JWT authentication & authorization
โ โโโ beneficiaries/ # Beneficiary management
โ โโโ blockchain/ # Stellar blockchain integration
โ โโโ common/ # Shared guards, interceptors, decorators, services
โ โโโ currencies/ # Fiat and crypto currency management
โ โโโ database/ # Database seeding scripts
โ โโโ exchange-rates/ # Real-time exchange rate providers
โ โโโ fees/ # Transaction fee management
โ โโโ health/ # Health check endpoints
โ โโโ kyc/ # KYC/AML compliance
โ โโโ notifications/ # Push & email notifications
โ โโโ otps/ # One-time passwords for 2FA
โ โโโ push-notifications/ # Firebase push notifications
โ โโโ rate-alerts/ # Rate change alerts (utility)
โ โโโ receipts/ # Transaction receipts
โ โโโ referrals/ # Referral program
โ โโโ scheduled-jobs/ # Background scheduled tasks
โ โโโ tokens/ # Refresh token management (utility)
โ โโโ transactions/ # Transaction processing & tracking
โ โโโ two-factor/ # Two-factor authentication
โ โโโ users/ # User management (CRUD, roles, profiles)
โ โโโ app.module.ts # Root application module
โ โโโ app.controller.ts # Root application controller
โ โโโ app.service.ts # Root application service
โ โโโ main.ts # Application entry point
โโโ migrations/ # TypeORM migration files
โโโ test/ # E2E and integration tests
โโโ .env.example # Environment configuration template
โโโ package.json # Dependencies and scripts
โโโ tsconfig.json # TypeScript configuration
โโโ README.md # This file
- Backend Framework: NestJS 11, TypeScript 5.7
- Database ORM: TypeORM 0.3 (PostgreSQL)
- Authentication: JWT (Passport.js), Bcrypt, TOTP
- Blockchain: Stellar SDK with Horizon API integration
- Background Jobs: NestJS Schedule (@nestjs/schedule)
- Notifications: Mailgun (email), Firebase (push notifications)
- Rate Limiting: NestJS Throttler
- Documentation: Swagger/OpenAPI
- Testing: Jest, Supertest
- Code Quality: ESLint, Prettier
- Node.js: v20+ (LTS recommended)
- Docker & Docker Compose: For running PostgreSQL
- npm: v9+ (comes with Node.js)
- Git: For version control
The fastest way to get started is using our automated setup script:
# Clone the repository
git clone https://github.com/Nexacore-Org/NexaFx-backend.git
cd NexaFx-backend
# Run the setup script (does everything for you!)
./scripts/setup-dev.sh
# Start the application
npm run start:devIf you prefer to set up manually:
git clone https://github.com/Nexacore-Org/NexaFx-backend.git
cd NexaFx-backendnpm ciCopy the .env.example file and create a .env file:
cp .env.example .envEdit .env and configure your variables (see Environment Variables section below).
docker-compose up -dnpm run typeorm:migration:runnpm run start:dev- API Docs: Visit
http://localhost:3000/api/docsfor Swagger UI - Health Check:
http://localhost:3000/health - Run Tests:
npm run test - Run Lint:
npm run lint - Format Code:
npm run format
Copy .env.example to .env and configure the following variables:
| Variable | Type | Required | Example | Description |
|---|---|---|---|---|
DATABASE_URL |
string | โ Yes | postgresql://user:pass@localhost:5432/nexafx |
PostgreSQL connection string |
DB_HOST |
string | โ Yes | localhost |
Database host address |
DB_PORT |
number | โ Yes | 5432 |
Database port |
DB_USERNAME |
string | โ Yes | postgres |
Database user |
DB_PASSWORD |
string | โ Yes | secure_password |
Database password |
DB_NAME |
string | โ Yes | nexafx |
Database name |
| Variable | Type | Required | Example | Description |
|---|---|---|---|---|
NODE_ENV |
string | โ Yes | development |
Runtime environment: development, staging, production |
PORT |
number | โ Yes | 3000 |
Server port |
| Variable | Type | Required | Min Length | Description |
|---|---|---|---|---|
JWT_SECRET |
string | โ Yes | 32 chars | Secret key for signing JWT tokens (keep secure in production) |
JWT_EXPIRES_IN |
string | โ Yes | N/A | JWT expiration time (e.g., 15m, 1h, 7d) |
REFRESH_TOKEN_SECRET |
string | โ Yes | 32 chars | Secret for refresh token signing |
REFRESH_TOKEN_EXPIRES_DAYS |
number | โ Yes | N/A | Refresh token lifespan in days (default: 30) |
| Variable | Type | Required | Description |
|---|---|---|---|
OTP_SECRET |
string | โ Yes | HMAC secret for TOTP generation (min 32 chars) |
OTP_EXPIRES_MINUTES |
number | โ Yes | OTP validity period in minutes (default: 10) |
| Variable | Type | Required | Description |
|---|---|---|---|
STELLAR_NETWORK |
string | โ Yes | Network: TESTNET or PUBLIC |
STELLAR_HORIZON_URL |
string | โ Yes | Horizon API endpoint (testnet: https://horizon-testnet.stellar.org) |
STELLAR_BASE_FEE |
number | โ Yes | Base transaction fee in stroops (typically 100) |
STELLAR_HOT_WALLET_SECRET |
string | โ Yes | Secret key for Stellar hot wallet (keep secure!) |
| Variable | Type | Required | Description |
|---|---|---|---|
WALLET_ENCRYPTION_KEY |
string | โ Yes | 64-character hex key for wallet encryption. Generate: openssl rand -hex 32 |
| Variable | Type | Required | Description |
|---|---|---|---|
MAILGUN_API_KEY |
string | โ Yes | Mailgun API key from dashboard |
MAILGUN_DOMAIN |
string | โ Yes | Verified Mailgun domain (e.g., mail.nexafx.com) |
MAILGUN_FROM_EMAIL |
string | โ Yes | Sender email address (e.g., [email protected]) |
MAILGUN_FROM_NAME |
string | โ No | Display name for emails (default: NexaFX) |
SKIP_EMAIL_SENDING |
boolean | โ No | Skip email sending in development (default: false) |
| Variable | Type | Required | Description |
|---|---|---|---|
FRONTEND_URL |
string | โ Yes | Frontend URL for CORS and email links (e.g., http://localhost:3001) |
| Variable | Type | Required | Description |
|---|---|---|---|
THROTTLE_TTL |
number | โ Yes | Time window in seconds (default: 60) |
THROTTLE_LIMIT |
number | โ Yes | Max requests per window (default: 100) |
THROTTLE_AUTH_LIMIT |
number | โ Yes | Max auth attempts per window (default: 5) |
| Variable | Type | Required | Description |
|---|---|---|---|
EXCHANGE_RATES_PROVIDER_BASE_URL |
string | โ Yes | Provider API base URL (default: https://api.exchangerate.host) |
EXCHANGE_RATES_PROVIDER_API_KEY |
string | โ No | API key if required by provider |
EXCHANGE_RATES_PROVIDER_TIMEOUT_MS |
number | โ Yes | Request timeout in milliseconds (default: 5000) |
EXCHANGE_RATES_CACHE_TTL_SECONDS |
number | โ Yes | Cache duration in seconds (default: 600 = 10 min) |
EXCHANGE_RATES_CACHE_MAX_SIZE |
number | โ Yes | Max cached rates (default: 1000) |
# Unit & Integration
npm run test
# E2E
npm run test:e2e
# Coverage
npm run test:covThe application implements role-based access control (RBAC) with the following roles:
- USER: Can perform standard exchange operations, manage own profile, view transactions
- ADMIN: Full control of all resources, user management, configuration, audit logs
- SUPER_ADMIN: System-level administrative access โ manages managed admins, platform configuration, and elevated role assignments via
src/super-admin/
Guards are applied at controller and route levels using custom decorators (@RequireRole(), @Permissions()) and NestJS Guards.
The codebase contains 150+ module directories. The following table lists the core modules that are fully implemented and integrated. Scaffold-stub modules (those containing NotImplementedException placeholders) are not listed here as complete.
| Module | File Location | Purpose | Status |
|---|---|---|---|
| auth | src/auth/ |
JWT authentication, password reset, OAuth2 strategies. Implements Passport.js strategies and JWT verification | โ Complete |
| admin | src/admin/ |
Admin dashboard, user moderation, system controls, configuration management | โ Complete |
| super-admin | src/super-admin/ |
Managed admin CRUD, role assignments, platform configuration. restricted to SUPER_ADMIN role | โ Complete |
| users | src/users/ |
User CRUD operations, profile management, roles, KYC status, personal data storage | โ Complete |
| currencies | src/currencies/ |
Fiat and crypto currency registry, metadata, pairs, support matrix | โ Complete |
| transactions | src/transactions/ |
Core exchange transactions, Stellar blockchain integration, settlement tracking, reversals | โ Complete |
| exchange-rates | src/exchange-rates/ |
Real-time rate fetching, multi-provider aggregation, in-memory caching | โ Complete |
| beneficiaries | src/beneficiaries/ |
Manage recipient accounts, wallets, bank details for transactions | โ Complete |
| kyc | src/kyc/ |
KYC/AML workflows, document collection, verification, compliance status | โ Complete |
| notifications | src/notifications/ |
Email & SMS system via Mailgun, verification codes, alerts, announcements | โ Complete |
| push-notifications | src/push-notifications/ |
Firebase Cloud Messaging (FCM) integration for mobile push notifications | โ Complete |
| referrals | src/referrals/ |
Referral program tracking, unique codes, rewards, commission calculation | โ Complete |
| receipts | src/receipts/ |
Transaction receipt generation and export (PDF via pdfkit, CSV, Excel via exceljs) | โ Complete |
| fees | src/fees/ |
Dynamic fee calculation, fee matrices, tier-based pricing, settlement | โ Complete |
| audit-logs | src/audit-logs/ |
Comprehensive audit trail for compliance, debugging, user activity tracking | โ Complete |
| scheduled-jobs | src/scheduled-jobs/ |
Background tasks: rate updates, data cleanup, notification batching, reconciliation | โ Complete |
| common | src/common/ |
Shared infrastructure: global guards, interceptors, decorators, pipes, error filters, shared services | โ Complete |
| health | src/health/ |
Health check endpoints for monitoring, load balancer integration, readiness/liveness probes | โ Complete |
| blockchain | src/blockchain/ |
Stellar SDK integration, Horizon API communication, contract deployment, transaction signing | โ Complete |
| two-factor | src/two-factor/ |
TOTP-based 2FA, recovery codes, backup authentication methods | โ Complete |
| otps | src/otps/ |
One-time password generation, validation, expiration, retry limits | โ Complete |
| analytics | src/analytics/ |
Platform analytics, usage metrics, reporting dashboards | โ Complete |
| dao | src/dao/ |
Decentralized governance, proposal creation, voting mechanisms | โ Complete |
| rate-alerts | src/rate-alerts/ |
Above/below absolute-threshold rate alerts with cron evaluation | โ Complete |
| sanctions | src/sanctions/ |
Sanctions screening, provider integration, compliance checks | โ Complete |
| disputes | src/disputes/ |
Dispute management, resolution workflows, admin controls | โ Complete |
| escrow | src/escrow/ |
Escrow accounts, fund locking, release/reversal workflows | โ Complete |
| compliance | src/compliance/ |
Compliance rules, checks, and reporting across modules | โ Complete |
| donations | src/donations/ |
Charitable donation processing, receipts, campaign tracking | โ Complete |
| cards | src/cards/ |
Virtual and physical card management, issuance, limits | โ Complete |
| loans | src/loans/ |
Loan products, applications, disbursement, repayment tracking | โ Complete |
| splits | src/splits/ |
Payment splits, beneficiary allocation, proportional distribution | โ Complete |
| vaults | src/vaults/ |
Secure storage, cold wallet management, key custody | โ Complete |
Swagger/OpenAPI documentation is available when the backend is running:
- URL: http://localhost:3000/api/docs
- Features: Interactive API explorer, request/response examples, schema definitions
- Auto-generated from NestJS decorators
Stellar Network provides the foundation for trustless, fast international transfers:
- Smart Contracts: Rust-based contracts deployed on Stellar
- Horizon API: Communication layer for account, ledger, and transaction queries
- Asset Creation: Native and custom asset support
- Multi-Signature Accounts: Enhanced security for hot wallets
- Transaction Flow: NestJS service โ Stellar SDK โ Horizon โ Ledger
Current implementation:
- Account creation and funding
- Asset issuance
- Payment operations
- Transaction signing and submission
- Advanced: path payments, atomic swaps
npm run test # Run all tests
npm run test:watch # Watch mode (re-run on file changes)
npm run test:cov # Generate coverage reportTest files follow the pattern: *.spec.ts
Coverage reports are generated in coverage/ directory
npm run test:e2e # Run end-to-end tests
npm run test:debug # Debug mode (use Chrome DevTools on port 9229)NODE_ENVโ runtime environment. Allowed values:development,staging,production,test.PORTโ application port, default3000.DATABASE_URLโ PostgreSQL connection string.JWT_SECRETโ JWT signing secret, minimum 32 characters.JWT_EXPIRES_INโ JWT expiration time, e.g.15m,1h,7d.ALLOWED_ORIGINSโ comma-separated allowed CORS origins.
GET /GET /health
This platform supports real-time updates via two complementary transports:
- Socket.IO Gateways (
src/gateways/): Optimized for high-throughput WebSocket clients and exchange rate feeds. - GraphQL Subscriptions (
src/graphql-subscriptions/): Powered bygraphql-ws, sharing underlying event streams with gateways for Apollo Client consumers with strict JWT authentication boundaries.