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.
- 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: v18+ (LTS recommended)
- PostgreSQL: v12+ running locally or via Docker
- npm or yarn
git clone https://github.com/Nexacore-Org/NexaFx-backend.git
cd NexaFx-backendnpm installCopy the .env.example file and create a .env file:
cp .env.example .envEdit .env and configure your variables (see Environment Variables section below).
Initialize the PostgreSQL database and apply migrations:
# Ensure PostgreSQL is running and DATABASE_URL is configured in .env
# TypeORM will auto-synchronize schema on startup if synchronize: true
# Create the database (first time only)
npm run typeorm:db:create
# Run migrations
npm run typeorm:migration:run
# OR generate a new migration after schema changes
npm run typeorm:migration:generate -- src/migrations/my-migration-name
# To revert the last migration
npm run typeorm:migration:revertNote: The application uses TypeORM with
autoLoadEntities: true, which automatically loads all entity metadata. Ensure all.entity.tsfiles are properly decorated with@Entity().
# Development (watch mode)
npm run start:dev
# Debug mode
npm run start:debug
# Production
npm run build
npm run start:prodThe API will be available at http://localhost:3000
API documentation: http://localhost:3000/api/docs
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., noreply@nexafx.com) |
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 (future)
Guards are applied at controller and route levels using custom decorators (@RequireRole(), @Permissions()) and NestJS Guards.
All major modules are fully implemented and integrated:
| 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 |
| 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 |
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)E2E test suite: test/jest-e2e.json
- Use
describe()blocks for logical grouping - Mock external services (Stellar, Mailgun, etc.)
- Test controller endpoints with
supertest - Test services in isolation with mocked repositories
- Aim for 80%+ coverage for critical paths
Follow Conventional Commits:
type(scope): subject
# Types: feat, fix, docs, style, refactor, perf, test, chore
# Scopes: auth, users, transactions, etc.
# Examples:
git commit -m "feat(transactions): add Stellar integration"
git commit -m "fix(auth): validate JWT expiration"
git commit -m "docs(readme): update setup instructions"
git commit -m "chore(deps): upgrade NestJS to 11.0.2"- Create feature branch:
git checkout -b feature/your-feature-name - Make changes and write tests
- Submit PR with description and linked issue
- Wait for CI/CD checks and code review
- Merge after approval
- Authentication module with JWT and refresh tokens
- User management (CRUD, profile, roles)
- Multi-currency support (fiat + crypto)
- Transactions module with full Stellar integration β Currently fully implemented
- Real-time exchange rate updates
- KYC/AML compliance workflows
- Email notifications (Mailgun)
- Push notifications (Firebase)
- Admin controls and audit logging
- Transaction receipts and export (PDF/CSV/Excel)
- Two-factor authentication (TOTP)
- Referral program
- Fee management system
- Scheduled background jobs
- Rate alerts
- Beneficiary management
- Advanced payment routing (path payments)
- DAO governance and voting
- Smart contract optimization
- Mobile app (React Native)
- Multi-wallet support
- API rate tiering
- Advanced reporting and analytics
- Webhook events system
- GraphQL API layer
Error: connect ECONNREFUSED 127.0.0.1:5432
Solution:
- Verify PostgreSQL is running:
brew services list(macOS) orsudo systemctl status postgresql(Linux) - Check
DATABASE_URLin.env - Default:
postgresql://postgres:postgres@localhost:5432/nexafx - Create database if missing:
createdb nexafx
Error: migrations not found
Solution:
# Ensure migration scripts exist in package.json
npm run typeorm:migration:run # Run pending migrations
npm run typeorm:migration:create -- src/migrations/fresh-migrationError: jwt malformed
Solution:
- Verify
JWT_SECRETis set in.env(minimum 32 characters) - Ensure token format:
Authorization: Bearer <token> - Check token expiration:
JWT_EXPIRES_IN(default: 15m)
Error: ECONNREFUSED (Horizon endpoint)
Solution:
- Verify
STELLAR_HORIZON_URL: testnet=https://horizon-testnet.stellar.org - Check internet connectivity
- Verify
STELLAR_NETWORKis set toTESTNETorPUBLIC - Testnet transactions: browse at https://stellar.expert/explorer/testnet
Error: Mailgun credentials invalid
Solution:
- Verify Mailgun API key and domain in
.env - Check
MAILGUN_DOMAINis verified in Mailgun dashboard - Test:
SKIP_EMAIL_SENDING=trueto bypass sending locally - Ensure
MAILGUN_FROM_EMAILmatches verified sender
Error: listen EADDRINUSE :::3000
Solution:
# Kill the process
lsof -ti:3000 | xargs kill -9 # macOS/Linux
netstat -ano | findstr :3000 # Windows
# Or use a different port
PORT=3001 npm run start:devError: Cannot find module '@nestjs/typeorm'
Solution:
# Reinstall dependencies
rm -rf node_modules package-lock.json
npm install
npm run buildEnable Debug Logging:
DEBUG=* npm run start:devTypeORM Query Logging:
Add to .env:
TYPEORM_LOGGING=true
Check Application State:
curl http://localhost:3000/healthView API Docs:
http://localhost:3000/api/docs
The NexaFX API provides health check endpoints for monitoring and uptime verification. These endpoints are designed for use with load balancers, orchestration platforms (e.g., Render, Kubernetes), and monitoring systems.
Returns the current status of the API service without making database queries. This endpoint is used by Render and other platforms to verify service liveness.
Request:
curl http://localhost:3000/Response:
{
"status": "ok",
"service": "NexaFX API",
"version": "1.0.0",
"timestamp": "2024-04-24T10:30:45.123Z",
"environment": "production"
}Status Code: 200 OK
Response Time: < 100ms (no database calls)
Authentication: Not required (@Public())
Performs a comprehensive health check including database connectivity and Stellar blockchain status. This endpoint is used for readiness probes to verify the service is fully operational.
Request:
curl http://localhost:3000/healthResponse:
{
"status": "ok",
"details": {
"database": "ok",
"stellar": "ok",
"cache": "ok"
}
}Status Codes:
200 OK- Service and all dependencies are healthy503 Service Unavailable- One or more dependencies are down
Authentication: Not required (@Public())
Render's infrastructure uses the GET / endpoint (HEAD requests) to verify service availability during deployments:
- Liveness Check: Render sends
HEAD /every 30 seconds - Readiness Check: Render sends
GET /healthbefore marking service as healthy - Configuration: No additional setup needed; Render uses the default health check
To monitor in Render's dashboard:
- View live logs: Check Logs tab for "GET /" requests
- Monitor uptime: Verify zero
Cannot HEAD /errors in error logs - Check dependencies: Use
GET /healthendpoint manually if database appears down
# Test liveness (quick check)
curl -i http://localhost:3000/
# Test readiness (full health check)
curl -i http://localhost:3000/health
# Monitor logs (development)
npm run start:dev | grep -i "health\|head\|404"| Resource | URL | Purpose |
|---|---|---|
| Frontend | NexaFx-frontend | Next.js 14 web UI with React, Tailwind CSS |
| Smart Contracts | NexaFx-contract | Rust smart contracts deployed on Stellar |
| API Docs | http://localhost:3000/api/docs | Interactive Swagger documentation (local) |
| Stellar Testnet Explorer | stellar.expert/explorer/testnet | View transactions and accounts on Stellar testnet |
| Stellar Horizon API | horizon-testnet.stellar.org | Official Stellar Horizon API endpoint |
This project is licensed under the MIT License. See the LICENSE file for details.
Have questions, need help, or want to contribute? Here's how to reach us:
| Channel | Link | Purpose |
|---|---|---|
| contact@nexacore.org | Business inquiries, partnerships | |
| Telegram | t.me/NexaFx | Community chat, quick support |
| GitHub Issues | Issues | Bug reports, feature requests |
| Discussions | Discussions | Technical questions, ideas |
We welcome contributions from the community! Please start with:
- Fork the repository
- Create a feature branch:
git checkout -b feature/your-feature - Commit changes:
git commit -m "feat(module): description"(see Commit Format) - Push to your fork:
git push origin feature/your-feature - Open a Pull Request with your changes
Before submitting:
- CI Pipeline Passes: Ensure GitHub Actions (Lint, Type-check, Tests, Build) complete successfully. Failing CI will block PR merges.
- Tests pass locally:
npm run test - Linting passes locally:
npm run lint - Coverage is adequate
- Updated README if adding major features
See CONTRIBUTING.md for detailed guidelines.
Happy coding! π