A high-performance API built with Bun and TypeScript for processing crypto-to-UPI payments using Cardano blockchain technology.
- Crypto-to-UPI Payments: Convert ADA, USDC, USDT to INR via UPI
- Smart Contract Integration: Plutus smart contracts for secure escrow
- Liquidity Pool Management: Dynamic exchange rates and pool balancing
- Credit Scoring: Web3 credit scoring with Midnight privacy layer
- Real-time Processing: Fast transaction processing with background tasks
- Comprehensive API: RESTful endpoints with OpenAPI documentation
The system follows the sequence diagram provided, implementing:
- Payment Initiation: User scans UPI QR, app calculates crypto amount
- Crypto Locking: User locks crypto in Plutus smart contract
- UPI Processing: System processes UPI payment to merchant
- Settlement: Crypto released to liquidity pool, transaction completed
- Credit Scoring: Background credit score update using AI and Midnight
The API follows a clean, layered architecture pattern:
src/
โโโ controllers/ # Request/Response handling
โ โโโ transaction.controller.ts
โ โโโ webhook.controller.ts
โ โโโ health.controller.ts
โโโ services/ # Business logic layer
โ โโโ transaction-orchestrator.service.ts
โ โโโ smart-contract.service.ts
โ โโโ liquidity-pool.service.ts
โ โโโ upi-gateway.service.ts
โ โโโ credit-score.service.ts
โโโ repositories/ # Data access layer
โ โโโ transaction.repository.ts
โโโ routes/ # API route definitions
โ โโโ transaction.routes.ts
โ โโโ webhook.routes.ts
โ โโโ health.routes.ts
โ โโโ stats.routes.ts
โโโ models/ # TypeScript interfaces
โ โโโ transaction.ts
โโโ types/ # Enums and type definitions
โ โโโ enums.ts
โโโ utils/ # Utility functions
โ โโโ validation.ts
โ โโโ error-handler.ts
โโโ index.ts # Main application entry point
Layer Responsibilities:
- Controllers: Handle HTTP requests/responses, input validation, error handling
- Services: Implement business logic, coordinate between different systems
- Repositories: Manage data persistence and retrieval
- Routes: Define API endpoints and request/response schemas
- Models: TypeScript interfaces for data structures
- Utils: Shared utilities for validation, error handling, etc.
- Bun runtime (v1.0+)
- Node.js 18+ (for compatibility)
- PostgreSQL 14+ (for production)
- Cardano node access (Blockfrost/Koios)
-
Clone the repository
git clone <repository-url> cd crypto-to-inr-api
-
Install dependencies
bun install
-
Set up environment variables
cp env.example .env # Edit .env with your configuration -
Test the controller architecture
bun run test-controllers.ts
-
Run the development server
bun run dev
Copy env.example to .env and configure:
- Server: PORT, NODE_ENV
- Database: PostgreSQL connection details
- Blockchain: Cardano network, Blockfrost API key
- UPI Gateway: Banking partner API credentials
- Services: AI engine, Midnight network APIs
For production, set up PostgreSQL with the schema:
-- See the schema in the LLD comments
-- Tables: transactions, liquidity_pool, exchange_ratesStart the server and visit:
- Swagger UI:
http://localhost:3000/swagger - Health Check:
http://localhost:3000/health
POST /api/v1/transactions/initiate
Content-Type: application/json
{
"user_wallet_address": "addr1...",
"merchant_upi_id": "merchant@paytm",
"amount_inr": 1000.00,
"crypto_asset": "ADA"
}POST /api/v1/transactions/lock
Content-Type: application/json
{
"transaction_id": "uuid",
"cardano_tx_hash": "64-char-hex",
"signed_by_wallet": "addr1..."
}GET /api/v1/transactions/{id}-
Initiation
- Validate request parameters
- Check liquidity pool availability
- Calculate crypto amount + fees
- Generate smart contract address
- Return payment details
-
Crypto Lock
- Verify blockchain transaction
- Update transaction status
- Trigger UPI payment (background)
-
UPI Processing (Background)
- Reserve INR from pool
- Initiate UPI payment
- Handle success/failure
- Release crypto to pool or refund
-
Completion
- Update transaction status
- Trigger credit score update
- Send notifications
# Run tests
bun test
# Test specific endpoint
curl -X POST http://localhost:3000/api/v1/transactions/initiate \
-H "Content-Type: application/json" \
-d '{
"user_wallet_address": "addr1test123...",
"merchant_upi_id": "test@paytm",
"amount_inr": 100,
"crypto_asset": "ADA"
}'- Input validation and sanitization
- Rate limiting (100 requests/minute)
- CORS configuration
- Environment-based secrets
- Error handling without data leakage
- Health check endpoints
- Transaction statistics
- Service status monitoring
- Error logging and tracking
bun run devbun run build
bun run startFROM oven/bun:1
WORKDIR /app
COPY package.json bun.lockb ./
RUN bun install
COPY . .
EXPOSE 3000
CMD ["bun", "run", "start"]- Blockfrost API: Blockchain queries and transaction submission
- Koios API: Alternative blockchain data source
- Plutus Scripts: Smart contract deployment and interaction
- Banking Partner API: UPI payment processing
- NPCI Integration: Direct UPI network access
- Webhook Handling: Real-time payment status updates
- Transaction Analysis: Pattern recognition and risk assessment
- Midnight Privacy: Zero-knowledge proofs for sensitive data
- On-chain Storage: Encrypted credit scores on Cardano
- Bun Runtime: 3x faster than Node.js
- Async Processing: Background UPI payment handling
- Connection Pooling: Efficient database connections
- Caching: Exchange rate and pool balance caching
- Bun Installation: Use official installer from bun.sh
- SSL Certificates: Configure for production deployment
- Database Connection: Check PostgreSQL credentials
- API Keys: Verify Blockfrost and UPI gateway keys
Check application logs for detailed error information:
# Development
bun run dev
# Production logs
tail -f /var/log/crypto-upi-api.log- Fork the repository
- Create feature branch (
git checkout -b feature/amazing-feature) - Commit changes (
git commit -m 'Add amazing feature') - Push to branch (
git push origin feature/amazing-feature) - Open Pull Request
This project is licensed under the MIT License - see the LICENSE file for details.
For support and questions:
- Create an issue in the repository
- Check the API documentation at
/swagger - Review the troubleshooting section above
- Multi-signature wallet support
- Advanced credit scoring models
- Mobile SDK integration
- Real-time notifications
- Analytics dashboard
- Multi-currency support
A CIBIL-like credit scoring system for cryptocurrency wallets using Covalent APIs. This service analyzes wallet activity across multiple blockchain networks and calculates a comprehensive wallet score (0-850).
-
Multi-chain Analysis: Analyzes wallet data across 8 major blockchain networks
- Ethereum (1)
- Linea (59144)
- Base (8453)
- Arbitrum (42161)
- BNB Chain (56)
- Optimism (10)
- Polygon (137)
- Sei (1329)
-
Comprehensive Scoring: Evaluates wallets based on:
- Total Balance (30% weight)
- Portfolio Diversity (20% weight)
- Transaction Activity (20% weight)
- NFT Ownership (10% weight)
- Chain Diversity (10% weight)
- Portfolio Stability (10% weight)
# Install dependencies
npm install
# Copy environment variables
cp .env.example .env
# Update your Covalent API key in .env# Development mode with hot reload
npm run dev
# Build for production
npm run build
# Start production server
npm startThe server will start on http://localhost:3000
Endpoint: GET /api/wallet-score/:walletAddress
Description: Returns the calculated wallet score and breakdown
Example:
curl http://localhost:3000/api/wallet-score/0xd362b7e73aed6d097bf7a2032d6ee6a25d91f368Response:
{
"success": true,
"data": {
"walletAddress": "0xd362b7e73aed6d097bf7a2032d6ee6a25d91f368",
"totalScore": 125,
"scoreBreakdown": {
"totalBalanceScore": 0,
"portfolioDiversityScore": 0,
"transactionActivityScore": 0,
"nftOwnershipScore": 0,
"chainDiversityScore": 20,
"portfolioStabilityScore": 50
},
"grade": "Very Poor",
"chainsAnalyzed": [1, 59144, 8453, 42161, 56, 10, 137, 1329],
"timestamp": "2025-11-29T10:55:00.000Z"
}
}Endpoint: GET /api/wallet-score/:walletAddress/details
Description: Returns the wallet score along with raw API responses from all chains
Example:
curl http://localhost:3000/api/wallet-score/0xd362b7e73aed6d097bf7a2032d6ee6a25d91f368/detailsEndpoint: GET /health
Description: Check if the API is running
Example:
curl http://localhost:3000/health| Score Range | Grade |
|---|---|
| 750-850 | Excellent |
| 650-749 | Very Good |
| 550-649 | Good |
| 450-549 | Fair |
| 350-449 | Poor |
| 0-349 | Very Poor |
- Evaluates the total USD value across all chains
- Uses logarithmic scaling to handle varying wallet sizes
- Filters out spam tokens and dust
- Measures the number of unique, valuable tokens held
- Rewards multi-token portfolios
- Ignores spam and low-value tokens
- Analyzes transaction count and success rate
- Higher activity and success rates yield better scores
- Considers transaction patterns across all chains
- Evaluates NFT holdings across chains
- Rewards NFT diversity
- Measures wallet activity across multiple blockchains
- Rewards cross-chain engagement
- Analyzes portfolio value volatility over time
- Lower volatility indicates better stability
- Uses 30-day historical data
cardano/
โโโ src/
โ โโโ controllers/
โ โ โโโ walletScoreController.ts
โ โโโ services/
โ โ โโโ covalentService.ts
โ โ โโโ walletScoreService.ts
โ โโโ routes/
โ โ โโโ walletScoreRoutes.ts
โ โโโ server.ts
โโโ package.json
โโโ tsconfig.json
โโโ .env.example
โโโ README.md
PORT: Server port (default: 3000)COVALENT_API_KEY: Your Covalent API key
The API returns appropriate HTTP status codes:
200: Success400: Bad request (invalid wallet address)404: Route not found500: Internal server error
- All wallet addresses must be valid Ethereum-style addresses (0x followed by 40 hexadecimal characters)
- API calls to Covalent are made in parallel for better performance
- Failed chain queries don't block the overall score calculation
- Scores are calculated in real-time on each request
MIT