-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
245 lines (202 loc) · 9.23 KB
/
main.py
File metadata and controls
245 lines (202 loc) · 9.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
"""
AddressTrackerBot v3 - Entry point.
Multi-chain monitoring with SQLite persistence.
"""
import sys
import time
import signal
import threading
from config import TELEGRAM_BOT_TOKEN, INFURA_PROJECT_ID, POLL_INTERVAL, MAX_BLOCK_RANGE
from database import (
init_db, get_all_addresses, update_last_seen_block, store_transaction,
)
from utils import logger
from web3_handler import (
ChainManager, get_block_number,
get_transactions_for_address, get_token_transfers,
get_token_info, format_transaction, get_price_usd,
)
from bot_handler import config_bot, register_handlers
# Graceful shutdown flag
shutdown_event = threading.Event()
def signal_handler(sig, frame):
logger.info("Shutdown signal received, stopping...")
shutdown_event.set()
def monitor_addresses(chain_manager, bot):
"""
Background thread that polls for new transactions on all monitored addresses.
Scans native transfers and ERC-20 Transfer events, then notifies the owning user.
"""
logger.info("Monitoring thread started")
while not shutdown_event.is_set():
try:
all_addresses = get_all_addresses()
# Group by chain for efficient block number lookups
chains_seen = {}
for addr in all_addresses:
cid = addr['chain_id']
if cid not in chains_seen:
block_num = get_block_number(chain_manager, cid)
chains_seen[cid] = block_num
for addr in all_addresses:
if shutdown_event.is_set():
break
chain_id = addr['chain_id']
latest_block = chains_seen.get(chain_id)
if latest_block is None:
continue
last_block = addr['last_seen_block']
if last_block >= latest_block:
continue
from_block = last_block + 1
to_block = min(from_block + MAX_BLOCK_RANGE - 1, latest_block)
address = addr['address']
name = addr['name']
chat_id = addr['chat_id']
address_id = addr['id']
logger.info(
f"Scanning {name} ({address[:10]}...) on chain {chain_id} "
f"blocks {from_block}-{to_block}"
)
scan_ok = True
# --- Native transactions ---
try:
native_txs = get_transactions_for_address(
chain_manager, chain_id, address, from_block, to_block
)
for tx in native_txs:
raw_hash = tx.get('hash', b'')
tx_hash = ('0x' + raw_hash.hex()) if isinstance(raw_hash, bytes) else str(raw_hash)
from_addr = tx.get('from', '')
to_addr = tx.get('to', '') or ''
value_wei = str(tx.get('value', 0))
block_num = tx.get('blockNumber', 0)
timestamp = tx.get('_block_timestamp')
direction = 'sent' if from_addr.lower() == address.lower() else 'received'
# Skip zero-value native txs (likely contract calls)
if int(value_wei) == 0:
continue
# Check threshold
threshold = int(addr.get('threshold_wei', '0') or '0')
if threshold > 0 and int(value_wei) < threshold:
continue
store_transaction(
address_id=address_id, chain_id=chain_id,
tx_hash=tx_hash, block_number=block_num,
from_addr=from_addr, to_addr=to_addr,
value_wei=value_wei, tx_type='native',
direction=direction, timestamp=timestamp,
)
# Compute USD value for notification
usd_value = None
price = get_price_usd(chain_id)
if price is not None:
eth_value = int(value_wei) / (10 ** 18)
usd_value = eth_value * price
msg = format_transaction(
chain_id=chain_id, tx_hash=tx_hash,
from_addr=from_addr, to_addr=to_addr,
value_wei=value_wei, name=name, address=address,
timestamp=timestamp, usd_value=usd_value,
)
try:
bot.send_message(chat_id, msg)
except Exception as e:
logger.error(f"Failed to send notification to {chat_id}: {e}")
except Exception as e:
logger.error(f"Error scanning native txs for {name}: {e}")
scan_ok = False
# --- ERC-20 transfers ---
try:
token_txs = get_token_transfers(
chain_manager, chain_id, address, from_block, to_block
)
for ttx in token_txs:
token_info = get_token_info(
chain_manager, chain_id, ttx['token_address']
)
store_transaction(
address_id=address_id, chain_id=chain_id,
tx_hash=ttx['tx_hash'], block_number=ttx['block_number'],
from_addr=ttx['from_addr'], to_addr=ttx['to_addr'],
value_wei=ttx['raw_value'], tx_type='erc20',
token_address=ttx['token_address'],
token_symbol=token_info['symbol'],
token_decimals=token_info['decimals'],
direction=ttx['direction'],
)
msg = format_transaction(
chain_id=chain_id, tx_hash=ttx['tx_hash'],
from_addr=ttx['from_addr'], to_addr=ttx['to_addr'],
value_wei=ttx['raw_value'], name=name, address=address,
tx_type='erc20', token_symbol=token_info['symbol'],
token_decimals=token_info['decimals'],
)
try:
bot.send_message(chat_id, msg)
except Exception as e:
logger.error(f"Failed to send token notification to {chat_id}: {e}")
except Exception as e:
logger.error(f"Error scanning token transfers for {name}: {e}")
scan_ok = False
# Only advance block pointer if both scans succeeded
if scan_ok:
update_last_seen_block(address_id, to_block)
else:
logger.warning(f"Skipping block update for {name} due to scan errors")
# Small delay between addresses to respect rate limits
if not shutdown_event.is_set():
time.sleep(0.5)
except Exception as e:
logger.error(f"Error in monitoring loop: {e}")
# Wait for next poll cycle (check shutdown every second)
for _ in range(POLL_INTERVAL):
if shutdown_event.is_set():
break
time.sleep(1)
logger.info("Monitoring thread stopped")
def main():
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
if not TELEGRAM_BOT_TOKEN or not INFURA_PROJECT_ID:
logger.error("Missing TELEGRAM_BOT_TOKEN or INFURA_PROJECT_ID in environment")
print("Error: Set TELEGRAM_BOT_TOKEN and INFURA_PROJECT_ID in .env file")
sys.exit(1)
# Initialize database
init_db()
# Initialize multi-chain Web3 connections
try:
chain_manager = ChainManager(INFURA_PROJECT_ID)
except ConnectionError as e:
logger.error(f"Failed to initialize chain connections: {e}")
print(f"Error: {e}")
sys.exit(1)
# Initialize Telegram bot
bot = config_bot(TELEGRAM_BOT_TOKEN)
register_handlers(bot, chain_manager)
# Start monitoring in background thread
monitor_thread = threading.Thread(
target=monitor_addresses,
args=(chain_manager, bot),
daemon=True,
)
monitor_thread.start()
logger.info("Background monitoring started")
# Run bot polling in the main thread
logger.info("Starting bot polling...")
print("AddressTrackerBot v3 is running. Press Ctrl+C to stop.")
while not shutdown_event.is_set():
try:
bot.polling(none_stop=True, interval=1, timeout=30)
except Exception as e:
logger.error(f"Bot polling error: {e}")
if not shutdown_event.is_set():
logger.info("Restarting polling in 5 seconds...")
time.sleep(5)
# Clean shutdown
bot.stop_polling()
monitor_thread.join(timeout=10)
logger.info("Bot stopped.")
print("Bot stopped.")
if __name__ == "__main__":
main()