Cedarich/NexaFx-backend

โ˜… 0Forks 0TypeScriptGitHub โ†—Compare

Project website โ†—

README

NexaFX Backend v2

CI/CD Coverage License Node Version TypeScript

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.


๐Ÿ—๏ธ Architecture Diagram

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
Loading

๐Ÿš€ Features

  • 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)

๐Ÿ—๏ธ Project Structure

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

๐Ÿ“ฆ Tech Stack

  • 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

๐Ÿš€ Getting Started

Prerequisites

  • Node.js: v20+ (LTS recommended)
  • Docker & Docker Compose: For running PostgreSQL
  • npm: v9+ (comes with Node.js)
  • Git: For version control

Quick Start (Automated)

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:dev

Manual Setup

If you prefer to set up manually:

1. Clone the Repository

git clone https://github.com/Nexacore-Org/NexaFx-backend.git
cd NexaFx-backend

2. Install Dependencies

npm ci

3. Setup Environment Variables

Copy the .env.example file and create a .env file:

cp .env.example .env

Edit .env and configure your variables (see Environment Variables section below).

4. Start Database with Docker

docker-compose up -d

5. Run Database Migrations

npm run typeorm:migration:run

6. Start the Application

npm run start:dev

Development Workflow

  • API Docs: Visit http://localhost:3000/api/docs for Swagger UI
  • Health Check: http://localhost:3000/health
  • Run Tests: npm run test
  • Run Lint: npm run lint
  • Format Code: npm run format

โš™๏ธ Environment Variables

Copy .env.example to .env and configure the following variables:

Database Configuration

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

Application Configuration

Variable Type Required Example Description
NODE_ENV string โœ… Yes development Runtime environment: development, staging, production
PORT number โœ… Yes 3000 Server port

JWT & Authentication

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)

OTP & Two-Factor Authentication

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)

Stellar Blockchain

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!)

Wallet Encryption

Variable Type Required Description
WALLET_ENCRYPTION_KEY string โœ… Yes 64-character hex key for wallet encryption. Generate: openssl rand -hex 32

Email Service (Mailgun)

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)

Frontend Configuration

Variable Type Required Description
FRONTEND_URL string โœ… Yes Frontend URL for CORS and email links (e.g., http://localhost:3001)

Rate Limiting

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)

Exchange Rates Provider

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)


๐Ÿงช Running Tests

# Unit & Integration
npm run test

# E2E
npm run test:e2e

# Coverage
npm run test:cov

๐Ÿ” Role-Based Access Control

The 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.


๐Ÿ“ Module Overview & Architecture

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

๐Ÿ“„ API Documentation

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

๐Ÿงฑ Blockchain Integration

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

๐Ÿงช Testing Strategy

Unit & Integration Tests

npm run test           # Run all tests
npm run test:watch    # Watch mode (re-run on file changes)
npm run test:cov      # Generate coverage report

Test files follow the pattern: *.spec.ts
Coverage reports are generated in coverage/ directory

E2E Tests

npm run test:e2e       # Run end-to-end tests
npm run test:debug     # Debug mode (use Chrome DevTools on port 9229)

Environment Variables

  • NODE_ENV โ€” runtime environment. Allowed values: development, staging, production, test.
  • PORT โ€” application port, default 3000.
  • 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.

Health Check

  • GET /
  • GET /health

Real-Time Transport Architecture

This platform supports real-time updates via two complementary transports:

  1. Socket.IO Gateways (src/gateways/): Optimized for high-throughput WebSocket clients and exchange rate feeds.
  2. GraphQL Subscriptions (src/graphql-subscriptions/): Powered by graphql-ws, sharing underlying event streams with gateways for Apollo Client consumers with strict JWT authentication boundaries.

Contributors

portableDDnafiuishaaqLaGodxydependabot[bot]ibrahimmosouf-pngdzekojohn4No-bodyqMagrexyYaronZakikilodesodiq-archDivineifed1Hassan-oladipupoameeribro4-sudoSpycallsnowrugar-beepahmadogoQoder-Undefinedyusuftomilolarobertocarlousshamoo53bukasin1Kaybee973Sadeequaugustine00zphertyameenOyinkans0la12mijinummiwalexjnrBigBen-7Nanafancy

Issues