Production-grade NestJS backend for PetAd โ a blockchain-backed platform enabling secure pet adoption and temporary custody with verifiable on-chain guarantees. Exposes REST APIs for the frontend and orchestrates escrow workflows using the PetAd Stellar SDK.
- Architecture Overview
- Key Responsibilities
- Features
- Tech Stack
- Prerequisites
- Getting Started
- Project Structure
- Escrow & Trust Flow
- API Documentation
- Docker Services
- Scripts
- Testing
- Security
- Deployment
- Roadmap
- Contributing
- License
PetAd Core acts as the central coordinator in the PetAd ecosystem, bridging the user-facing frontend with the blockchain trust layer.
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Frontend (React) โ
โ User Interface Layer โ
โโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โ REST API (HTTP/JSON)
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ PetAd Core Backend (NestJS) โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ Controllers (REST endpoints) โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ Services (Business logic) โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ Escrow Orchestration Layer โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ Event Logging (Audit trail) โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โโโโโโฌโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโ
โ โ โ
โผ โผ โ
โโโโโโโโโโโโ โโโโโโโโโโโโ โ
โPostgreSQLโ โ Redis โ โ
โ(Prisma) โ โ(Queue) โ โ
โโโโโโโโโโโโ โโโโโโโโโโโโ โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโ
โ PetAd Stellar SDK โ
โ (Blockchain Layer) โ
โโโโโโโโโโโโฌโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโ
โ Stellar Blockchain โ
โ (Trust Layer) โ
โโโโโโโโโโโโโโโโโโโโโโโ
- ๐ Security First - No private keys exposed to clients
- ๐ Event Logging - Audit trail of all operations
- โก Async Operations - Background jobs for blockchain interactions
- ๐ฏ Domain-Driven - Clear separation of concerns
- ๐ Idempotent - Safe to retry all operations
The backend service handles:
โ Authentication & Authorization
- JWT-based authentication
- Role-based access control (USER, ADMIN, SHELTER)
- Session management
- Password hashing with bcrypt
โ Pet Management
- CRUD operations for pet listingshttps://github.com/EzeanoroEbuka/PetAd-backend.git
- Search and filtering
- Image upload and storage
- Availability status tracking
โ Adoption Workflows
- Adoption request submission
- Document upload and storage
- Status tracking (PENDING โ APPROVED โ COMPLETED)
- Admin approval system
โ Temporary Custody
- Time-bound custody agreement creation
- Deposit amount calculation
- Duration tracking
- Status management
โ Escrow Orchestration
- Creates escrow accounts via Stellar SDK
- Coordinates with blockchain layer
- Monitors transaction confirmations
- Updates internal records
โ Event Logging
- Logs all significant operations
- Provides audit trail
- Stores transaction references
โ Background Jobs
- Blockchain confirmation polling
- Notification delivery
- Scheduled task execution
๐ Advanced event sourcing, trust scoring, and reputation systems are planned for future phases.
- โ RESTful API - Clean, documented endpoints
- โ JWT Authentication - Secure token-based auth
- โ Database Migrations - Version-controlled schema with Prisma
- โ Background Jobs - BullMQ for async tasks
- โ File Uploads - Secure document storage
- โ API Validation - Request/response validation with DTOs
- โ Error Handling - Standardized error responses
- โ Logging - Structured logging
- โ Health Checks - Readiness and liveness probes
- โ Swagger Docs - Auto-generated API documentation
- โ Docker Support - Containerized deployment
| Technology | Version | Purpose |
|---|---|---|
| NestJS | 10+ | Progressive Node.js framework |
| TypeScript | 5.0+ | Type-safe development |
| Node.js | 20+ | Runtime environment |
| Technology | Version | Purpose |
|---|---|---|
| PostgreSQL | 16+ | Primary relational database |
| Prisma ORM | Latest | Type-safe database client |
| Redis | 7+ | Caching and job queues |
| Technology | Purpose |
|---|---|
| PetAd Stellar SDK | Blockchain operations (escrow, transactions) |
| @petad/stellar-sdk | npm package for Stellar integration |
| Technology | Purpose |
|---|---|
| BullMQ | Job queue management |
| Bull Board | Queue monitoring dashboard |
| Technology | Purpose |
|---|---|
| Docker | Containerization |
| Docker Compose | Local development orchestration |
| GitHub Actions | CI/CD pipeline |
Ensure you have the following installed:
- Node.js
>= 20.0.0 - npm
>= 10.0.0or pnpm>= 8.0.0 - Docker
>= 24.0.0 - Docker Compose
>= 2.0.0 - PostgreSQL
>= 16.0(or use Docker) - Redis
>= 7.0(or use Docker)
Verify installations:
node --version
npm --version
docker --version
docker-compose --version- Clone the repository
git clone https://github.com/amina69/PetAd-Backend.git
cd petad-core- Install dependencies
npm installOr using pnpm:
pnpm install- Install PetAd Stellar SDK
npm install @petad/stellar-sdkCreate a .env file in the project root:
# Database Configuration
DATABASE_URL=postgresql://petad:petad@localhost:5432/petad
# Redis Configuration
REDIS_URL=redis://localhost:6379
# Stellar Blockchain
STELLAR_NETWORK=testnet
STELLAR_SECRET_KEY=S... # Backend signing key (CRITICAL)
STELLAR_PUBLIC_KEY=G... # Backend public address
STELLAR_HORIZON_URL=https://horizon-testnet.stellar.org
# Authentication
JWT_SECRET=your-super-secure-jwt-secret-min-32-characters
JWT_EXPIRATION=7d
# Application
PORT=3000
NODE_ENV=development
# File Upload
MAX_FILE_SIZE=10485760 # 10MB in bytes
UPLOAD_DEST=./uploads
# Background Jobs
QUEUE_CONCURRENCY=5
JOB_ATTEMPTS=3
JOB_BACKOFF_DELAY=5000
# Monitoring (Optional)
SENTRY_DSN=
LOG_LEVEL=debug # debug | info | warn | error
# Email (Optional)
SMTP_HOST=smtp.example.com
SMTP_PORT=587
SMTP_USER=
SMTP_PASS=Create .env from example:
cp .env.example .env
# Edit .env with your valuesStart PostgreSQL and Redis:
docker-compose up -d postgres redisIf not using Docker:
# Create PostgreSQL database
createdb petad
# Start Redis
redis-server# Generate Prisma Client
npx prisma generate
# Run database migrations
npx prisma migrate dev --name init
# Seed database with sample data (optional)
npm run seednpx prisma studio
# Opens at http://localhost:5555npm run start:devnpm run build
npm run start:prodnpm run start:debugServer will be available at:
http://localhost:3000
Health check:
curl http://localhost:3000/healthExpected response:
{
"status": "ok",
"database": "connected",
"redis": "connected"
}src/
โโโ auth/ # Authentication & authorization
โ โโโ auth.controller.ts
โ โโโ auth.service.ts
โ โโโ jwt.strategy.ts
โ โโโ guards/
โ โ โโโ jwt-auth.guard.ts
โ โ โโโ roles.guard.ts
โ โโโ dto/
โ โโโ login.dto.ts
โ โโโ register.dto.ts
โ
โโโ users/ # User management
โ โโโ users.controller.ts
โ โโโ users.service.ts
โ โโโ users.repository.ts
โ โโโ entities/
โ โโโ user.entity.ts
โ
โโโ pets/ # Pet listings & management
โ โโโ pets.controller.ts
โ โโโ pets.service.ts
โ โโโ pets.repository.ts
โ โโโ dto/
โ โโโ create-pet.dto.ts
โ โโโ search-pets.dto.ts
โ
โโโ adoption/ # Adoption workflows
โ โโโ adoption.controller.ts
โ โโโ adoption.service.ts
โ โโโ adoption.state-machine.ts
โ โโโ dto/
โ โโโ create-adoption.dto.ts
โ โโโ approve-adoption.dto.ts
โ
โโโ custody/ # Temporary custody
โ โโโ custody.controller.ts
โ โโโ custody.service.ts
โ โโโ custody.scheduler.ts
โ โโโ entities/
โ โโโ custody.entity.ts
โ
โโโ escrow/ # Escrow orchestration
โ โโโ escrow.service.ts # Main escrow logic
โ โโโ escrow.repository.ts
โ โโโ escrow.orchestrator.ts # Coordinates with Stellar SDK
โ โโโ dto/
โ โโโ create-escrow.dto.ts
โ โโโ release-escrow.dto.ts
โ
โโโ events/ # Event logging
โ โโโ events.service.ts
โ โโโ events.repository.ts
โ โโโ types/
โ โโโ event.types.ts
โ
โโโ stellar/ # Blockchain integration layer
โ โโโ stellar.module.ts
โ โโโ stellar.service.ts # Wrapper for @petad/stellar-sdk
โ โโโ transaction.monitor.ts # Polls blockchain confirmations
โ โโโ utils/
โ โโโ keypair.manager.ts
โ
โโโ jobs/ # Background workers
โ โโโ jobs.module.ts
โ โโโ processors/
โ โ โโโ blockchain-confirmation.processor.ts
โ โ โโโ notification.processor.ts
โ โโโ queues/
โ โโโ queue.config.ts
โ
โโโ documents/ # Document management
โ โโโ documents.service.ts
โ โโโ upload.service.ts
โ โโโ storage/
โ
โโโ notifications/ # Email & push notifications
โ โโโ notifications.service.ts
โ โโโ email.service.ts
โ โโโ templates/
โ
โโโ common/ # Shared utilities
โ โโโ decorators/
โ โโโ filters/
โ โ โโโ http-exception.filter.ts
โ โโโ guards/
โ โโโ interceptors/
โ โ โโโ logging.interceptor.ts
โ โโโ pipes/
โ โ โโโ validation.pipe.ts
โ โโโ utils/
โ
โโโ config/ # Configuration management
โ โโโ configuration.ts
โ โโโ database.config.ts
โ โโโ validation.schema.ts
โ
โโโ prisma/ # Database layer
โ โโโ schema.prisma
โ โโโ migrations/
โ โโโ seed.ts
โ
โโโ main.ts # Application entry point
โโโ app.module.ts # Root module
escrow/- Handles escrow operations via Stellar SDKstellar/- Abstraction layer wrapping@petad/stellar-sdkevents/- Event logging for audit trailjobs/- Background workers for async operations
The backend never exposes private keys to clients. All blockchain operations are server-signed.
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Adoption Escrow Workflow โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
1. Frontend: User submits adoption request
โ
POST /adoption/requests
2. Backend: Validates request
โ
Creates internal adoption record (status: PENDING)
3. Admin: Approves adoption
โ
PATCH /adoption/:id/approve
4. Backend: Orchestrates escrow creation
โ
calls escrowOrchestrator.createEscrow({
adopterPublicKey,
ownerPublicKey,
amount
})
โ
internally calls @petad/stellar-sdk
โ
Creates multisig escrow on Stellar
5. Blockchain: Escrow account created
โ
Transaction confirmed on Stellar network
6. Background Job: Monitors confirmation
โ
blockchain-confirmation.processor polls Horizon API
โ
Updates adoption status: ESCROW_FUNDED
7. Backend: Logs event
โ
events.create({
type: 'ESCROW_CREATED',
adoptionId,
transactionHash
})
8. Adoption Complete: Escrow released
โ
POST /adoption/:id/complete
โ
calls escrowOrchestrator.releaseEscrow()
โ
Funds transferred to shelter + platform
// escrow/escrow.orchestrator.ts
import { StellarSDK } from '@petad/stellar-sdk';
@Injectable()
export class EscrowOrchestrator {
constructor(
private readonly stellarSDK: StellarSDK,
private readonly eventsService: EventsService
) {}
async createEscrow(params: CreateEscrowParams): Promise<EscrowAccount> {
// 1. Create escrow via SDK
const escrow = await this.stellarSDK.escrow.createAccount({
adopterPublicKey: params.adopterKey,
ownerPublicKey: params.ownerKey,
depositAmount: params.amount,
metadata: {
adoptionId: params.adoptionId,
petId: params.petId
}
});
// 2. Store in database
const dbEscrow = await this.escrowRepository.create({
accountId: escrow.accountId,
transactionHash: escrow.transactionHash,
status: 'CREATED'
});
// 3. Log event
await this.eventsService.create({
type: 'ESCROW_CREATED',
aggregateId: params.adoptionId,
payload: {
escrowAccountId: escrow.accountId,
txHash: escrow.transactionHash
}
});
// 4. Schedule background confirmation job
await this.jobsQueue.add('monitor-confirmation', {
transactionHash: escrow.transactionHash,
escrowId: dbEscrow.id
});
return dbEscrow;
}
}Interactive API docs are available at:
http://localhost:3000/api
http://localhost:3000/api/v1
Protected endpoints require a JWT token in the Authorization header:
Authorization: Bearer <your-jwt-token>| Method | Endpoint | Description | Auth Required |
|---|---|---|---|
POST |
/auth/register |
Create new user account | โ |
POST |
/auth/login |
Login and receive JWT | โ |
POST |
/auth/logout |
Invalidate token | โ |
GET |
/auth/me |
Get current user profile | โ |
| Method | Endpoint | Description | Auth Required |
|---|---|---|---|
GET |
/pets |
List all available pets | โ |
GET |
/pets/:id |
Get pet details | โ |
POST |
/pets |
Create new pet listing | โ (Shelter/Admin) |
PATCH |
/pets/:id |
Update pet details | โ (Shelter/Admin) |
DELETE |
/pets/:id |
Remove pet listing | โ (Admin) |
| Method | Endpoint | Description | Auth Required |
|---|---|---|---|
POST |
/adoption/requests |
Submit adoption request | โ |
GET |
/adoption/requests |
List adoption requests | โ |
GET |
/adoption/requests/:id |
Get adoption details | โ |
PATCH |
/adoption/:id/approve |
Approve adoption (admin) | โ (Admin) |
POST |
/adoption/:id/complete |
Complete adoption | โ (Admin) |
| Method | Endpoint | Description | Auth Required |
|---|---|---|---|
POST |
/custody/create |
Create custody agreement | โ |
GET |
/custody |
List custody agreements | โ |
POST |
/custody/:id/complete |
Complete custody period | โ |
| Method | Endpoint | Description | Auth Required |
|---|---|---|---|
GET |
/escrow/:id |
Get escrow details | โ |
GET |
/escrow/:id/status |
Check blockchain status | โ |
# Login
curl -X POST http://localhost:3000/api/v1/auth/login -H "Content-Type: application/json" -d '{
"email": "[email protected]",
"password": "password123"
}'
# Response
{
"access_token": "eyJhbGciOiJIUzI1NiIs...",
"user": {
"id": "user-123",
"email": "[email protected]",
"role": "USER"
}
}
# Use token for authenticated requests
curl -X GET http://localhost:3000/api/v1/pets -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIs..."The docker-compose.yml includes all necessary infrastructure:
services:
postgres:
image: postgres:16-alpine
environment:
POSTGRES_DB: petad
POSTGRES_USER: petad
POSTGRES_PASSWORD: petad
ports:
- "5432:5432"
volumes:
- pgdata:/var/lib/postgresql/data
redis:
image: redis:7-alpine
ports:
- "6379:6379"
volumes:
- redisdata:/data
backend:
build: .
ports:
- "3000:3000"
env_file: .env
depends_on:
- postgres
- redis
volumes:
- ./src:/app/src
- ./uploads:/app/uploads
prisma-studio:
image: timothyjmiller/prisma-studio:latest
environment:
DATABASE_URL: postgresql://petad:petad@postgres:5432/petad
ports:
- "5555:5555"
depends_on:
- postgresdocker-compose up -ddocker-compose downdocker-compose logs -f backenddocker-compose up -d --build| Command | Description |
|---|---|
npm run start |
Start application |
npm run start:dev |
Development mode with hot reload |
npm run start:debug |
Debug mode with inspector |
npm run start:prod |
Production mode |
npm run build |
Build for production |
npm run test |
Run unit tests |
npm run test:watch |
Watch mode for tests |
npm run test:cov |
Generate coverage report |
npm run test:e2e |
End-to-end tests |
npm run lint |
Lint code with ESLint |
npm run format |
Format code with Prettier |
npm run prisma:migrate |
Run database migrations |
npm run prisma:generate |
Generate Prisma Client |
npm run prisma:studio |
Open Prisma Studio |
npm run seed |
Seed database with sample data |
- โ No Private Keys Exposed - All blockchain signing server-side
- โ JWT Authentication - Token-based auth with expiration
- โ RBAC - Role-based access control
- โ Input Validation - Request validation with class-validator
- โ SQL Injection Prevention - Prisma ORM with parameterized queries
- โ Rate Limiting - Prevents brute force attacks
- โ CORS Configuration - Whitelist allowed origins
- โ Helmet - Security headers
- โ Event Logging - Audit trail of operations
- Set
NODE_ENV=production - Use strong
JWT_SECRET(32+ characters) - Store
STELLAR_SECRET_KEYin secrets manager - Enable HTTPS
- Configure CORS for production domain
- Set up monitoring (Sentry, DataDog)
- Configure backup strategy for PostgreSQL
- Enable rate limiting
- Set up CI/CD pipeline
| Component | Service |
|---|---|
| Backend | AWS ECS / Google Cloud Run / Railway |
| Database | AWS RDS PostgreSQL / Supabase |
| Redis | AWS ElastiCache / Upstash |
| Monitoring | Sentry + DataDog |
Status: In Development
- โ User authentication & authorization
- โ Pet listings CRUD
- โ Basic adoption workflows
- โ Custody agreement creation
- โ Escrow orchestration via SDK
- โ Document upload
- โ Event logging
Target: Q2 2026
- ๐ Automated escrow settlement
- ๐ Enhanced status tracking
- ๐ Multi-party approval flows
- ๐ Dispute initiation system
- ๐ Notification system improvements
- ๐ File verification
Target: Q3-Q4 2026
-
๐ Event Sourcing Architecture
- Append-only event ledger
- Complete pet movement tracking
- Event replay capability
- Blockchain hash anchoring for events
-
๐ Trust & Reputation System
- Adopter trust history tracking
- Completed agreements counter
- Dispute records and resolution history
- Verifiable trust profiles
- Reputation scoring algorithm
- Trust badges and certifications
Target: 2027
- ๐ฎ Platform metrics dashboard
- ๐ฎ Adoption success rate analytics
- ๐ฎ Predictive insights
- ๐ฎ Shelter performance metrics
- ๐ฎ Geographic adoption patterns
We welcome community contributions!
See CONTRIBUTING.md for:
- Branch strategy
- Code style guidelines
- Pull request workflow
- Issue reporting
Looking to contribute? Check out issues labeled:
good first issue- Perfect for newcomershelp wanted- Community contributions neededdocumentation- Improve our docs
This project is licensed under the MIT License - see the LICENSE file for details.
- Built with โค๏ธ for transparent, trustworthy pet adoption
- Powered by Stellar blockchain technology
- Inspired by the mission to connect pets with loving homes
- Frontend: petad-frontend - React web application
- Stellar SDK: petad-chain - Blockchain SDK
Made with ๐พ by the PetAd Team
Building trust infrastructure for pet adoption, one API at a time.