Skip to main content

Professional TRC20 transaction monitoring for Tron blockchain

Project description

TRC20 Monitor

Professional TRC20 transaction monitoring for Tron blockchain with pluggable adapters.

Python Version License: MIT

๐Ÿš€ Quick Start

Installation

pip install trc20-monitor

Basic Usage

import asyncio
from trc20_monitor import (
    TRC20Monitor,
    MonitorConfig,
    MemoryDatabaseAdapter,
    ConsoleNotificationAdapter
)

async def main():
    # Configure monitoring
    config = MonitorConfig(
        monitor_addresses=["TYourTronAddress1", "TYourTronAddress2"],
        large_transaction_threshold=1000.0  # Alert for >= 1000 USDT
    )
    
    # Create adapters
    database = MemoryDatabaseAdapter()
    notifications = ConsoleNotificationAdapter()
    
    # Create monitor
    monitor = TRC20Monitor(
        config=config,
        database_adapter=database,
        notification_adapter=notifications
    )
    
    # Run once or continuously
    await monitor.start_monitoring(run_once=True)

asyncio.run(main())

Environment Configuration

export MONITOR_ADDRESSES="TAddress1,TAddress2,TAddress3"
export TRON_API_KEY="your_trongrid_api_key"
export LARGE_TRANSACTION_THRESHOLD="5000.0"
export CHECK_INTERVAL_SECONDS="60"
# Load from environment variables
config = MonitorConfig.from_env()

๐Ÿ—๏ธ Architecture

TRC20 Monitor uses a pluggable adapter architecture:

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚   TRC20Monitor  โ”‚โ”€โ”€โ”€โ”€โ”‚ DatabaseAdapter  โ”‚โ”€โ”€โ”€โ”€โ”‚ NotificationAdapter โ”‚
โ”‚                 โ”‚    โ”‚                  โ”‚    โ”‚                     โ”‚
โ”‚ - Check API     โ”‚    โ”‚ - Track TXs      โ”‚    โ”‚ - Send Alerts       โ”‚
โ”‚ - Process TXs   โ”‚    โ”‚ - Prevent Dups   โ”‚    โ”‚ - Format Messages   โ”‚
โ”‚ - Handle Errors โ”‚    โ”‚ - Cleanup Old    โ”‚    โ”‚ - Multiple Channels โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
         โ”‚                       โ”‚                        โ”‚
         โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                                 โ”‚
                    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
                    โ”‚     Worker Process      โ”‚
                    โ”‚ - Continuous Running    โ”‚
                    โ”‚ - Graceful Shutdown     โ”‚
                    โ”‚ - Health Monitoring     โ”‚
                    โ”‚ - Statistics Tracking   โ”‚
                    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

๐Ÿ“ฆ Available Adapters

Database Adapters

  • MemoryDatabaseAdapter: In-memory storage (development/testing)
  • SQLiteDatabaseAdapter: SQLite database (single-node production)
  • SQLAlchemyDatabaseAdapter: PostgreSQL/MySQL (enterprise)

Notification Adapters

  • ConsoleNotificationAdapter: Terminal output with colors
  • FileNotificationAdapter: JSON/text file logging
  • WebhookNotificationAdapter: HTTP POST notifications
  • MultiNotificationAdapter: Multiple channels simultaneously

๐Ÿ”ง Advanced Configuration

Custom Database

from trc20_monitor.implementations import SQLiteDatabaseAdapter

# Persistent SQLite storage
database = SQLiteDatabaseAdapter("monitor.db")

# Or PostgreSQL via SQLAlchemy
from trc20_monitor.implementations import SQLAlchemyDatabaseAdapter
database = SQLAlchemyDatabaseAdapter("postgresql://user:pass@localhost/db")

Multiple Notifications

from trc20_monitor.implementations import (
    WebhookNotificationAdapter,
    FileNotificationAdapter,
    MultiNotificationAdapter
)

# Webhook notifications
webhook = WebhookNotificationAdapter([
    "https://hooks.slack.com/services/YOUR/WEBHOOK/URL",
    "https://discord.com/api/webhooks/YOUR/WEBHOOK"
])

# File logging
file_logger = FileNotificationAdapter("transactions.log", log_format="json")

# Combine multiple channels
notifications = MultiNotificationAdapter([webhook, file_logger])

Worker Process

from trc20_monitor.worker import TRC20Worker

# Background worker with health monitoring
worker = TRC20Worker(
    config=config,
    database_adapter=database,
    notification_adapter=notifications
)

# Start continuous monitoring
await worker.start()  # Runs until stopped

๐Ÿ–ฅ๏ธ Command Line Interface

# Initialize configuration file
trc20-monitor init

# Run once
trc20-monitor run-once --notification-type console

# Run continuously  
trc20-monitor --config-file config.json --db-type sqlite run

# Available options
trc20-monitor --help

๐Ÿ“Š Features

