Getting Started

Referenced Files in This Document - README.md - docker-compose.yml - Dockerfile - chains.yaml - requirements.txt - pyproject.toml - app/core/config.py - server.py - migrate.py - app/db/engine.py - app/blockchain/manager.py - app/utils/crypto.py - app/workers/init.py - app/api/health.py - app/api/v1/payments.py

Table of Contents

  1. Introduction
  2. Prerequisites
  3. Quick Start
  4. Environment Configuration
  5. Chains Configuration
  6. HD Wallet Mnemonic
  7. Installation Methods
  8. Verification Steps
  9. Troubleshooting Guide
  10. Conclusion

Introduction

cTrip Payment Gateway is a high-performance, multi-chain cryptocurrency payment gateway built with FastAPI. It supports automated payment detection, confirmation monitoring, and funds sweeping across multiple EVM-compatible blockchains. The system uses an asynchronous architecture with PostgreSQL/SQLite for persistence, Redis for background task processing via ARQ, and Web3.py for blockchain interactions.

Key capabilities include: - Multi-chain support for BSC, Ethereum, and local testing environments (Anvil) - Real-time payment detection via WebSocket listeners using chain-sniper - Asynchronous API and database operations - Background workers powered by ARQ (async task queue) with Redis - HD Wallet integration for secure address generation (BIP-44) - Webhook notifications for payment status changes (HMAC-SHA256 signed) - Robust database migration system using Alembic - Admin API endpoints for manual task triggering

Prerequisites

Before installing cTrip Payment Gateway, ensure you have the following prerequisites:

  • Python 3.10 or higher
  • Docker and Docker Compose for containerized deployment
  • Redis for background worker messaging
  • PostgreSQL for production database storage

These requirements are essential for both Docker deployment and local development setups. The project includes comprehensive configuration for both environments.

Section sources - README.md - requirements.txt - pyproject.toml

Quick Start

Choose one of the two recommended installation approaches:

The fastest way to get started is using Docker Compose, which provisions all required services automatically:

docker-compose up --build

This single command starts: - PostgreSQL database service - Redis cache/queue service
- Application API service - Background worker service

Option B: Local Development Setup

For development, follow these steps:

  1. Create and activate virtual environment:

    python -m venv venv
    source venv/bin/activate  # On Windows use: venv\Scripts\activate
    

  2. Install dependencies:

    pip install -r requirements.txt
    

  3. Run database migrations:

    python migrate.py upgrade
    

  4. Start the API server:

    uvicorn server:app --reload
    

  5. Start background workers:

    python run_worker.py
    

Section sources - README.md - docker-compose.yml - Dockerfile

Environment Configuration

The application uses environment-based configuration managed through Pydantic Settings. Configuration is loaded from a .env file located at the project root.

Required Environment Variables

Set these variables in your .env file:

  • DATABASE_URL - Production database connection string
  • DATABASE_URL_DEV - Development database connection string (defaults to SQLite)
  • REDIS_URL - Redis connection URL for background tasks
  • PRIVATE_KEY - Ethereum private key for wallet operations (required)
  • MNEMONIC - HD Wallet mnemonic phrase (defaults to test phrase)
  • WEBHOOK_URL - Global webhook URL for payment notifications (optional)
  • WEBHOOK_SECRET - Secret key for signing webhook payloads (optional)
  • SECRET_KEY - Application secret key for cryptography
  • ENV - Environment mode: development, production, or testing

Environment-Specific Settings

The application supports three environments: - development - Uses SQLite by default - production - Requires explicit database URL configuration - testing - For test suite execution

Configuration Loading

Configuration is loaded from the .env file with automatic validation and type conversion. The system validates Ethereum private keys and enforces production security requirements.

Section sources - app/core/config.py - server.py

Chains Configuration

Configure supported blockchain networks in chains.yaml. This file defines RPC endpoints and token configurations for each chain.

Supported Chains

The system currently supports: - BSC (Binance Smart Chain) - Mainnet RPC endpoint with USDT token (commented out by default) - Ethereum - Mainnet configuration (commented out by default) - Anvil - Local development/testing WebSocket endpoint (active by default)

