Skip to content

nayanprasad/crypto-pi

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

1 Commit
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

Crypto-to-INR Transaction API

A high-performance API built with Bun and TypeScript for processing crypto-to-UPI payments using Cardano blockchain technology.

๐Ÿš€ Features

  • 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

๐Ÿ—๏ธ Architecture

System Flow

The system follows the sequence diagram provided, implementing:

  1. Payment Initiation: User scans UPI QR, app calculates crypto amount
  2. Crypto Locking: User locks crypto in Plutus smart contract
  3. UPI Processing: System processes UPI payment to merchant
  4. Settlement: Crypto released to liquidity pool, transaction completed
  5. Credit Scoring: Background credit score update using AI and Midnight

Code Architecture

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.

๐Ÿ“‹ Prerequisites

  • Bun runtime (v1.0+)
  • Node.js 18+ (for compatibility)
  • PostgreSQL 14+ (for production)
  • Cardano node access (Blockfrost/Koios)

๐Ÿ› ๏ธ Installation

  1. Clone the repository

    git clone <repository-url>
    cd crypto-to-inr-api
  2. Install dependencies

    bun install
  3. Set up environment variables

    cp env.example .env
    # Edit .env with your configuration
  4. Test the controller architecture

    bun run test-controllers.ts
  5. Run the development server

    bun run dev

๐Ÿ”ง Configuration

Environment Variables

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

Database Setup

For production, set up PostgreSQL with the schema:

-- See the schema in the LLD comments
-- Tables: transactions, liquidity_pool, exchange_rates

๐Ÿ“– API Documentation

Start the server and visit:

  • Swagger UI: http://localhost:3000/swagger
  • Health Check: http://localhost:3000/health

Core Endpoints

1. Initiate Payment

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"
}

2. Confirm Crypto Lock

POST /api/v1/transactions/lock
Content-Type: application/json

{
  "transaction_id": "uuid",
  "cardano_tx_hash": "64-char-hex",
  "signed_by_wallet": "addr1..."
}

3. Get Transaction Status

GET /api/v1/transactions/{id}

๐Ÿ”„ Transaction Flow

  1. Initiation

    • Validate request parameters
    • Check liquidity pool availability
    • Calculate crypto amount + fees
    • Generate smart contract address
    • Return payment details
  2. Crypto Lock

    • Verify blockchain transaction
    • Update transaction status
    • Trigger UPI payment (background)
  3. UPI Processing (Background)

    • Reserve INR from pool
    • Initiate UPI payment
    • Handle success/failure
    • Release crypto to pool or refund
  4. Completion

    • Update transaction status
    • Trigger credit score update
    • Send notifications

๐Ÿงช Testing

# 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"
  }'

๐Ÿ” Security

  • Input validation and sanitization
  • Rate limiting (100 requests/minute)
  • CORS configuration
  • Environment-based secrets
  • Error handling without data leakage

๐Ÿ“Š Monitoring

  • Health check endpoints
  • Transaction statistics
  • Service status monitoring
  • Error logging and tracking

๐Ÿš€ Deployment

Development

bun run dev

Production

bun run build
bun run start

Docker (Optional)

FROM oven/bun:1
WORKDIR /app
COPY package.json bun.lockb ./
RUN bun install
COPY . .
EXPOSE 3000
CMD ["bun", "run", "start"]

๐Ÿ”ง Services Integration

Cardano Blockchain

  • Blockfrost API: Blockchain queries and transaction submission
  • Koios API: Alternative blockchain data source
  • Plutus Scripts: Smart contract deployment and interaction

UPI Gateway

  • Banking Partner API: UPI payment processing
  • NPCI Integration: Direct UPI network access
  • Webhook Handling: Real-time payment status updates

AI Credit Scoring

  • Transaction Analysis: Pattern recognition and risk assessment
  • Midnight Privacy: Zero-knowledge proofs for sensitive data
  • On-chain Storage: Encrypted credit scores on Cardano

๐Ÿ“ˆ Performance

  • 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

๐Ÿ› Troubleshooting

