Skip to content

TypeScript/Express REST API for STO/RWA platforms. User auth, wallet integration, dual database (MongoDB/SQL). Legacy reference implementation.

Notifications You must be signed in to change notification settings

OnDemandWorld/sto-backend-api

Repository files navigation

🔗 STO Backend API

Part of the ODW ASSETTECH Legacy RWA / STO Reference Stack

⚡ About This Repository

This is the STO Backend API: a TypeScript/Express REST backend providing authentication, user management, wallet linking, and integration points between off-chain systems (databases, email, KYC providers) and the on-chain ERC-1400 token contracts. It is the glue layer that coordinates identity, sessions, and business logic across the STO platform.

Back in 2024, the ODW Team built a full Security Token Offering (STO) solution using the ERC‑1400 token standard on a private EVM chain running ConsenSys Quorum. Since then, the ecosystem has evolved: Quorum is no longer actively supported by ConsenSys (with Hyperledger Besu recommended as the successor), and STOs are now more commonly framed under the broader Real‑World Assets (RWA) narrative.

On the token side, ERC‑3643 (T‑REX) and ERC‑1155 have emerged as the most commonly used standards for regulated STO/RWA projects, with ERC‑3643 gaining prominence for its advanced, on‑chain compliance (DID, KYC/AML, transfer restrictions), and ERC‑1155 enabling efficient multi‑asset, multi‑class tokenization.

We are open‑sourcing this repository as a reference implementation to share architecture, design patterns, and integration approaches around ERC‑1400‑based STOs on permissioned EVM chains.

Important: This repository is not intended for production use. A production‑grade RWA/STO system today should:

  • Migrate from Quorum → Hyperledger Besu (or another actively maintained EVM execution client), and
  • Refactor token logic from ERC‑1400 → ERC‑3643 and/or ERC‑1155, with modern compliance and identity tooling.

📚 Repository Series

This repository is part of the ODW ASSETTECH legacy RWA collection:

  1. ERC1400 Token Dashboard (Frontend Dashboard)
  2. STO Backend API ← You are here (Express.js API with JWT, Wallet Auth)
  3. STO Web Client (Next.js Web Interface)
  4. ERC1400 Smart Contracts (Solidity Implementation)

Each repository can be explored independently, but together they form a complete STO platform architecture.


🎯 Overview

This backend API provides a comprehensive REST interface for STO operations with enterprise-grade features:

  • User Management: Registration, authentication, password reset, and profile management
  • Wallet Integration: Ethereum wallet connection and signature verification
  • Dual Database Support: MongoDB for document storage and SQL (PostgreSQL/MySQL) for relational data
  • RESTful API: Auto-generated routes and Swagger documentation via TSOA
  • Dependency Injection: Inversify for clean architecture and testability
  • Type Safety: Full TypeScript implementation with strict typing

🏗️ Architecture

High-Level Architecture

┌─────────────────┐
│   Express App    │
│   (TSOA Routes)  │
└────────┬─────────┘
         │
    ┌────▼─────┐
    │Controllers│
    └────┬─────┘
         │
    ┌────▼─────┐
    │ Services │
    └────┬─────┘
         │
    ┌────▼─────┐
    │Repositories│
    └────┬─────┘
         │
    ┌────▼─────┐
    │ Databases │
    │ (Mongo/SQL)│
    └──────────┘

Directory Structure

src/
├── config/          # Server, database connections, logging, error handling
├── controllers/     # TSOA route controllers
├── models/          # Data models and formatters
├── repositories/    # Data access layer (MongoDB & SQL)
├── services/        # Business logic layer
├── utils/           # Utility functions
├── auth.ts          # Authentication middleware
├── ioc.ts           # Dependency injection container
└── index.ts         # Application entry point

Key Technologies

  • Framework: Express.js
  • API Generation: TSOA (TypeScript OpenAPI)
  • DI Container: Inversify
  • MongoDB ORM: Mongoose with Typegoose
  • SQL ORM: Sequelize
  • Authentication: JWT (JSON Web Tokens)
  • Logging: Winston
  • Testing: Mocha, Chai, Supertest, Sinon

🚀 Getting Started

Prerequisites

  • Node.js >= 16.x
  • Yarn >= 1.22.x
  • MongoDB (for document storage)
  • PostgreSQL or MySQL (for relational data)
  • Environment variables configured (see Environment Variables)

