A complete full-stack decentralized micro-lending platform combining blockchain technology, AI-powered risk assessment, and modern web technologies. Built for HackWithStack Hackathon by Team MicroLend.
MicroLend is a peer-to-peer lending platform that enables borrowers to request loans and lenders to fund them through Ethereum smart contracts. The platform features AI-driven risk assessment, explainable AI insights, user authentication, and a modern responsive interface.
- 💰 Loan Requests - Create loan requests with custom amount, interest rate, duration, and purpose
- 🤝 Loan Funding - Lenders can fund loans directly through smart contracts
- 💸 Loan Repayment - Automatic interest calculation and repayment tracking
- 📊 Risk Scoring - ML-powered risk assessment (0-100 scale)
- ⭐ Reputation System - On-chain reputation tracking for borrowers
- 🛡️ Security - ReentrancyGuard, Ownable pattern, comprehensive input validation
- 📢 Event Emissions - Complete transparency with blockchain events
- 💼 Escrow System - Secure fund holding in smart contract
- 🧠 Machine Learning Risk Assessment - LightGBM model for credit scoring
- 🔍 Explainable AI - SHAP (SHapley Additive exPlanations) for feature importance
- 🗣️ Natural Language Explanations - Gemini AI generates human-readable risk assessments
- 📊 Feature Importance - Shows which factors (income, age, employment) impact risk most
- 🎯 Auto Risk Calculation - Automatic risk score generation during borrower signup
- 💡 AI Insights - Lenders see detailed AI explanations for each loan opportunity
- 👤 User Registration - Secure signup with user type selection (borrower/lender)
- 🔑 JWT Authentication - Token-based authentication with 7-day expiration
- 📝 User Profiles - Editable profiles with financial information
- 🔒 Password Hashing - Secure password storage with Werkzeug
- 💾 MongoDB Storage - User data and financial profiles stored in MongoDB Atlas
- 🔄 Session Persistence - Remember me functionality with localStorage
- 📱 Responsive Design - Works seamlessly on desktop, tablet, and mobile
- 🎯 Role-Based Dashboards - Separate interfaces for borrowers and lenders
- 📊 Real-Time Stats - Live portfolio metrics and loan statistics
- 🔄 Auto-Refresh - Real-time updates from blockchain
- 🎨 Modern UI - Clean, intuitive interface with TailwindCSS
- ⚡ Fast Performance - Built with Vite for optimal speed
- 🌈 Color-Coded Status - Visual indicators for loan states and risk levels
- 📋 Two-Column Layout - Enhanced visibility for investments and opportunities (lender)
- 📑 Two-Column Grid - Organized loan cards for better overview (borrower)
The homepage welcomes users with a clean interface and easy access to sign up or log in.
Borrowers can view all their loans, track repayment status, and manage their loan requests.
Lenders can track their active investments, earnings, and portfolio performance in the left column.
The right column shows available loan opportunities with risk scores and potential earnings.
Explainable AI provides detailed risk analysis showing which factors impact the borrower's credit score.
Users can update their financial information, which is used for risk assessment calculations.
Borrowers can create new loan requests with custom terms including amount, interest rate, and duration.
Detailed view of loan information including terms, repayment schedule, and current status.
MetaMask Transaction Signing Issues: Initially struggled with ethers.js v6 breaking changes. The switch from signer.sendTransaction() to contract method calls required restructuring our Web3 provider initialization.
SHAP Integration with Flask: The SHAP LinearExplainer required specific numpy array formatting. We solved this by preprocessing user input to match the exact feature order and data types expected by our LightGBM model.
MongoDB Atlas Connection Timeouts: Intermittent connection drops during JWT authentication. Fixed by implementing connection pooling and proper error handling with automatic reconnection logic.
Smart Contract Gas Optimization: Our initial MicroLending contract exceeded gas limits for loan creation. We optimized by removing redundant storage operations and using events instead of storing detailed loan histories on-chain.
Cross-Origin CORS Conflicts: React frontend couldn't communicate with Flask backend during local development. Resolved by configuring Flask-CORS with specific origins and credential handling.
Gemini API Rate Limiting: Hit API limits when generating explanations for multiple loans. Implemented caching for risk explanations and graceful fallback to SHAP-only mode when API is unavailable.
Each challenge taught us valuable lessons about blockchain development, ML integration, and building production-ready full-stack applications.
- React 18 - Modern UI library
- Vite - Lightning-fast build tool
- TailwindCSS - Utility-first styling
- Ethers.js v6 - Ethereum interaction
- React Router - Client-side routing
- Lucide React - Beautiful icons
- Flask - Python web framework
- PyMongo - MongoDB driver
- Flask-CORS - Cross-origin support
- JWT - Token authentication
- Werkzeug - Password hashing
- LightGBM - Gradient boosting model
- SHAP - Explainable AI library
- Scikit-learn - Data preprocessing
- NumPy - Numerical computing
- Google Gemini AI - Natural language generation
- Hardhat 3.x - Development environment
- Solidity ^0.8.20 - Smart contract language
- OpenZeppelin - Security contracts
- Ethers.js - Blockchain interaction
- MongoDB Atlas - Cloud database
Before you begin, ensure you have the following installed:
- Node.js (v16 or higher) & npm
- Python 3.x (3.8 or higher)
- Git - Version control
- MetaMask - Browser extension for Ethereum wallet
- MongoDB Atlas Account - Free tier is sufficient
git clone https://github.com/aayushhh-operator/HackWithStack_LogicLooms.git
cd HackWithStack_LogicLooms-contractscd backend
pip install -r requirements.txtThe .env file should already exist in the backend/ folder with:
MONGODB_URI=your_mongodb_connection_string
SECRET_KEY=your_jwt_secret_key
GEMINI_API_KEY=your_gemini_api_key # Optional, for AI explanationsImportant:
- Replace
your_mongodb_connection_stringwith your MongoDB Atlas connection string - Change
your_jwt_secret_keyto a secure random string - Get Gemini API key from Google AI Studio (optional)
Ensure risk_model (1).pkl exists in the backend/ folder. This is the trained LightGBM model.
cd ../contracts
npm installnpx hardhat compilecd ../frontend
npm install- Install MetaMask browser extension if not already installed
- Create or import a wallet
- Add Hardhat Local Network:
- Open MetaMask → Settings → Networks → Add Network
- Network Name:
Hardhat Local - RPC URL:
http://127.0.0.1:8545 - Chain ID:
1337 - Currency Symbol:
ETH
You need to run 4 separate terminal windows simultaneously:
cd contracts
npx hardhat nodeWhat this does:
- Starts local Ethereum blockchain on port 8545
- Provides 20 test accounts with 10,000 ETH each
- Keep this running - don't close the terminal
Copy one of the private keys shown - you'll need it for MetaMask.
Wait for Terminal 1 to be fully running, then in a new terminal:
cd contracts
npx hardhat ignition deploy ignition/modules/MicroLending.js --network localhostWhat this does:
- Deploys MicroLending contract to local blockchain
- Shows contract address (save this)
- Creates
deploymentInfo.jsonwith contract details
Note: If you restart the Hardhat node (Terminal 1), you must re-deploy the contract.
cd backend
python app.pyWhat this does:
- Starts Flask server on port 5000
- Loads ML model and SHAP explainer
- Configures Gemini AI (if API key provided)
- Connects to MongoDB
You should see:
✓ ML Model loaded successfully
✓ SHAP Explainer configured
✓ Gemini AI configured (or warning if no API key)
* Running on http://127.0.0.1:5000
cd frontend
npm run devWhat this does:
- Starts Vite dev server on port 5173
- Enables hot module replacement
- Provides local and network URLs
You should see:
VITE v5.x.x ready in xxx ms
➜ Local: http://localhost:5173/
➜ Network: http://192.168.x.x:5173/
- Open MetaMask
- Click account icon → Import Account
- Paste a private key from Terminal 1 (Hardhat node output)
- Switch to Hardhat Local network
- Navigate to
http://localhost:5173 - Click "Get Started" or "Sign Up"
- Fill in registration form:
- Name, Email, Password, Phone
- Age (used for risk calculation)
- Annual Income (in USD)
- Employment Length (in years)
- Select user type: Borrower or Lender
- Click "Sign Up"
- Risk score is automatically calculated on signup
- Use your email and password
- Check "Remember me" to save email
- Click "Login"
- On Dashboard, click "Connect Wallet"
- MetaMask will pop up
- Select your imported account
- Click "Connect"
- Click "Request Loan" button
- Fill in loan details:
- Amount (in ETH, e.g., 0.5)
- Interest Rate (%, e.g., 10)
- Duration (days, e.g., 30)
- Purpose (optional description)
- Click "Submit Request"
- Confirm transaction in MetaMask
- Wait for transaction confirmation
- My Loans section shows all your loan requests
- Status indicators:
- 🟡 Pending - Waiting for lender
- 🟢 Funded - Money received, needs repayment
- ⚪ Repaid - Fully paid back
- Find a Funded loan
- Click "Repay Now"
- Confirm repayment amount (principal + interest)
- Approve transaction in MetaMask
- Available Opportunities section lists all pending loans
- Each opportunity shows:
- Loan amount and interest rate
- Borrower's risk score
- Expected return
- Duration and purpose
- Find a loan opportunity
- Click "View AI Risk Analysis"
- Review:
- AI Explanation - Natural language assessment
- Key Risk Factors - Top 3 factors with impacts
- Feature Importance - Which borrower attributes matter most
- Recommendation - AI-based investment suggestion
- Review loan details and AI insights
- Click "Fund Loan"
- Confirm amount in MetaMask
- Approve transaction
- Loan moves to your My Investments section
- My Investments (left column) shows funded loans
- Track progress bars
- View expected returns
- Monitor due dates
- Click "Profile" in navigation
- Update financial information:
- Age
- Annual Income
- Employment Length
- Changes affect risk score
- Click "Save Changes"
- 0-29: 🟢 Low Risk - Highly recommended
- 30-59: 🟡 Medium Risk - Moderate caution
- 60-100: 🔴 High Risk - Careful consideration needed
The ML model considers 7 key features:
- Age - Older borrowers typically lower risk
- Income - Higher income = better repayment capacity
- Employment Length - Longer employment = stability
- Loan Amount - Higher amounts = higher risk
- Interest Rate - Market signal of risk
- Percent of Income - Loan amount as % of income
- Credit History Length - Calculated as (Age - 18)
- SHAP Values show feature importance
- Positive impact (🟢) - Factor decreases risk
- Negative impact (🔴) - Factor increases risk
- Impact % - Relative importance of each factor
┌─────────────────────────────────────────────────────────┐
│ User (Browser) │
│ MetaMask + React Frontend │
└─────────────────────────────────────────────────────────┘
│
┌────────────────┼────────────────┐
│ │ │
▼ ▼ ▼
┌──────────────┐ ┌──────────────┐ ┌──────────────┐
│ Flask API │ │ Ethers.js │ │ Hardhat │
│ (Port 5000) │ │ Web3 │ │ Node │
│ │ │ Context │ │ (Port 8545) │
└──────────────┘ └──────────────┘ └──────────────┘
│ │
▼ ▼
┌──────────────┐ ┌──────────────┐
│ MongoDB │ │ MicroLending │
│ Atlas │ │ Smart │
│ (Users) │ │ Contract │
└──────────────┘ └──────────────┘
│
▼
┌──────────────┐
│ ML Model │
│ LightGBM │
│ + SHAP │
└──────────────┘
- User Authentication: Frontend → Flask API → MongoDB
- Loan Operations: Frontend → Ethers.js → MetaMask → Smart Contract
- Risk Assessment: Flask API → ML Model → SHAP → Gemini AI
- Real-time Updates: Smart Contract Events → Frontend Updates
MicroLend/
│
├── backend/ # Flask Backend
│ ├── app.py # Main Flask application
│ ├── requirements.txt # Python dependencies
│ ├── .env # Environment variables
│ └── risk_model (1).pkl # Trained ML model
│
├── contracts/ # Smart Contracts
│ ├── contracts/
│ │ ├── MicroLending.sol # Main lending contract
│ │ └── Counter.sol # Example contract
│ ├── ignition/
│ │ └── modules/
│ │ └── MicroLending.js # Deployment module
│ ├── test/
│ │ └── MicroLending.test.js # Contract tests
│ ├── hardhat.config.js # Hardhat configuration
│ ├── deploymentInfo.json # Deployed contract info
│ └── package.json # Node dependencies
│
├── frontend/ # React Frontend
│ ├── src/
│ │ ├── components/ # Reusable components
│ │ ├── contexts/
│ │ │ ├── AuthContext.jsx # Authentication state
│ │ │ └── Web3Context.jsx # Blockchain state
│ │ ├── hooks/
│ │ │ └── useLoan.jsx # Loan operations hook
│ │ ├── pages/
│ │ │ ├── LandingPage.jsx # Homepage
│ │ │ ├── Login.jsx # Login page
│ │ │ ├── Signup.jsx # Registration page
│ │ │ ├── Profile.jsx # User profile
│ │ │ ├── BorrowerDashboard.jsx # Borrower interface
│ │ │ └── LenderDashboard.jsx # Lender interface
│ │ ├── App.jsx # Main app component
│ │ └── index.css # Global styles
│ ├── package.json # Frontend dependencies
│ └── vite.config.js # Vite configuration
│
├── MDs/ # Documentation
│ ├── EXPLAINABLE_AI_COMPLETE.md # AI features guide
│ ├── LAYOUT_ENHANCEMENT.md # UI improvements
│ ├── METAMASK_GUIDE.md # Wallet setup
│ └── QUICK_REFERENCE.md # Quick commands
│
└── README.md # This file
cd contracts
npx hardhat testTests include:
- Loan request creation
- Loan funding
- Loan repayment
- Risk score calculation
- Access control
- Edge cases
- User registration (borrower & lender)
- Login with remember me
- Profile updates
- MetaMask connection
- Loan request creation
- Loan funding
- Loan repayment
- AI risk explanations
- Dashboard statistics
- Real-time updates
- Responsive design (mobile/tablet/desktop)
Problem: Can't connect wallet
Solutions:
- Ensure MetaMask is installed
- Check you're on Hardhat Local network (Chain ID 1337)
- Refresh page and try again
- Check browser console for errors
Problem: Transaction reverts or fails
Solutions:
- Ensure you have enough ETH for gas
- Check contract is deployed (Terminal 2 output)
- Verify you're on correct network
- Check account has sufficient balance
Problem: Flask server errors
Solutions:
- Check MongoDB connection string in
.env - Verify Python dependencies installed:
pip install -r requirements.txt - Check ML model file exists:
risk_model (1).pkl - Look for port conflicts (port 5000)
Problem: Vite dev server errors
Solutions:
- Delete
node_modulesand reinstall:npm install - Clear Vite cache:
rm -rf node_modules/.vite - Check port 5173 is available
- Verify all dependencies installed
Problem: Risk analysis shows error
Solutions:
- Add Gemini API key to
backend/.env - SHAP still works without Gemini (shows feature importance only)
- Check backend logs for specific errors
- Verify ML model loaded successfully
Problem: "Contract not deployed" error
Solutions:
- Restart Hardhat node (Terminal 1)
- Re-deploy contract (Terminal 2)
- Check
deploymentInfo.jsonexists - Verify contract address in logs
- EXPLAINABLE_AI_COMPLETE.md - Complete AI features guide
- EXPLAINABLE_AI_SUMMARY.md - Quick AI overview
- LAYOUT_ENHANCEMENT.md - UI/UX improvements
- METAMASK_GUIDE.md - Detailed wallet setup
// Request a new loan
requestLoan(uint256 amount, uint256 interestRate, uint256 duration, string purpose)
// Fund an existing loan
fundLoan(uint256 loanId) payable
// Repay a funded loan
repayLoan(uint256 loanId) payable
// Get loan details
getLoan(uint256 loanId) returns (Loan)
// Calculate risk score
calculateRiskScore(address borrower, uint256 amount) returns (uint256)
// Get total number of loans
getTotalLoans() returns (uint256)
// Get all loans for a borrower
getBorrowerLoans(address borrower) returns (uint256[])
// Get all loans for a lender
getLenderLoans(address lender) returns (uint256[])- 0 = Requested - Loan created, waiting for lender
- 1 = Funded - Loan funded, awaiting repayment
- 2 = Repaid - Loan fully repaid
- 3 = Defaulted - Loan not repaid (future feature)
- ✅ ReentrancyGuard - Prevents reentrancy attacks on payable functions
- ✅ Ownable - Admin-only functions protected
- ✅ Input Validation - All inputs validated before processing
- ✅ Safe Math - Overflow protection (Solidity 0.8+)
- ✅ Access Control - Only borrower can repay, only lenders can fund
- ✅ Event Emissions - Full audit trail on blockchain
- ✅ Password Hashing - Werkzeug secure password hashing
- ✅ JWT Authentication - Token-based auth with expiration
- ✅ CORS Protection - Configured for frontend origin only
- ✅ Input Sanitization - MongoDB injection prevention
⚠️ Never share private keys⚠️ Don't commit.envfiles⚠️ Test thoroughly before mainnet⚠️ Audit smart contracts professionally⚠️ Use hardware wallets for production
- Build production bundle:
npm run build - Deploy
dist/folder - Update environment variables for production backend URL
- Ensure
requirements.txtis up-to-date - Configure environment variables
- Deploy Flask app
- Update CORS origins for production frontend
- Get Sepolia ETH from faucet
- Update
hardhat.config.jswith Sepolia RPC - Set
SEPOLIA_PRIVATE_KEYenvironment variable - Deploy:
npx hardhat ignition deploy --network sepolia ignition/modules/MicroLending.js
- User authentication & profiles
- Loan creation, funding, repayment
- ML-powered risk assessment
- Explainable AI with SHAP
- Gemini AI natural language explanations
- Real-time blockchain integration
- Responsive UI with modern design
- MetaMask integration
- Collateral-based loans
- Loan insurance pool
- Default handling & recovery
- Multi-currency support
- Mobile app (React Native)
- Loan marketplace & secondary market
- Credit score improvement tracking
- Automated loan matching
- Governance token
- Staking rewards for lenders
MIT License - See LICENSE file for details
Built for HackWithStack Hackathon 2025
@aayushhh-operator |
@ArshvirSk |
@AgentR04 |
@Aagnya-Mistry |
@kabir-999 |
⭐ Star this repository if you find it helpful!
🐛 Report issues: GitHub Issues
📧 Contact: arshvirsk26@gmail.com
Last Updated: November 21, 2025