โœ… Core Functionality

  • Multi-address monitoring: Track multiple Tron addresses simultaneously
  • Duplicate prevention: Automatically prevents reprocessing transactions
  • Large amount alerts: Configurable threshold for high-value transaction alerts
  • Transaction age filtering: Ignore old transactions to focus on recent activity
  • Robust error handling: Graceful degradation and automatic retry mechanisms

โœ… Production Ready

  • Async/await: Full asyncio support for high performance
  • Pluggable architecture: Swap database and notification backends easily
  • Health monitoring: Built-in health checks for all components
  • Graceful shutdown: Proper cleanup on termination signals
  • Statistics tracking: Monitor processing rates and error counts

โœ… Enterprise Features

  • PostgreSQL support: Scale to high transaction volumes
  • Webhook notifications: Integrate with Slack, Discord, PagerDuty, etc.
  • Structured logging: JSON logs for centralized log management
  • Configuration management: Environment variables, JSON files, or code-based
  • Test coverage: Comprehensive test suite with async test support

๐Ÿงช Testing

# Install development dependencies
pip install trc20-monitor[dev]

# Run tests
pytest

# With coverage
pytest --cov=trc20_monitor

# Integration tests
pytest -m integration

๐Ÿ“ˆ Monitoring & Observability

Health Checks

# Component health status
health = await monitor.health_check()
print(health)
# {
#   "monitor": "ok",
#   "database": "ok", 
#   "notifications": "ok",
#   "api_connectivity": "ok"
# }

Statistics

# Worker statistics
stats = worker.get_stats()
print(f"Uptime: {stats['uptime_seconds']}s")
print(f"Successful checks: {stats['successful_checks']}")
print(f"Failed checks: {stats['failed_checks']}")

Custom Metrics

# Get transaction counts
total = await database.get_transaction_count()
recent = await database.get_recent_transactions(limit=10)

# Address-specific stats  
addr_summary = await database.get_addresses_summary()

๐Ÿ” Security Best Practices

API Keys

# Use environment variables for sensitive data
export TRON_API_KEY="your_api_key_here"

# Or use a secrets management system
# Never commit API keys to version control

Network Security

# Configure timeouts and retries
config = MonitorConfig(
    api_timeout_seconds=30,
    api_retries=3,
    retry_delay_seconds=5
)

Input Validation

# All inputs are validated
from trc20_monitor.utils import validate_address

if validate_address("TYourAddress"):
    print("Valid Tron address")

๐Ÿšฆ Error Handling

The library provides comprehensive error handling:

from trc20_monitor.core.exceptions import (
    TRC20MonitorError,      # Base exception
    ConfigurationError,     # Configuration issues
    ValidationError,        # Input validation errors
    APIError,              # Tron API errors
    DatabaseError,         # Database operation errors
    NotificationError      # Notification sending errors
)

try:
    await monitor.check_transactions()
except APIError as e:
    print(f"API error: {e.status_code} - {e}")
except DatabaseError as e:
    print(f"Database error: {e}")

๐Ÿ“š Examples

Check the examples/ directory for complete working examples:

  • basic_usage.py: Simple monitoring setup
  • with_database.py: SQLite persistence
  • webhook_example.py: Webhook notifications
  • enterprise_setup.py: Production configuration

๐Ÿค Contributing

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

Development Setup

git clone https://github.com/kun-g/trc20-monitor.git
cd trc20-monitor
pip install -e .[dev]
pre-commit install

๐Ÿ“œ License

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

๐Ÿ™ Acknowledgments

๐Ÿ“ž Support


Made with โค๏ธ for the Tron ecosystem

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

trc20_monitor-0.1.0.tar.gz (43.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

trc20_monitor-0.1.0-py3-none-any.whl (41.5 kB view details)

Uploaded Python 3

File details

Details for the file trc20_monitor-0.1.0.tar.gz.

File metadata

  • Download URL: trc20_monitor-0.1.0.tar.gz
  • Upload date:
  • Size: 43.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.1.4 CPython/3.13.7 Darwin/24.3.0

File hashes

Hashes for trc20_monitor-0.1.0.tar.gz
Algorithm Hash digest
SHA256 60f397d4856cc543d210370d2ed14eb0d7e786b7f75d742ec336a0a947eaf980
MD5 30e6983fd0e632d721cab943df39ac6e
BLAKE2b-256 64e36c89ddb8a04038a8d6f5863dcfdd95441ca3684b7eddecd2ad626e3f3b91

See more details on using hashes here.

File details

Details for the file trc20_monitor-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: trc20_monitor-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 41.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.1.4 CPython/3.13.7 Darwin/24.3.0

File hashes

Hashes for trc20_monitor-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 caf54abb8e93bfe64b9f60d5fa0bbe9c1633aa0f1f7c98c85301f95d98f96459
MD5 ab8521ce012dde81f79e38a58dfcc9de
BLAKE2b-256 c39dc1fc140d9e4529b19667755f7733b716b487ab7f83ea3e9017d068872277

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page