Key Features and Capabilities
Referenced Files in This Document - README.md - server.py - app/core/config.py - chains.yaml - docker-compose.yml - app/blockchain/manager.py - app/blockchain/base.py - app/blockchain/bsc.py - app/blockchain/ethereum.py - app/blockchain/anvil.py - app/db/models/payment.py - app/db/models/transaction.py - app/services/blockchain/scanner.py - app/services/blockchain/sweeper.py - app/utils/crypto.py - app/api/v1/payments.py - app/api/health.py - app/api/dependencies.py - app/workers/listener.py - app/workers/sweeper.py - app/workers/webhook.py - app/services/webhook.py - app/db/async_session.py - app/db/engine.py - app/db/session.py - app/db/base.py - app/db/seed.py - migrate.py - alembic/env.py - alembic/script.py.mako - alembic/versions/2026_01_27_1807-5ec6405addd0_initial_database_schema.py
Table of Contents
- Introduction
- Project Structure
- Core Components
- Architecture Overview
- Detailed Component Analysis
- Dependency Analysis
- Performance Considerations
- Troubleshooting Guide
- Conclusion
- Appendices
Introduction
This document explains cTrip’s core features and capabilities with a focus on multi-chain support, automated payment detection, confirmation monitoring, async architecture, background workers, HD wallet integration, webhook notifications, and database migrations. It provides practical examples, configuration requirements, integration patterns, and discusses performance, scalability, and reliability.
Project Structure
The project is organized around a FastAPI application with modular components: - API layer: endpoints for payments and health checks - Blockchain layer: multi-chain implementations and Web3 integration - Services: scanning and sweeping logic - Workers: background tasks orchestrated by ARQ and Redis - Database: SQLAlchemy ORM models and Alembic migrations - Utilities: HD wallet management
Diagram sources - server.py - app/core/config.py - app/blockchain/manager.py - app/blockchain/base.py - app/blockchain/bsc.py - app/blockchain/ethereum.py - app/blockchain/anvil.py - app/services/blockchain/scanner.py - app/services/blockchain/sweeper.py - app/workers/listener.py - app/workers/sweeper.py - app/workers/webhook.py - app/db/models/payment.py - app/db/models/transaction.py - app/db/async_session.py - app/db/engine.py - app/db/session.py - app/db/base.py - app/db/seed.py - migrate.py - alembic/env.py - alembic/script.py.mako - alembic/versions/2026_01_27_1807-5ec6405addd0_initial_database_schema.py
Section sources - README.md - server.py - docker-compose.yml
Core Components
- Multi-chain support across BSC, Ethereum, and Anvil test networks
- Automated payment detection and confirmation monitoring
- Async FastAPI and SQLAlchemy architecture
- Background workers via ARQ and Redis
- HD wallet for unique address generation
- Webhook notifications for payment status updates
- Alembic-based database migrations
Section sources - README.md - app/blockchain/manager.py - app/blockchain/base.py - app/services/blockchain/scanner.py - app/services/blockchain/sweeper.py - app/utils/crypto.py - app/services/webhook.py - migrate.py
Architecture Overview
cTrip runs an async FastAPI application that loads configured blockchains at startup, initializes an HD wallet, seeds chain states, and triggers background workers. The scanner service periodically scans blocks for incoming payments, while the sweeper service consolidates funds after confirmation. Webhooks notify external systems upon status changes.
Diagram sources - server.py - app/core/config.py - app/blockchain/manager.py - app/services/blockchain/scanner.py - app/services/blockchain/sweeper.py - app/workers/listener.py - app/workers/sweeper.py
Detailed Component Analysis
Multi-Chain Support (BSC, Ethereum, Anvil)
- Implementation pattern: A base class encapsulates shared Web3 operations; chain-specific subclasses override chain ID and PoA handling.
- Configuration: Chains are loaded from a YAML file and mapped to blockchain instances at runtime.
- Benefits:
- Unified interface for native and token transfers
- Pluggable chain selection
- Test network support via Anvil
Diagram sources - app/blockchain/base.py - app/blockchain/bsc.py - app/blockchain/ethereum.py - app/blockchain/anvil.py
Practical example: - Configure chains in the YAML file and ensure the manager creates instances for each chain. - Use the base class methods to query balances, estimate fees, and build transactions.
Configuration requirements: - Provide RPC endpoints per chain in the YAML file. - Ensure chain IDs and PoA flags match the target network.
Integration pattern: - Resolve a Web3 client per chain and pass it to services that operate on that chain.
Section sources - app/blockchain/manager.py - chains.yaml - app/blockchain/base.py - app/blockchain/bsc.py - app/blockchain/ethereum.py - app/blockchain/anvil.py
Automated Payment Detection and Confirmation Monitoring
- Detection: Scans blocks within a batch window, matches native transfers and ERC20 logs to pending payments, and marks them as detected.
- Confirmation: After a configurable threshold, updates status to confirmed and optionally triggers a webhook.
- Async architecture: Uses async Web3 and SQLAlchemy sessions for non-blocking IO.
with row-level lock"] LoadState --> CheckPayments["Select pending payments for chain"] CheckPayments --> Batch["Compute from/to block window"] Batch --> LoopBlocks["Iterate blocks in window"] LoopBlocks --> NativeCheck["Match native transfers to payment addresses"] LoopBlocks --> ERC20Logs["Fetch ERC20 Transfer logs"] ERC20Logs --> MatchERC20["Match token address and amount"] NativeCheck --> UpdateDetected["Set status=detected"] MatchERC20 --> UpdateDetected UpdateDetected --> CommitState["Commit last_scanned_block"] CommitState --> ConfirmStep["Run confirm_payments(chain)"] ConfirmStep --> CalcConf["Compute confirmations vs threshold"] CalcConf --> Confirmed{"Reached threshold?"} Confirmed --> |Yes| MarkConfirmed["Set status=confirmed"] MarkConfirmed --> MaybeWebhook{"Webhook configured?"} MaybeWebhook --> |Yes| SendHook["Dispatch webhook task"] MaybeWebhook --> |No| SkipHook["Skip"] Confirmed --> |No| End(["End"]) SendHook --> End SkipHook --> End
Diagram sources - app/services/blockchain/scanner.py
Operational example: - Start the API and workers; the listener will schedule scanning and sweeping tasks. - Pending payments on a chain will be detected and confirmed according to the configured threshold.
Configuration requirements: - Set the number of confirmations required and block batch size in the scanner service initialization. - Configure the global webhook URL and secret if notifications are desired.
Integration pattern: - Call the scanner service from a worker actor or periodic scheduler. - Use the same session for database reads/writes within a single task.
Section sources - app/services/blockchain/scanner.py - app/db/models/payment.py - app/db/models/transaction.py
Async Architecture (SQLAlchemy and FastAPI)
- FastAPI routes are async; the lifespan hook initializes blockchains, HD wallet, and seeds chain states.
- Database sessions are async; models define payment and transaction states.
- Reliability: Transactions are committed per batch; errors are logged and tasks are retried by workers.
Diagram sources - server.py - app/db/async_session.py - app/db/engine.py - app/db/session.py - app/db/base.py - app/services/blockchain/scanner.py
Section sources - server.py - app/db/models/payment.py - app/db/models/transaction.py
Background Worker System (ARQ + Redis)
- ARQ tasks handle listening for payments, sweeping confirmed payments, and sending webhooks.
- Redis serves as the broker; workers are started via the container command.
- Scalability: Multiple worker containers can be deployed behind the same Redis instance.
Diagram sources - server.py - docker-compose.yml - app/workers/listener.py - app/workers/sweeper.py - app/workers/webhook.py
Operational example: - Run the worker container; it will start consuming tasks from Redis and execute background jobs.
Configuration requirements: - Set Redis URL in environment variables. - Ensure the worker command includes the three actors.
Section sources - docker-compose.yml - server.py
Secure HD Wallet Integration
- Generates unique payment addresses using BIP-44 derivation from a mnemonic.
- Provides deterministic address derivation for each payment index.
- Security: mnemonic and derived keys are handled via the underlying cryptographic libraries.
Diagram sources - app/utils/crypto.py
Operational example: - Initialize the HD wallet manager with a mnemonic; derive addresses for each payment. - Persist addresses and indices in the database for future sweeping.
Configuration requirements: - Provide a secure mnemonic via environment variables. - Seed chain states and ensure address uniqueness per payment.
Section sources - app/utils/crypto.py - app/db/models/payment.py
Webhook Notification System
- On confirmation, the scanner service can dispatch a webhook task if configured.
- Payload includes payment metadata; signature can be validated using the configured secret.
Diagram sources - app/services/blockchain/scanner.py - app/services/webhook.py - app/workers/webhook.py
Operational example: - Configure the global webhook URL and secret; on confirmed payments, a task is enqueued and delivered asynchronously.
Configuration requirements: - Set webhook URL and secret in settings. - Implement signature verification on the receiving end.
Section sources - app/services/blockchain/scanner.py - app/core/config.py
Robust Migration System (Alembic)
- Alembic manages database schema evolution; a helper script wraps migration commands.
- Initial schema defines payments and transactions with appropriate statuses and relationships.
Diagram sources - migrate.py - alembic/env.py - alembic/script.py.mako - alembic/versions/2026_01_27_1807-5ec6405addd0_initial_database_schema.py
Operational example: - Run the migration helper to upgrade/downgrade schema as needed.
Configuration requirements: - Configure the database URL in environment variables. - Keep migrations versioned and review changes before applying.
Section sources - migrate.py - alembic/env.py - alembic/script.py.mako - alembic/versions/2026_01_27_1807-5ec6405addd0_initial_database_schema.py
Dependency Analysis
- API depends on services and workers; services depend on blockchain clients and database sessions.
- Blockchain layer abstracts chain differences; workers depend on Redis.
- Database models define relationships between payments and transactions.
Diagram sources - app/api/v1/payments.py - app/api/health.py - app/api/dependencies.py - app/services/blockchain/scanner.py - app/services/blockchain/sweeper.py - app/workers/listener.py - app/workers/sweeper.py - app/workers/webhook.py - app/db/models/payment.py - app/db/models/transaction.py - app/blockchain/manager.py - app/core/config.py
Section sources - app/blockchain/manager.py - app/services/blockchain/scanner.py - app/services/blockchain/sweeper.py - app/workers/listener.py - app/workers/sweeper.py - app/workers/webhook.py - app/db/models/payment.py - app/db/models/transaction.py - app/core/config.py
Performance Considerations
- Block scanning batch size controls throughput versus latency; tune based on chain throughput and worker capacity.
- Gas price caching reduces repeated RPC calls; adjust cache duration for volatility.
- Async IO prevents blocking on network calls; ensure database connections pool appropriately.
- Webhook delivery is offloaded to workers; configure retry/backoff on the receiver.
- HD wallet derivation is CPU-light; batching address generation improves throughput.
[No sources needed since this section provides general guidance]
Troubleshooting Guide
- Connectivity: Verify RPC URLs and chain IDs; check base class connection method.
- Database: Ensure migrations are applied and the database URL is correct.
- Workers: Confirm Redis connectivity and that the worker command includes the actors.
- Webhooks: Validate webhook URL and secret; inspect worker logs for delivery failures.
- Addresses: Regenerate addresses from the HD wallet if collisions occur.
Section sources - app/blockchain/base.py - migrate.py - docker-compose.yml - app/services/blockchain/scanner.py - app/utils/crypto.py
Conclusion
cTrip delivers a robust, scalable payment infrastructure with multi-chain support, automated detection and confirmation, async processing, distributed workers, secure HD wallets, webhooks, and migrations. By tuning configuration parameters and leveraging the modular architecture, teams can achieve high reliability and performance across production and test environments.
[No sources needed since this section summarizes without analyzing specific files]
Appendices
Configuration Checklist
- Environment variables: database URL, Redis URL, RPC URL, private key, mnemonic, webhook URL and secret.
- Chains YAML: RPC endpoints and token lists per chain.
- Docker Compose: services for app, worker, db, and redis.
Section sources - app/core/config.py - chains.yaml - docker-compose.yml