Analytics & Purchase Tracking Implementation Summary
Comprehensive analytics system added to the RWA Marketplace backend for tracking marketplace activity, user engagement, and asset performance.
backend/src/services/transactionService.js (337 lines)
Core service for recording and querying purchase transactions
Methods for user activity tracking, volume metrics, daily analytics
Factory function: createTransactionService(db, logger)
backend/src/routes/analytics.js (461 lines)
Public analytics endpoints (no auth required)
Admin dashboard endpoints (require API key)
11 public endpoints + 3 admin endpoints
Factory function: createAnalyticsRoutes(transactionService, logger, adminAuth)
backend/src/routes/purchases.js (219 lines)
Endpoints for recording purchase events from blockchain
Purchase history queries
Factory function: createPurchaseRoutes(transactionService, logger)
backend/migrations/20260630000000_create_transactions_table.js (73 lines)
Knex migration creating 3 new tables:
transactions — Records every share purchase
user_activity — Aggregated user statistics
daily_analytics — Pre-computed daily metrics
Includes indexes for query optimization
backend/docs/ANALYTICS_API.md (545 lines)
Complete API reference for all analytics endpoints
Request/response examples for each endpoint
Frontend integration examples
Database schema documentation
Error handling and caching strategies
docs/ANALYTICS_FEATURE.md (399 lines)
Feature overview and setup instructions
Backend implementation details
Frontend integration guide
Admin dashboard guide
Performance considerations
Troubleshooting and future enhancements
backend/src/app.js
Added imports for new services
Updated initializeApp() to initialize TransactionService
Mounted analytics and purchases routes
Error handling for uninitialized services
Public Endpoints (No Auth Required)
Endpoint
Method
Purpose
/api/analytics/overview
GET
Marketplace totals and key metrics
/api/analytics/volume
GET
Trading volume by time period
/api/analytics/popular
GET
Top assets by volume
/api/analytics/active-users
GET
Active user counts
/api/analytics/top-buyers
GET
Buyers ranked by spending
/api/analytics/purchase-trends
GET
Volume trends over time
/api/analytics/asset-performance/:contractId
GET
Asset-specific metrics
/api/analytics/user/:address
GET
User portfolio and history
Purchase Recording Endpoints
Endpoint
Method
Purpose
/api/purchases
POST
Record a blockchain purchase
/api/purchases/:transactionId
GET
Get purchase details
/api/purchases/contract/:contractId
GET
Get asset purchase history
Admin Endpoints (API Key Required)
Endpoint
Method
Purpose
/api/analytics/dashboard
GET
Full admin dashboard
/api/analytics/compute-daily
POST
Compute daily snapshot
/api/analytics/daily
GET
Daily metrics time series
id — AUTO_INCREMENT PRIMARY KEY
transaction_id — UNIQUE identifier
contract_id — RWA contract being purchased
buyer_address — Stellar wallet address
shares_purchased — Number of shares bought
price_per_share — Price per share
total_amount — Total USD/token value
payment_token — Token used for payment
status — 'completed', 'pending', or 'failed'
blockchain_hash — Soroban transaction hash
metadata — JSONB additional data
created_at, updated_at — Timestamps
Indexes: contract_id, buyer_address, created_at, status
id — AUTO_INCREMENT PRIMARY KEY
wallet_address — UNIQUE Stellar wallet
total_purchases — Number of purchases
total_spent — Total USD spent
shares_owned — Total shares owned
last_purchase_at — Most recent purchase
first_seen_at — First activity timestamp
created_at, updated_at — Timestamps
Index: total_purchases, last_purchase_at, created_at
id — AUTO_INCREMENT PRIMARY KEY
date — UNIQUE YYYY-MM-DD
transactions_count — Transactions that day
total_volume — Total USD volume
unique_buyers — Number of unique buyers
unique_assets_traded — Assets with purchases
average_transaction_size — Avg transaction value
metadata — JSONB (top assets, breakdowns)
created_at, updated_at — Timestamps
Index: date, created_at
Records every blockchain transaction
Links purchase to buyer wallet address
Stores blockchain hash for verification
Tracks purchase metadata (timestamp, user agent)
Aggregates user statistics automatically
Tracks total purchases, spending, shares owned
Records first and last purchase timestamps
Updated on every purchase transaction
Overview: Total volume, transactions, users, assets
Volume: By time period, asset type, location
Popular Assets: Ranked by volume and recency
User Metrics: Active users, top buyers, engagement
Trends: Daily purchase volume, unique buyers
Asset Performance: Transactions, volume, buyers per asset
User Portfolio: Purchase history and holdings
Real-time overview of all metrics
Daily snapshots for historical analysis
Top buyers and trending assets
Time-series data for charts
Performance Optimizations
5-minute caching for public endpoints
Database indexes on query columns
Pre-computed daily snapshots
Running totals in user_activity table
// In src/app.js during initializeApp()
const transactionService = createTransactionService ( db , logger ) ;
const analyticsRoutes = createAnalyticsRoutes ( transactionService , logger , adminAuth ) ;
const purchasesRoutes = createPurchaseRoutes ( transactionService , logger ) ;
app . use ( '/api/analytics' , analyticsRoutes ) ;
app . use ( '/api/purchases' , purchasesRoutes ) ;
// After blockchain transaction succeeds
await fetch ( '/api/purchases' , {
method : 'POST' ,
headers : { 'Content-Type' : 'application/json' } ,
body : JSON . stringify ( {
contractId,
buyerAddress,
sharesPurchased : shares ,
pricePerShare : price ,
totalAmount : shares * price ,
paymentToken,
blockchainHash : txHash ,
} ) ,
} ) ;
// Display analytics
const overview = await fetch ( '/api/analytics/overview' ) . then ( r => r . json ( ) ) ;
const portfolio = await fetch ( `/api/analytics/user/${ address } ` ) . then ( r => r . json ( ) ) ;
const trends = await fetch ( '/api/analytics/purchase-trends?days=30' ) . then ( r => r . json ( ) ) ;
cd backend
npm run migrate
# Overview metrics
curl http://localhost:3001/api/analytics/overview
# Record a purchase
curl -X POST http://localhost:3001/api/purchases \
-H " Content-Type: application/json" \
-d ' {
"contractId": "CBKJ5G3X...",
"buyerAddress": "GXYZ...",
"sharesPurchased": 500,
"pricePerShare": 1000,
"totalAmount": 500000,
"paymentToken": "CDLZFC3S..."
}'
# User portfolio
curl http://localhost:3001/api/analytics/user/GXYZ...
# Asset performance
curl http://localhost:3001/api/analytics/asset-performance/CBKJ5G3X...
# Admin dashboard (requires API key)
curl -H " x-api-key: YOUR_API_KEY" \
http://localhost:3001/api/analytics/dashboard
Full API Reference: backend/docs/ANALYTICS_API.md
Feature Overview: docs/ANALYTICS_FEATURE.md
Integration Examples: Both docs include frontend examples
Run migrations: npm run migrate
Test endpoints with curl (see Testing section)
Integrate purchase recording in frontend after blockchain transactions
Add analytics displays to dashboard UI
Set up cron job to compute daily analytics (optional)
For detailed endpoint documentation, request/response examples, and frontend integration patterns, see:
backend/docs/ANALYTICS_API.md — Complete endpoint reference
docs/ANALYTICS_FEATURE.md — Implementation guide and troubleshooting