Installation

  1. Clone the repository

    git clone https://github.com/OnDemandWorld/sto-backend-api.git
    cd sto-backend-api
  2. Install dependencies

    yarn install
  3. Set up environment variables

    cp .env.example .env.development
    # Edit .env.development with your configuration
  4. Run database migrations (if using SQL)

    yarn migrate:dev
  5. Seed databases (optional)

    yarn seed:sql:dev
    yarn seed:mongo:dev
  6. Start development server

    yarn start:dev

The API will be available at http://localhost:3000 (or your configured PORT).

⚙️ Configuration

Environment Files

Environment-specific configuration files are located in src/config/env/:

  • .env.development - Development environment
  • .env.test - Test environment
  • .env.production - Production environment

The active environment is determined by the NODE_ENV environment variable.

Database Configuration

The application supports both MongoDB and SQL databases:

  • MongoDB: Used for document-based storage (users, wallets)
  • SQL: Used for relational data (PostgreSQL/MySQL supported)

Both databases can be used simultaneously, with different repositories using different databases.

🔧 Environment Variables

Required Variables

# Server
NODE_ENV=development
PORT=3000

# MongoDB
MONGO_CONNECTION_STRING=mongodb://localhost:27017/sto-backend

# SQL Database
SQL_DB=sto_backend
SQL_USERNAME=postgres
SQL_PASSWORD=password
SQL_HOST=localhost
SQL_PORT=5432
SQL_DIALECT=postgres  # or 'mysql'

# JWT Authentication
JWT_SECRET=your-secret-key-change-in-production

# Email (Mailgun)
MAILGUN_APIKEY=your-mailgun-api-key
MAILGUN_DOMAIN=your-mailgun-domain

# Optional: Email Configuration
EMAIL_FROM=Your App <noreply@yourapp.com>
RESET_PASSWORD_URL=http://localhost:3000/reset-password

# Optional: CORS
ALLOWED_ORIGINS=http://localhost:3000,http://localhost:3001

Optional Variables

  • AWS_ACCESS_KEY_ID - AWS access key (if using AWS services)
  • AWS_SECRET_ACCESS_KEY - AWS secret key
  • AWS_MAINBUCKET - AWS S3 bucket name
  • AUTH0_DOMAIN - Auth0 domain (if using Auth0)
  • AUTH0_CLIENT_ID - Auth0 client ID
  • PUBNUB_PUBLISH_KEY - PubNub publish key

📝 Scripts

Development

# Start development server with hot reload
yarn start:dev

# Build TSOA routes and Swagger docs
yarn build:tsoa

Production

# Build for production
yarn build

# Start production server
yarn start:prod

Testing

# Run all tests (unit + integration)
yarn test

# Run unit tests only
yarn test:unit

# Run integration tests only
yarn test:integration

# Generate coverage report
yarn test:coverage

Database Migrations

# Development
yarn migrate:dev              # Run migrations
yarn migrate:undo:dev         # Rollback migrations

# Production
yarn migrate:prod             # Run migrations
yarn migrate:undo:prod        # Rollback migrations

Database Seeding

# SQL Seeding
yarn seed:sql:dev             # Seed SQL database
yarn seed:sql:undo:dev        # Undo SQL seeds

# MongoDB Seeding
yarn seed:mongo:dev            # Seed MongoDB
yarn seed:mongo:prod          # Seed MongoDB (production)

Code Quality

# Lint code
yarn lint

# Clean build artifacts
yarn clean

📚 API Documentation

Swagger UI

Once the server is running, API documentation is available at:

  • Swagger UI: http://localhost:3000/api-docs

The Swagger documentation is auto-generated from TSOA decorators in the controllers.

API Base Path

All API endpoints are prefixed with /api:

  • Base URL: http://localhost:3000/api

Authentication

Most endpoints require JWT authentication. Include the token in the Authorization header:

Authorization: Bearer <your-jwt-token>

Example Endpoints

User Management

  • POST /api/users/signup - Register a new user
  • POST /api/users/signin - Sign in and get JWT token
  • POST /api/users/signup/confirm - Confirm activation code
  • GET /api/users/info - Get current user info (requires JWT)
  • POST /api/users/change/password - Change password (requires JWT)

Wallet Management

  • GET /api/wallet/message - Get message to sign
  • POST /api/wallet/login - Login with wallet signature
  • POST /api/wallet/verify - Verify and link wallet (requires JWT)

🧪 Testing