Chain Configuration Format

Each chain requires: - name - Chain identifier (ethereum, bsc, anvil) - rpc_url - RPC endpoint URL — must be a WebSocket URL (ws:// or wss://) for real-time payment detection via chain-sniper - tokens - Array of supported tokens with: - symbol - Token symbol - address - Contract address (for ERC20 tokens; omit for native tokens) - decimals - Token decimal precision

Default Configuration

The default configuration uses Anvil local testing with a WebSocket endpoint (ws://localhost:8545). Ethereum and BSC are commented out as examples. To enable mainnet chains, uncomment and set valid WebSocket RPC URLs.

Important: Payment detection requires WebSocket RPC URLs. If only an HTTP URL is provided, the chain-sniper listener will be skipped for that chain and payments won't be detected automatically.

Section sources - chains.yaml - app/blockchain/manager.py - app/core/config.py

HD Wallet Mnemonic

The system uses Hierarchical Deterministic (HD) Wallets for secure address generation following BIP-44 standards.

Mnemonic Configuration

  • Default: Test mnemonic phrase included for development
  • Production: Replace with your secure mnemonic phrase
  • Security: Never commit mnemonics to version control

Address Derivation

Addresses are derived using the path: m/44'/60'/0'/0/{index} where index corresponds to payment identifiers.

Wallet Management

The HDWalletManager class provides: - Mnemonic phrase validation and generation - Sequential address derivation - Private key derivation for fund management - Batch address generation for multiple payments

Security Best Practices

  • Use strong, random mnemonics in production
  • Store mnemonics in secure environment variables
  • Rotate keys periodically
  • Limit mnemonic exposure in logs and error messages

Section sources - app/utils/crypto.py - app/core/config.py

Installation Methods

The Docker-based installation provides a complete, isolated environment with all dependencies pre-configured.

Prerequisites

  • Docker Engine 20.10+ installed
  • Docker Compose v2+ installed
  • Port 8000 (API), 5432 (PostgreSQL), and 6379 (Redis) available

Build and Run

# Clone repository and navigate to project directory
git clone <repository-url>
cd ctrip

# Start all services
docker-compose up --build

Service Architecture

graph TB subgraph "Docker Network" API[API Service
Port 8000] Worker[Worker Service
Background Tasks] DB[(PostgreSQL Database)] Cache[(Redis Cache/Queue)] end Client[Client Applications] --> API API --> DB API --> Cache Worker --> DB Worker --> Cache API -.-> Worker

Diagram sources - docker-compose.yml

Container Configuration

  • App Service: Builds from Dockerfile, exposes port 8000, mounts code volume
  • Worker Service: Runs ARQ workers for background processing
  • Database Service: PostgreSQL 15 with persistent volume storage
  • Cache Service: Redis 7 for task queue and caching

Section sources - docker-compose.yml - Dockerfile

Local Development Setup

For development and testing, set up the environment locally with Python dependencies.

Step-by-Step Installation

  1. Python Environment

    # Create virtual environment
    python -m venv venv
    
    # Activate environment
    source venv/bin/activate  # Linux/Mac
    # venv\Scripts\activate    # Windows
    
    # Install dependencies
    pip install -r requirements.txt
    

  2. Database Setup

  3. Development: SQLite database file (auto-created)
  4. Production: PostgreSQL server with configured credentials

  5. Configuration

  6. Create .env file from template
  7. Configure chains in chains.yaml
  8. Set HD wallet mnemonic and private key

  9. Migration Execution

    # Apply database migrations
    python migrate.py upgrade
    
    # Verify migration status
    python migrate.py current
    

  10. Service Startup

    # Start API server
    uvicorn server:app --reload
    
    # Start ARQ background worker
    python run_worker.py
    

Section sources - README.md - requirements.txt - migrate.py

Verification Steps

After installation, verify the system is functioning correctly using these steps:

Health Check

Test the health endpoint to ensure the API is responsive:

curl http://localhost:8000/health

Expected response: {"status": "ok"}

Database Connectivity

Verify database connectivity and migration status:

python migrate.py current

Chain Configuration Validation

Check that configured chains are properly loaded:

# Start Python interpreter
python

# Test chain loading
from app.core.config import settings
print(settings.chains)

Background Worker Status

Verify background workers are processing tasks:

# Check Redis for queued tasks
redis-cli ping
# Should return: PONG

# Start the ARQ worker
python run_worker.py

Basic API Functionality

Test payment creation endpoint:

curl -X POST "http://localhost:8000/api/v1/payments/" \
  -H "Content-Type: application/json" \
  -d '{
    "chain": "bsc",
    "amount": "1000000000000000000",
    "token_id": null
  }'

Docker Environment Verification

For Docker deployments, verify all containers are healthy:

docker-compose ps

Expected status: All services should show "Up" status

Section sources - app/api/health.py - app/api/v1/payments.py - migrate.py

Troubleshooting Guide

Common Installation Issues

Docker Build Failures

Problem: Docker build fails during dependency installation Solution: - Clear Docker build cache: docker builder prune --all - Increase Docker memory allocation - Check internet connectivity for package downloads

Port Conflicts

Problem: Ports 8000, 5432, or 6379 already in use Solution:

# Find processes using ports
lsof -i :8000
lsof -i :5432  
lsof -i :6379

# Kill conflicting processes or change ports in docker-compose.yml

Database Connection Errors

Problem: Cannot connect to PostgreSQL Solution: - Verify PostgreSQL service is running: docker-compose up db - Check database credentials in .env file - Ensure database volume permissions are correct

Redis Connection Issues

Problem: Background workers cannot connect to Redis Solution: - Verify Redis service health: docker-compose up redis - Check Redis URL format in environment variables - Ensure firewall allows connections on port 6379

Migration Failures

Problem: Database migrations fail or hang Solution:

# Reset migrations (use with caution - backup database first)
python migrate.py downgrade -1
python migrate.py upgrade

# Check migration history
python migrate.py history

Chain Configuration Problems

Problem: Unsupported chain or RPC errors Solution: - Verify chain names match exactly: "ethereum", "bsc", "anvil" - Test RPC endpoint connectivity manually - Check token contract addresses for correct chain

HD Wallet Issues

Problem: Invalid mnemonic or address derivation failures Solution: - Use valid 12-word mnemonic phrases - Verify private key format matches Ethereum standards - Check mnemonic encoding in environment variables

Development Environment Issues

Python Dependency Conflicts

Problem: Import errors or missing modules Solution:

# Clean virtual environment
deactivate
rm -rf venv
python -m venv venv
source venv/bin/activate

# Reinstall dependencies
pip install --upgrade pip
pip install -r requirements.txt

Alembic Configuration Problems

Problem: Alembic cannot find database configuration Solution: - Verify alembic.ini and alembic/env.py are present - Check database URL format in environment variables - Ensure DATABASE_URL is exported to environment

Uvicorn Reload Issues

Problem: Hot reload not working or frequent restarts Solution: - Check for syntax errors in Python files - Verify file permissions in mounted volumes - Disable auto-reload during debugging: uvicorn server:app

Production Deployment Considerations

Security Hardening

  • Change default secret keys immediately
  • Use HTTPS termination in front of API
  • Implement rate limiting and input validation
  • Regular security audits of dependencies

Performance Optimization

  • Scale Redis and PostgreSQL instances
  • Implement connection pooling
  • Monitor database query performance
  • Use appropriate hardware resources

Monitoring and Logging

  • Set up centralized logging
  • Implement health checks and alerts
  • Monitor background worker queues
  • Track API response times and error rates

Section sources - docker-compose.yml - app/core/config.py - migrate.py

Conclusion

cTrip Payment Gateway provides a robust foundation for building multi-chain cryptocurrency payment solutions. The recommended Docker deployment approach ensures consistent environments and simplified dependency management. For development, the local setup offers flexibility and debugging capabilities.

Key success factors: - Proper environment configuration with secure secrets - Correct chain configuration for target networks - HD wallet security best practices - Comprehensive testing and monitoring setup

The modular architecture supports easy extension for additional blockchain networks and payment features. Regular maintenance includes dependency updates, database migrations, and security audits to ensure long-term reliability and security.