SwiftChain_Backend is the core API service for SwiftChain, a Blockchain-Powered Logistics & Escrow Delivery Platform. It connects individuals, businesses, and independent drivers in a decentralized logistics economy, ensuring trust through escrow payments and smart contracts.
SwiftChain revolutionizes logistics by enabling existing transport assets (motorcycles, trucks, independent couriers) to participate in a shared economy. It addresses trust issues in delivery services through blockchain-powered escrow mechanisms.
Traditional logistics are often centralized, expensive, and lack trust between unknown parties. SwiftChain bridges this gap by locking payments in escrow until delivery is confirmed.
The platform empowers:
- Small Logistics Operators & Drivers: Access to a steady stream of delivery requests.
- Underserved Communities: Access to global payments via Stellar's borderless network.
- Cross-Border Merchants: Seamless settlement for international goods movement.
- π African Logistics Markets
- π’ SMEs & E-commerce Merchants
- π΅ Courier Startups & Independent Drivers
- π’ Cross-Border Trade Facilitators
- Delivery Commission Fees: Percentage of each successful delivery.
- Escrow Service Charges: Small fee for securing the transaction.
- Enterprise Logistics APIs: Subscription for high-volume business integration.
- Cross-Border Settlement Fees: Currency conversion and transfer fees.
- Premium Analytics: Insights for fleet owners and businesses.
SwiftChain operates as a distributed system across three repositories:
- SwiftChain_Frontend: Next.js + TypeScript + TailwindCSS (User Interface)
- SwiftChain_Backend: Node.js + Express.js + TypeScript + MongoDB (Core Logic)
- SwiftChain_SmartContract: Stellar Soroban + Rust (Escrow & Trust)
The backend serves as the central hub connecting the frontend, database, and blockchain layers. Key responsibilities include:
- REST API for platform operations.
- Authentication & Authorization (JWT, RBAC).
- Delivery & Shipment Management (CRUD, Tracking).
- Driver Assignment Algorithms.
- File Upload Services (Receipts, Proof of Delivery).
- Real-Time Updates (WebSockets/Polling).
- Blockchain Integration Layer (Stellar/Soroban events).
- Runtime: Node.js
- Framework: Express.js
- Language: TypeScript
- Database: MongoDB (with Mongoose ODM)
- Authentication: JWT (JSON Web Tokens)
- Validation: Zod
- File Storage: Cloudinary / AWS S3
- Real-Time: Socket.io / Polling
- Documentation: Swagger / OpenAPI
- Logging: Winston
- Containerization: Docker & Docker Compose
- CI/CD: GitHub Actions
- Users: Register, Login, Create Requests.
- Drivers: Register, Verify, Accept Jobs.
- Admins: Platform Management.
- Security: JWT-based stateless auth with Role-Based Access Control (RBAC).
- Create Delivery: Customer details, pickup/drop-off locations, package info.
- Delivery List: Filtering, pagination, and status tracking.
- Status Workflow: Pending -> Assigned -> Picked Up -> In Transit -> Delivered.
- Mechanism to assign available drivers to pending delivery requests.
- Shipment Tracking: Detailed tracking of goods.
- Escrow Logic: Integration with Stellar Smart Contracts to lock/release funds based on delivery status.
- Secure upload of delivery receipts, images, and documents (PDF/JPG).
All endpoints are versioned under the /api prefix (e.g. /api/v1/...). The list below
mirrors what is mounted in src/routes/index.ts.
POST /api/v1/auth/register- Register a new user/driver.POST /api/v1/auth/login- Authenticate and retrieve token.
POST /api/v1/deliveries- Create a new delivery request.GET /api/v1/deliveries- Retrieve a list of deliveries (with filters).GET|PATCH /api/v1/deliveries/:id- Retrieve or update a delivery.PATCH /api/v1/deliveries/:id/assign-driver- Assign a driver (admin only; requires a fully initialised escrow).PATCH /api/v1/deliveries/:id/archive/.../restore- Soft-delete / restore.GET /api/v1/deliveries/:id/qrcode- Handoff verification QR code.GET /api/v1/deliveries/:id/eta- Estimated arrival time.PUT /api/v1/deliveries/:id/status- Advance the delivery status (driver/admin).
GET /api/v1/escrow/delivery/:id- Fetch the escrow record (locking state, amount, asset, contract id, on-chain transaction hashes) associated with a delivery.:idaccepts either the delivery_idor its businessdeliveryId.GET /api/v1/escrow/contract/:contractId- Fetch the escrow record by Soroban contract id.POST /api/v1/escrow/fund- Record an on-chainescrow_fundedevent (idempotent).POST /api/v1/escrow/sync- Manually trigger anescrow_fundedindexer poll.POST /api/v1/escrow/release- Release an escrow (Redlock-protected).GET /api/v1/admin/escrows/flagged- List escrows flagged as expired (admin only).PATCH /api/v1/admin/escrows/:id/resolve- Resolve a flagged escrow (admin only).
POST /api/v1/transactions/escrow-lock- Build the unsigned, simulation-prepared Soroban XDR that locks a delivery's escrow amount. Accepts{ deliveryId, payerAddress }; the amount and contract target are resolved server-side from MongoDB and the deployment configuration. The returned base64 envelope is signed and submitted by the client wallet β the backend never holds secret keys.POST /api/v1/transactions/submit- Submit a signed escrow-lock XDR with automatictx_bad_seqretry.
GET /api/v1/monitor/indexer-lag- On-demand indexer-lag check against the live ledger (admin only).GET /api/v1/monitor/indexer-lag/alerts- Recent persisted indexer-lag alerts (admin only).GET /api/v1/health- Liveness/readiness probe with Soroban RPC health check.
GET /api/v1/indexer/escrows/:escrowId- Escrow status from the database.POST /api/v1/indexer/escrows/sync/released- Manually syncescrow_releasedevents.POST /api/v1/indexer/escrows/sync/refunded- Manually syncescrow_refundedevents.POST /api/v1/indexer/delivery-created- Process adelivery_createdevent (indexer worker).
POST /api/v1/uploads/evidence- Upload dispute evidence media (authenticated).GET /api/v1/uploads/evidence/:disputeId- List evidence for a dispute (authenticated).
Collection endpoints can share a standardized query interface via the
buildQueryOptions middleware in src/middlewares/queryMiddleware.ts, which
parses and validates the query string once and hands the service layer a
ready-to-use Mongoose filter, sort and page window.
| Parameter | Description | Example |
|---|---|---|
page |
1-based page number | ?page=2 |
limit |
Items per page, clamped to the route maximum | ?limit=50 |
sort |
Comma-separated fields, - prefix for descending |
?sort=-createdAt,name |
search |
Case-insensitive search across searchable fields | ?search=lagos |
Filters accept direct equality or the comparison operators eq, ne, gt,
gte, lt, lte, in and nin in bracket notation:
GET /api/v1/deliveries?status=pending&amount[gte]=100&sort=-amount&page=1&limit=20Each route declares the fields it exposes, so only whitelisted fields can be
filtered or sorted on. buildPaginationMeta produces the accompanying
metadata:
{
"totalItems": 137,
"totalPages": 7,
"currentPage": 1,
"limit": 20,
"hasNextPage": true,
"hasPreviousPage": false,
"nextPage": 2,
"previousPage": null
}- Authentication System (Register/Login/JWT).
- Core Delivery CRUD Endpoints.
- Driver Assignment Logic.
- MongoDB Schema Design.
- Basic Validation & Error Handling.
- Stellar Payment Service Integration.
- Escrow Payment Initiation Endpoints.
- Transaction Tracking.
- Payment Verification Webhooks.
- Soroban Smart Contract Interaction Layer.
- Blockchain Event Listeners.
- Escrow Release Verification Logic.
- Delivery Proof Validation on Chain.
- Logistics Analytics & Reporting APIs.
- Fleet Management Features.
- Reputation & Scoring System for Drivers.
- Cross-Border Payment Logic.
- Advanced Monitoring (Prometheus/Grafana).
SwiftChain_Backend/
βββ .github/
β βββ workflows/
β βββ ci.yml # GitHub Actions CI pipeline
βββ docs/ # Documentation files
βββ postman/ # Postman collections
βββ scripts/ # Utility scripts (seed, migration)
βββ src/
β βββ config/ # Environment & App Config
β βββ controllers/ # Request Handlers
β βββ services/ # Business Logic
β βββ routes/ # API Route Definitions
β βββ middlewares/ # Express Middlewares (Auth, Error, Validation)
β βββ models/ # Mongoose Models
β βββ repositories/ # Data Access Layer
β βββ validators/ # Zod/Joi Schemas
β βββ utils/ # Helper Functions
β βββ types/ # TypeScript Type Definitions
β βββ interfaces/ # TypeScript Interfaces
β βββ events/ # Event Emitters/Handlers
β βββ sockets/ # WebSocket Handlers
β βββ uploads/ # File Upload Logic
β βββ blockchain/ # Stellar/Soroban Integration
β βββ database/ # DB Connection Logic
β βββ app.ts # Express App Setup
β βββ server.ts # Entry Point
βββ tests/ # Unit & Integration Tests
βββ .env.example # Environment Variables Example
βββ .eslintrc # Linter Config
βββ .prettierrc # Formatter Config
βββ docker-compose.yml # Docker Services
βββ Dockerfile # Docker Build Instructions
βββ package.json # Dependencies & Scripts
βββ tsconfig.json # TypeScript Config
βββ README.md # Project Documentation- Node.js v18+
- MongoDB v6.0+
- Docker (Optional)
git clone https://github.com/your-org/SwiftChain_Backend.git
cd SwiftChain_BackendCopy the example environment file and update the values.
cp .env.example .envpnpm installpnpm run devdocker-compose up --buildRun the test suite using Jest:
pnpm test- Fork the repository.
- Create a feature branch (
git checkout -b feature/amazing-feature). - Commit your changes (
git commit -m 'Add some amazing feature'). - Push to the branch (
git push origin feature/amazing-feature). - Open a Pull Request.
linked PR 5,4,6
This project is licensed under the ISC License.