Common Issues

  1. Bun Installation: Use official installer from bun.sh
  2. SSL Certificates: Configure for production deployment
  3. Database Connection: Check PostgreSQL credentials
  4. API Keys: Verify Blockfrost and UPI gateway keys

Logs

Check application logs for detailed error information:

# Development
bun run dev

# Production logs
tail -f /var/log/crypto-upi-api.log

๐Ÿค Contributing

  1. Fork the repository
  2. Create feature branch (git checkout -b feature/amazing-feature)
  3. Commit changes (git commit -m 'Add amazing feature')
  4. Push to branch (git push origin feature/amazing-feature)
  5. Open Pull Request

๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

๐Ÿ†˜ Support

For support and questions:

  • Create an issue in the repository
  • Check the API documentation at /swagger
  • Review the troubleshooting section above

๐Ÿ”ฎ Roadmap

  • Multi-signature wallet support
  • Advanced credit scoring models
  • Mobile SDK integration
  • Real-time notifications
  • Analytics dashboard
  • Multi-currency support

Wallet Score API

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).

Features

  • 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)

Installation

# Install dependencies
npm install

# Copy environment variables
cp .env.example .env

# Update your Covalent API key in .env

Running the Application

# Development mode with hot reload
npm run dev

# Build for production
npm run build

# Start production server
npm start

The server will start on http://localhost:3000

API Endpoints

1. Get Wallet Score

Endpoint: GET /api/wallet-score/:walletAddress

Description: Returns the calculated wallet score and breakdown

Example:

curl http://localhost:3000/api/wallet-score/0xd362b7e73aed6d097bf7a2032d6ee6a25d91f368

Response:

{
  "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"
  }
}

2. Get Wallet Score with Details

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/details

3. Health Check

Endpoint: GET /health

Description: Check if the API is running

Example:

curl http://localhost:3000/health

Score Grading System

Score Range Grade
750-850 Excellent
650-749 Very Good
550-649 Good
450-549 Fair
350-449 Poor
0-349 Very Poor

Score Components

1. Total Balance Score (30%)

  • Evaluates the total USD value across all chains
  • Uses logarithmic scaling to handle varying wallet sizes
  • Filters out spam tokens and dust

2. Portfolio Diversity Score (20%)

  • Measures the number of unique, valuable tokens held
  • Rewards multi-token portfolios
  • Ignores spam and low-value tokens

3. Transaction Activity Score (20%)

  • Analyzes transaction count and success rate
  • Higher activity and success rates yield better scores
  • Considers transaction patterns across all chains

4. NFT Ownership Score (10%)

  • Evaluates NFT holdings across chains
  • Rewards NFT diversity

5. Chain Diversity Score (10%)

  • Measures wallet activity across multiple blockchains
  • Rewards cross-chain engagement

6. Portfolio Stability Score (10%)

  • Analyzes portfolio value volatility over time
  • Lower volatility indicates better stability
  • Uses 30-day historical data

Project Structure

cardano/
โ”œโ”€โ”€ src/
โ”‚   โ”œโ”€โ”€ controllers/
โ”‚   โ”‚   โ””โ”€โ”€ walletScoreController.ts
โ”‚   โ”œโ”€โ”€ services/
โ”‚   โ”‚   โ”œโ”€โ”€ covalentService.ts
โ”‚   โ”‚   โ””โ”€โ”€ walletScoreService.ts
โ”‚   โ”œโ”€โ”€ routes/
โ”‚   โ”‚   โ””โ”€โ”€ walletScoreRoutes.ts
โ”‚   โ””โ”€โ”€ server.ts
โ”œโ”€โ”€ package.json
โ”œโ”€โ”€ tsconfig.json
โ”œโ”€โ”€ .env.example
โ””โ”€โ”€ README.md

Environment Variables

  • PORT: Server port (default: 3000)
  • COVALENT_API_KEY: Your Covalent API key

Error Handling

The API returns appropriate HTTP status codes:

  • 200: Success
  • 400: Bad request (invalid wallet address)
  • 404: Route not found
  • 500: Internal server error

Notes

  • 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

License

MIT

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published