Professional TRC20 transaction monitoring for Tron blockchain
Project description
TRC20 Monitor
Professional TRC20 transaction monitoring for Tron blockchain with pluggable adapters.
๐ 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 setupwith_database.py: SQLite persistencewebhook_example.py: Webhook notificationsenterprise_setup.py: Production configuration
๐ค Contributing
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - 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
- Tron Network for the blockchain infrastructure
- TronGrid for API services
- aiogram for Telegram bot inspiration
- FastAPI for async patterns
๐ Support
- ๐ Documentation
- ๐ Issues
- ๐ฌ Discussions
- ๐ง Email: support@trc20monitor.com
Made with โค๏ธ for the Tron ecosystem
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
60f397d4856cc543d210370d2ed14eb0d7e786b7f75d742ec336a0a947eaf980
|
|
| MD5 |
30e6983fd0e632d721cab943df39ac6e
|
|
| BLAKE2b-256 |
64e36c89ddb8a04038a8d6f5863dcfdd95441ca3684b7eddecd2ad626e3f3b91
|
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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
caf54abb8e93bfe64b9f60d5fa0bbe9c1633aa0f1f7c98c85301f95d98f96459
|
|
| MD5 |
ab8521ce012dde81f79e38a58dfcc9de
|
|
| BLAKE2b-256 |
c39dc1fc140d9e4529b19667755f7733b716b487ab7f83ea3e9017d068872277
|