Test Structure

  • Unit Tests: src/tests/unit/ - Test individual components in isolation
  • Integration Tests: src/tests/integration/ - Test API endpoints end-to-end

Running Tests

# All tests
yarn test

# Unit tests only
yarn test:unit

# Integration tests only
yarn test:integration

# With coverage
yarn test:coverage

Test Coverage

Coverage reports are generated in the coverage/ directory. Open coverage/index.html in a browser to view detailed coverage.

🚢 Deployment

Production Build

  1. Build the application

    yarn build
  2. Set environment variables

    export NODE_ENV=production
    # Set all required environment variables
  3. Run database migrations

    yarn migrate:prod
  4. Start the server

    yarn start:prod

Docker Deployment (Recommended)

Create a Dockerfile:

FROM node:16-alpine
WORKDIR /app
COPY package.json yarn.lock ./
RUN yarn install --frozen-lockfile --production
COPY . .
RUN yarn build
EXPOSE 3000
CMD ["yarn", "start:prod"]

Environment-Specific Considerations

  • CORS: Update ALLOWED_ORIGINS to restrict access to your frontend domains
  • JWT Secret: Use a strong, randomly generated secret in production
  • Database: Use connection pooling and read replicas for production
  • Logging: Configure log rotation and external log aggregation
  • Monitoring: Set up health checks and monitoring endpoints

🐛 Troubleshooting

Common Issues

Database Connection Errors

Problem: Cannot connect to MongoDB or SQL database

Solutions:

  • Verify database is running
  • Check connection strings in environment variables
  • Ensure network/firewall allows connections
  • Check database credentials

TSOA Build Errors

Problem: Routes not generating or Swagger docs missing

Solutions:

  • Run yarn build:tsoa manually
  • Check for TypeScript errors: yarn lint
  • Verify controller decorators are correct
  • Ensure build/ directory exists

JWT Authentication Fails

Problem: Authentication errors or token validation failures

Solutions:

  • Verify JWT_SECRET is set and consistent
  • Check token expiration
  • Ensure token is sent in Authorization: Bearer <token> format

Port Already in Use

Problem: EADDRINUSE error when starting server

Solutions:

  • Change PORT in environment variables
  • Kill process using the port: lsof -ti:3000 | xargs kill

Debug Mode

Enable verbose logging by setting:

NODE_ENV=development

🤝 Contributing

Development Workflow

  1. Create a feature branch

    git checkout -b feature/your-feature-name
  2. Make your changes

    • Follow existing code style
    • Add tests for new features
    • Update documentation as needed
  3. Run tests and linting

    yarn test
    yarn lint
  4. Commit your changes

    git commit -m "feat: add new feature"
  5. Push and create PR

    git push origin feature/your-feature-name

Code Style

  • Use TypeScript strict mode
  • Follow existing naming conventions
  • Add JSDoc comments for public methods
  • Keep functions small and focused
  • Use dependency injection for testability

📄 License

ISC


🌟 Support & Community

If this repository is useful to you as a reference for STO/RWA design, please consider:

  • Giving the project a ⭐ star on GitHub
  • Watching the repo to follow updates
  • Opening issues for questions, ideas, or problems you hit
  • Submitting pull requests with improvements or fixes

Your feedback and contributions help us decide how much more to invest in evolving these open‑source building blocks.


💼 Work with the ODW Team

ODW ASSETTECH specializes in:

  • RWA / STO architecture & solution design
  • Backend infrastructure - REST APIs, databases, authentication systems
  • Smart contract engineering (ERC‑3643, ERC‑1155, custom compliance modules)
  • Migration of legacy ERC‑1400 / Quorum stacks to Hyperledger Besu and modern standards
  • Backend & frontend integration (wallet flows, KYC/AML, dashboards, ops tooling)
  • Regulated environments: focusing on compliance‑aware tokenization flows

If you are:

  • A financial institution or issuer exploring tokenization,
  • A startup building an RWA platform, or
  • An engineering team looking to modernize an existing STO stack,

we'd be happy to discuss how we can help.

📧 Contact the ODW Team


🔗 Related Repositories in This Series

This repository is one component of a 4‑repo reference stack. For a fuller picture, explore the other repos in the ODW ASSETTECH organization.


Made by the ODW Team – sharing our 2024 STO stack as a reference for today's RWA builders.

About

TypeScript/Express REST API for STO/RWA platforms. User auth, wallet integration, dual database (MongoDB/SQL). Legacy reference implementation.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published