demo vedio https://youtu.be/J_yn2BMaE7Y?si=C_OL2IkoHeXP_Yrw
Visit the live demo to experience the platform in action!
- Overview
- Live Demo
- Features
- Tech Stack
- Folder Structure
- Installation & Setup
- Configuration
- Running the Application
- Project Architecture
- API Endpoints
- Smart Contract
- Machine Learning Models
- Contributing
- License
SettleTrack is a comprehensive blockchain-enabled trade settlement platform that combines cutting-edge technologies to revolutionize post-trade processing. The platform leverages:
- Ethereum Smart Contracts for immutable, transparent trade recording
- Machine Learning for intelligent risk assessment and anomaly detection
- Modern Web Technologies for intuitive user experience
- RESTful API for seamless integration with third-party systems
SettleTrack enables financial institutions and trading platforms to automate trade settlements with enhanced security, reduced counterparty risk, and real-time monitoring capabilities.
- Immutable recording of trade settlements using Ethereum smart contracts
- Transparent audit trail for regulatory compliance
- Decentralized trade status tracking
- Support for pending and settled trade states
- Event-driven architecture for real-time notifications
- AI-powered risk assessment for trade validation
- Anomaly detection to identify suspicious trading patterns
- Trade delay prediction and risk scoring
- Feature engineering for financial data
- Decision engine for automated trade approval/rejection
- Intuitive Next.js frontend for trade management
- Real-time risk monitoring and status updates
- Trade form for new trade submissions
- Risk visualization components
- Settlement tracking interface
- Responsive design with Tailwind CSS
- Node.js/Express backend for integration
- Blockchain service integration
- ML model inference endpoints
- Health check and status monitoring
- Cross-origin resource sharing (CORS) enabled
- Live status updates for trade settlements
- Risk score visualization
- Settlement execution tracking
- System health monitoring
| Technology | Version | Purpose |
|---|---|---|
| Next.js | 16.1.1 | React framework for production-ready applications |
| React | 19.2.3 | UI component library |
| React DOM | 19.2.3 | React rendering engine |
| Tailwind CSS | 4.1.18 | Utility-first CSS framework |
| PostCSS | 8.5.6 | CSS transformation tool |
| ESLint | 9 | Code quality and linting |
| Technology | Version | Purpose |
|---|---|---|
| Node.js | Latest | JavaScript runtime |
| Express.js | 5.2.1 | Web application framework |
| Ethers.js | 6.16.0 | Ethereum blockchain interaction |
| Axios | 1.13.2 | HTTP client for API calls |
| CORS | 2.8.5 | Cross-origin resource sharing middleware |
| dotenv | 17.2.3 | Environment variable management |
| Nodemon | 3.1.11 | Auto-reload during development |
| Technology | Details |
|---|---|
| Language | Solidity ^0.8.0 |
| Network | Ethereum (compatible with mainnet/testnets/L2s) |
| Smart Contract | TradeSettlement.sol - Immutable post-trade settlement recorder |
| ABI | Generated from compiled contract |
| Development | Remix IDE support for testing |
| Technology | Version | Purpose |
|---|---|---|
| Python | 3.x | Programming language |
| FastAPI | Latest | Modern async web framework |
| Uvicorn | Latest | ASGI server |
| Pandas | Latest | Data manipulation and analysis |
| NumPy | Latest | Numerical computing |
| Scikit-learn | Latest | Machine learning library |
| Pickle | Built-in | Model serialization |
SettleTrack/
├── backend/ # Node.js Backend Application
│ ├── package.json # Backend dependencies and npm scripts
│ ├── src/
│ │ ├── index.js # Express app initialization
│ │ ├── config/
│ │ │ └── blockchain.config.js # Blockchain network configuration
│ │ ├── routes/
│ │ │ └── settlement.routes.js # API route handlers
│ │ ├── services/
│ │ │ ├── blockchain.service.js # Smart contract interaction
│ │ │ └── ml.service.js # ML model integration
│ │ └── abi/
│ │ └── TradeSettlement.json # Smart contract ABI
│
├── frontend/ # Next.js Frontend Application
│ ├── package.json # Frontend dependencies
│ ├── next.config.mjs # Next.js configuration
│ ├── tailwind.config.js # Tailwind CSS setup
│ ├── postcss.config.mjs # PostCSS configuration
│ ├── jsconfig.json # JavaScript path aliases
│ ├── eslint.config.mjs # ESLint rules
│ ├── app/
│ │ ├── layout.js # Root layout component
│ │ ├── page.js # Home page
│ │ ├── globals.css # Global styles
│ │ ├── risk/
│ │ │ └── page.js # Risk assessment page
│ │ └── settle/
│ │ └── page.js # Settlement management page
│ ├── components/
│ │ ├── Navbar.js # Navigation component
│ │ ├── StatusCard.js # Trade status display
│ │ └── TradeForm.js # Trade submission form
│ ├── lib/
│ │ ├── api.js # API client utilities
│ │ └── utils.js # Helper functions
│ └── public/ # Static assets
│
├── blockchain/ # Ethereum Smart Contracts
│ ├── contracts/
│ │ └── TradeSettlement.sol # Main settlement smart contract
│ ├── abi/
│ │ └── TradeSettlement.json # Contract ABI for integration
│ └── deployment/
│ └── deployed-address.txt # Deployed contract addresses
│
├── ml/ # Machine Learning Pipeline
│ ├── api.py # FastAPI server for ML predictions
│ ├── requirements.txt # Python dependencies
│ ├── data/
│ │ └── sample_track.csv # Sample training data
│ ├── model/ # Pre-trained model storage
│ ├── training/
│ │ ├── train_anomaly_model.py # Anomaly detection model training
│ │ ├── train_risk_model.py # Risk assessment model training
│ │ └── __pycache__/
│ └── utils/
│ ├── feature_builder.py # Feature engineering utilities
│ ├── decision_engine.py # Trade approval decision logic
│ ├── preprocess.py # Data preprocessing
│ └── __pycache__/
│
└── README.md # Project documentation
Before running the application, ensure you have the following installed:
- Node.js (v18.17 or higher) - Download
- Python (v3.8 or higher) - Download
- npm (comes with Node.js)
- pip (Python package installer)
- Git - Download
- Ethereum Wallet (MetaMask or compatible) for blockchain interactions
- Web3 Provider (Infura, Alchemy, or local node for Ethereum network access)
git clone <repository-url>
cd SettleTrackNavigate to the backend directory and install dependencies:
cd backend
npm installCreate a .env file in the backend directory:
# Environment
NODE_ENV=development
PORT=5000
# Blockchain Configuration
BLOCKCHAIN_NETWORK=sepolia # or mainnet, goerli, etc.
BLOCKCHAIN_RPC_URL=https://sepolia.infura.io/v3/YOUR_INFURA_PROJECT_ID
CONTRACT_ADDRESS=0x... # Your deployed TradeSettlement contract address
CONTRACT_ABI_PATH=./src/abi/TradeSettlement.json
# ML Service Configuration
ML_SERVICE_URL=http://localhost:8000
ML_API_TIMEOUT=30000
# CORS Configuration
ALLOWED_ORIGINS=http://localhost:3000,https://yourdomain.comcd ../frontend
npm installCreate a .env.local file in the frontend directory:
NEXT_PUBLIC_API_BASE_URL=http://localhost:5000/api
NEXT_PUBLIC_BLOCKCHAIN_NETWORK=sepoliacd ../ml
python -m venv venv
# On Windows
venv\Scripts\activate
# On macOS/Linux
source venv/bin/activate
pip install -r requirements.txtCreate a .env file in the ml directory:
FASTAPI_ENV=development
PORT=8000
WORKERS=4
# Model Configuration
MODEL_PATH=./model
ANOMALY_MODEL=anomaly_model.pkl
RISK_MODEL=risk_model.pklEdit backend/src/config/blockchain.config.js:
export const blockchainConfig = {
network: process.env.BLOCKCHAIN_NETWORK || 'sepolia',
rpcUrl: process.env.BLOCKCHAIN_RPC_URL,
contractAddress: process.env.CONTRACT_ADDRESS,
contractABI: require('../abi/TradeSettlement.json'),
chainId: {
'mainnet': 1,
'sepolia': 11155111,
'goerli': 5,
'localhost': 31337
}
};- Copy the contract from
blockchain/contracts/TradeSettlement.sol - Deploy using Remix IDE or Hardhat:
- Go to Remix IDE
- Create new file and paste contract code
- Compile with Solidity 0.8.0+
- Deploy to your target network
- Copy deployed contract address to
CONTRACT_ADDRESSin.env
Open three terminal windows and run each service:
Terminal 1 - Backend (Node.js/Express)
cd backend
npm run dev
# Server runs on http://localhost:5000Terminal 2 - Frontend (Next.js)
cd frontend
npm run dev
# Application runs on http://localhost:3000Terminal 3 - ML Service (FastAPI)
cd ml
python -m uvicorn api:app --reload --port 8000
# API runs on http://localhost:8000Backend:
cd backend
npm run build # If applicable
npm startFrontend:
cd frontend
npm run build
npm startML Service:
cd ml
python -m uvicorn api:app --workers 4 --port 8000┌─────────────────────────────────────────────────────────────┐
│ USER INTERFACE │
│ (Next.js Frontend - Port 3000) │
│ ┌──────────────┬────────────────┬──────────────────────┐ │
│ │ Home Page │ Risk Page │ Settlement Page │ │
│ │ Dashboard │ Monitoring │ Trade Management │ │
│ └──────────────┴────────────────┴──────────────────────┘ │
└──────────────────────┬──────────────────────────────────────┘
│ HTTP/REST (Axios)
▼
┌────────────────────────────────────────────────────────────┐
│ BACKEND API LAYER │
│ (Express.js - Port 5000) │
│ ┌──────────────┬────────────────┬──────────────────────┐ │
│ │ Settlement │ Risk Check │ Trade Status │ │
│ │ Routes │ Endpoint │ Endpoint │ │
│ └──────────────┴────────────────┴──────────────────────┘ │
└──────┬──────────────────────────────────────┬──────────────┘
│ │
├─── Web3/Ethers.js ──────────┐ │
│ │ │
▼ ▼ ▼
┌────────────────┐ ┌──────────────────────┐
│ Blockchain │ │ ML Service │
│ (Ethereum) │ │ (FastAPI - 8000) │
│ │ │ │
│ TradeSettlement│ │ Risk Prediction │
│ Smart Contract │ │ Anomaly Detection │
└────────────────┘ └──────────────────────┘
-
Trade Submission
- User submits trade via frontend form
- Frontend sends to backend API
- Backend initiates risk check with ML service
-
Risk Assessment
- ML service analyzes trade features
- Returns risk score and anomaly status
- Decision engine approves/rejects trade
-
Blockchain Recording
- Approved trades sent to smart contract
- Smart contract records trade immutably
- Event emitted for logging
-
Settlement
- Frontend queries trade status
- Settlement status updated on blockchain
- User notified of completion
GET /api/settlement/healthResponse:
{
"status": "ok",
"backend": "running",
"blockchain": {
"connected": true,
"network": "sepolia"
}
}POST /api/settlement/risk
Content-Type: application/json
{
"trade_id": "TRADE123",
"trade_amount": 1000000,
"volatility": 0.15,
"past_delays": 2
}Response:
{
"trade_id": "TRADE123",
"risk_score": 0.35,
"delay_prediction": 2,
"is_anomaly": false,
"recommendation": "APPROVE",
"confidence": 0.92
}GET /api/settlement/tradesResponse:
{
"trades": [],
"message": "Trade history endpoint",
"blockchain": {
"connected": true,
"network": "sepolia"
}
}POST /api/settlement/record
Content-Type: application/json
{
"tradeId": 1,
"buyer": "0x123...",
"seller": "0x456...",
"quantity": 100,
"price": 1000
}POST /api/settlement/settle
Content-Type: application/json
{
"tradeId": 1
}GET /api/settlement/status/:tradeIdResponse:
{
"tradeId": 1,
"status": "Settled",
"timestamp": 1705449600
}Location: blockchain/contracts/TradeSettlement.sol
recordTrade()
- Records a new trade on the blockchain
- Requires: Trade ID not already recorded
- Emits: TradeRecorded event
settleTrade()
- Marks a trade as settled
- Requires: Trade exists and is pending
- Emits: TradeSettled event
getTradeStatus()
- Returns current status of a trade
- Returns: Status enum (Pending/Settled)
struct Trade {
uint256 tradeId; // Unique trade identifier
address buyer; // Buyer address
address seller; // Seller address
uint256 quantity; // Trade quantity
uint256 price; // Trade price per unit
Status status; // Current status (Pending/Settled)
uint256 timestamp; // Block timestamp of recording
}event TradeRecorded(uint256 tradeId, uint256 timestamp);
event TradeSettled(uint256 tradeId, uint256 timestamp);Location: ml/training/train_anomaly_model.py
- Algorithm: Isolation Forest
- Input Features: Trade amount, volatility, past delays, frequency
- Output: Anomaly flag (-1 = anomaly, 1 = normal)
- Use Case: Detect unusual trading patterns
Location: ml/training/train_risk_model.py
- Algorithm: Gradient Boosting/Random Forest
- Input Features: Trade characteristics and historical data
- Output: Risk score (0-1) and delay prediction
- Use Case: Predict settlement delays and risk levels
Location: ml/utils/feature_builder.py
Extracts and engineered features from raw trade data:
- Trade amount normalization
- Volatility metrics
- Historical delay patterns
- Counterparty risk indicators
- Market conditions
Location: ml/utils/decision_engine.py
Business logic for trade approval:
- Threshold-based risk evaluation
- Anomaly weight consideration
- Approval/rejection/review recommendations
- Confidence scoring
- Navigation menu across pages
- Link to home, risk monitoring, settlement
- Status indicator
- Input fields for trade details
- Form validation
- API submission handling
- Error and success messaging
- Displays trade status
- Risk score visualization
- Settlement progress
- Action buttons
- recordTrade() // Record trade on smart contract
- settleTrade() // Mark trade as settled
- getTradeStatus() // Query trade status
- getBlockchainStatus() // Check connection status- checkRisk() // Call ML API for risk assessment
- parseResponse() // Process ML model outputs
- handleError() // Error handling for ML failuresBackend:
# Add remote repository
git remote add heroku <heroku-git-url>
# Deploy
git push heroku mainFrontend:
# Deploy to Vercel (recommended for Next.js)
npm i -g vercel
vercel --prodML Service:
# Create requirements.txt
pip freeze > requirements.txt
# Deploy using Docker or platform-specific methodUpdate .env files with production values:
- Production RPC URLs (Infura, Alchemy)
- Real contract addresses
- Production domain URLs
- SSL certificates enabled
-
Trade Recording:
- Submit form on frontend
- Verify trade appears in blockchain
- Check status endpoint
-
Risk Assessment:
- Submit trade with various characteristics
- Verify ML predictions are reasonable
- Check anomaly detection
-
Settlement:
- Record trade
- Mark as settled
- Verify status updates
# Backend tests
cd backend
npm test
# Frontend tests
cd frontend
npm test
# ML tests
cd ml
pytest tests/Backend can't connect to blockchain:
- Check RPC URL is correct
- Verify network is accessible
- Check contract address is deployed on that network
ML service returning errors:
- Verify models are trained and saved
- Check FastAPI server is running
- Verify input data format matches expected schema
Frontend not connecting to API:
- Check backend is running on correct port
- Verify CORS configuration
- Check API_BASE_URL in frontend env
Smart contract errors:
- Ensure contract address is correct
- Verify contract is deployed
- Check ABI matches deployed contract
- Database integration for trade history
- User authentication and authorization
- Advanced analytics dashboard
- WebSocket support for real-time updates
- Multi-chain support (Polygon, Arbitrum)
- Advanced ML models with deep learning
- Mobile app development
- Integration with external data providers
- Compliance and reporting features
- Automated market maker (AMM) integration
Contributions are welcome! Please follow these steps:
- Fork the repository
- Create a feature branch (
git checkout -b feature/AmazingFeature) - Commit changes (
git commit -m 'Add AmazingFeature') - Push to branch (
git push origin feature/AmazingFeature) - Open a Pull Request
This project is licensed under the MIT License. See LICENSE file for details.
For issues, questions, or suggestions, please:
- Open an issue on GitHub
- Contact the development team
- Check existing documentation
- Ethereum Foundation for smart contract standards
- OpenZeppelin for contract security patterns
- Scikit-learn for ML algorithms
- Next.js team for the amazing framework
PORT=5000
GANACHE_RPC=http://127.0.0.1:7545
PRIVATE_KEY=<your-private-key>
CONTRACT_ADDRESS=0xd9145CCE52D386f254917e481eB44e9943F39138
ML_SERVICE_URL=http://localhost:8000/api/predictcd ../frontend
npm installcd ../ml
pip install -r requirements.txtThe smart contract is already deployed on Remix VM for testing. For production deployment:
- Open Remix IDE
- Load
blockchain/contracts/TradeSettlement.sol - Compile and deploy to your preferred network
- Update the contract address in backend configuration
cd ml
python api.pyThe ML API will be available at http://localhost:8000
cd backend
npm startFor development with auto-reload:
npm run devThe backend API will be available at http://localhost:5000
cd frontend
npm run devThe web application will be available at http://localhost:3000
- Access the Web Interface: Open
http://localhost:3000in your browser - Navigate to Trade Settlement: Use the "Settle" page to initiate new trades
- Risk Assessment: Visit the "Risk" page to view ML-powered risk analysis
- Monitor Status: Check settlement status through the dashboard components
GET /api/settlement/health- Health check endpointGET /api/settlement/trades- Retrieve trade recordsPOST /api/settlement/trade- Create new trade settlement
POST /api/predict- Predict trade risk and anomaly detection
# Backend tests
cd backend
npm test
# Frontend linting
cd frontend
npm run lint# Frontend build
cd frontend
npm run build
npm start- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
For support and questions, please open an issue in the GitHub repository.