-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.py
More file actions
6489 lines (5348 loc) · 238 KB
/
bot.py
File metadata and controls
6489 lines (5348 loc) · 238 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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
TradeSeer Bot - Webhook Version for Cloud Deployment
This version uses Flask webhooks instead of polling to avoid asyncio issues
"""
import os
import json
import requests
import threading
import time
import re
import sqlite3
import secrets
import hashlib
from datetime import datetime, timedelta
from flask import Flask, request, jsonify
from flask_cors import CORS
from dotenv import load_dotenv
import logging
from collections import defaultdict
import statistics
# JWT for FunBonk integration
try:
import jwt
JWT_AVAILABLE = True
print("✅ JWT available for FunBonk integration")
except ImportError as e:
JWT_AVAILABLE = False
print(f"⚠️ JWT not available - FunBonk integration will be limited: {e}")
# Import all required packages with proper error handling
WEB3_AVAILABLE = False
WALLET_AVAILABLE = False
CRYPTO_AVAILABLE = False
ACCOUNT_AVAILABLE = False
# Try to import Web3 first
try:
from web3 import Web3
from eth_utils import to_checksum_address
WEB3_AVAILABLE = True
print("✅ Web3 available for full blockchain functionality")
except ImportError as e:
print(f"⚠️ Web3 not available - some features may be limited: {e}")
# Try to import Account
try:
from eth_account import Account
ACCOUNT_AVAILABLE = True
print("✅ Account creation available")
except ImportError as e:
print(f"❌ Account features not available: {e}")
# Try to import cryptography
try:
from cryptography.fernet import Fernet
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
import base64
CRYPTO_AVAILABLE = True
print("✅ Cryptography features available")
except ImportError as e:
print(f"❌ Cryptography features not available: {e}")
# Set wallet availability based on required components
if ACCOUNT_AVAILABLE and CRYPTO_AVAILABLE:
WALLET_AVAILABLE = True
print("✅ Wallet features available")
else:
print("❌ Wallet features not available - missing required dependencies")
# Load environment variables
try:
load_dotenv()
except Exception as e:
print(f"Warning: Could not load .env file: {e}")
TELEGRAM_BOT_TOKEN = os.getenv('TELEGRAM_BOT_TOKEN')
ETHERSCAN_API_KEY = os.getenv('ETHERSCAN_API_KEY')
WEBHOOK_URL = os.getenv('WEBHOOK_URL', '') # Will be set by Render
PORT = int(os.getenv('PORT', 5000))
# FunBonk Configuration
FONBNK_MERCHANT_SOURCE = os.getenv('FONBNK_MERCHANT_SOURCE', '') # Your FunBonk merchant source ID
FONBNK_ENVIRONMENT = os.getenv('FONBNK_ENVIRONMENT', 'sandbox') # 'sandbox' or 'production'
FONBNK_WEBHOOK_SECRET = os.getenv('FONBNK_WEBHOOK_SECRET', '') # Webhook verification secret
FONBNK_URL_SIGNATURE_SECRET = os.getenv('FONBNK_URL_SIGNATURE_SECRET', FONBNK_WEBHOOK_SECRET) # JWT signing secret
# Alternative USDC purchase options
ENABLE_ALTERNATIVE_ONRAMPPS = os.getenv('ENABLE_ALTERNATIVE_ONRAMPPS', 'true').lower() == 'true'
# Alternative onramp services configuration
ALTERNATIVE_ONRAMPPS = {
'transak': {
'enabled': os.getenv('ENABLE_TRANSAK', 'true').lower() == 'true',
'api_key': os.getenv('TRANSAK_API_KEY', ''),
'base_url': 'https://global.transak.com',
'widget_url': 'https://global.transak.com',
'supported_networks': ['base', 'ethereum', 'polygon'],
'min_amount': 20,
'max_amount': 10000
},
'moonpay': {
'enabled': os.getenv('ENABLE_MOONPAY', 'true').lower() == 'true',
'api_key': os.getenv('MOONPAY_API_KEY', ''),
'base_url': 'https://buy.moonpay.com',
'widget_url': 'https://buy.moonpay.com',
'supported_networks': ['base', 'ethereum', 'polygon'],
'min_amount': 25,
'max_amount': 50000
},
'ramp': {
'enabled': os.getenv('ENABLE_RAMP', 'true').lower() == 'true',
'api_key': os.getenv('RAMP_API_KEY', ''),
'base_url': 'https://ramp.network',
'widget_url': 'https://ramp.network',
'supported_networks': ['base', 'ethereum', 'polygon'],
'min_amount': 20,
'max_amount': 20000
}
}
# Validate environment variables
if not ETHERSCAN_API_KEY:
raise ValueError("ETHERSCAN_API_KEY not found in environment variables")
# Make Telegram token optional for development
if not TELEGRAM_BOT_TOKEN:
print("⚠️ TELEGRAM_BOT_TOKEN not found - Telegram bot features will be disabled")
TELEGRAM_BOT_TOKEN = None
# FunBonk availability check
FONBNK_AVAILABLE = bool(FONBNK_MERCHANT_SOURCE) and JWT_AVAILABLE
if FONBNK_AVAILABLE:
print("✅ FunBonk integration available")
elif bool(FONBNK_MERCHANT_SOURCE) and not JWT_AVAILABLE:
print("⚠️ FunBonk integration disabled - JWT not available")
else:
print("⚠️ FunBonk integration disabled - set FONBNK_MERCHANT_SOURCE environment variable")
# Global storage
user_wallets = {}
user_settings = {}
user_profiles = {} # New: Store user profiles with unique IDs
user_portfolios = {} # Portfolio tracking data
portfolio_history = {} # Historical portfolio data
wallet_performance = {} # Wallet performance metrics
running = True
# Database setup
DB_FILE = 'tradeseer_bot.db'
# Global state for pending swaps and token info requests
PENDING_SWAPS = {} # chat_id -> swap_info
TOKEN_INFO_REQUESTS = {} # chat_id -> token_info_request
def init_database():
"""Initialize SQLite database for persistent storage"""
conn = sqlite3.connect(DB_FILE)
cursor = conn.cursor()
# Create users table for unique user management
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
user_id INTEGER PRIMARY KEY AUTOINCREMENT,
chat_id INTEGER UNIQUE NOT NULL,
username TEXT,
first_name TEXT,
last_name TEXT,
registration_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
last_activity TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
is_active BOOLEAN DEFAULT 1,
user_type TEXT DEFAULT 'regular',
preferences JSON
)
''')
# Create tables
cursor.execute('''
CREATE TABLE IF NOT EXISTS tracked_wallets (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
chat_id INTEGER NOT NULL,
wallet_address TEXT NOT NULL,
date_added TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE(user_id, wallet_address),
FOREIGN KEY (user_id) REFERENCES users(user_id)
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS user_settings (
user_id INTEGER PRIMARY KEY,
chat_id INTEGER NOT NULL,
alert_threshold REAL DEFAULT 0.2,
notification_style TEXT DEFAULT 'default',
auto_score BOOLEAN DEFAULT 1,
FOREIGN KEY (user_id) REFERENCES users(user_id)
)
''')
# New table for connected wallets
cursor.execute('''
CREATE TABLE IF NOT EXISTS connected_wallets (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
chat_id INTEGER NOT NULL,
wallet_address TEXT NOT NULL,
wallet_name TEXT,
is_active BOOLEAN DEFAULT 1,
date_connected TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE(user_id, wallet_address),
FOREIGN KEY (user_id) REFERENCES users(user_id)
)
''')
# New table for wallet private keys (encrypted)
cursor.execute('''
CREATE TABLE IF NOT EXISTS wallet_keys (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
chat_id INTEGER NOT NULL,
wallet_address TEXT NOT NULL,
encrypted_private_key TEXT NOT NULL,
salt TEXT NOT NULL,
date_created TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE(user_id, wallet_address),
FOREIGN KEY (user_id) REFERENCES users(user_id)
)
''')
# New table for transaction history
cursor.execute('''
CREATE TABLE IF NOT EXISTS bot_transactions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
chat_id INTEGER NOT NULL,
wallet_address TEXT NOT NULL,
transaction_type TEXT NOT NULL,
token_address TEXT,
token_symbol TEXT,
amount REAL,
tx_hash TEXT,
chain TEXT DEFAULT 'base',
status TEXT DEFAULT 'pending',
date_created TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(user_id)
)
''')
# Create indexes for better performance
cursor.execute('CREATE INDEX IF NOT EXISTS idx_users_chat_id ON users(chat_id)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_tracked_wallets_user_id ON tracked_wallets(user_id)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_connected_wallets_user_id ON connected_wallets(user_id)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_transactions_user_id ON bot_transactions(user_id)')
# Create portfolio tracking tables
cursor.execute('''
CREATE TABLE IF NOT EXISTS portfolio_history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
chat_id INTEGER NOT NULL,
date_recorded TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
portfolio_value REAL NOT NULL,
total_roi REAL DEFAULT 0,
num_wallets INTEGER DEFAULT 0,
FOREIGN KEY (chat_id) REFERENCES users(chat_id)
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS wallet_performance (
id INTEGER PRIMARY KEY AUTOINCREMENT,
wallet_address TEXT NOT NULL,
chat_id INTEGER NOT NULL,
initial_investment REAL DEFAULT 0,
current_value REAL DEFAULT 0,
total_return REAL DEFAULT 0,
daily_returns TEXT, -- JSON array of daily returns
last_updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (chat_id) REFERENCES users(chat_id)
)
''')
# Create table for tracking token positions
cursor.execute('''
CREATE TABLE IF NOT EXISTS user_positions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
chat_id INTEGER NOT NULL,
wallet_address TEXT NOT NULL,
token_address TEXT NOT NULL,
token_symbol TEXT NOT NULL,
token_name TEXT,
chain TEXT DEFAULT 'base',
initial_amount REAL NOT NULL,
current_amount REAL NOT NULL,
initial_price_usd REAL,
initial_investment_usd REAL,
first_purchase_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
last_updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
is_active BOOLEAN DEFAULT 1,
UNIQUE(user_id, wallet_address, token_address),
FOREIGN KEY (user_id) REFERENCES users(user_id)
)
''')
# Create table for FunBonk orders tracking
cursor.execute('''
CREATE TABLE IF NOT EXISTS fonbnk_orders (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
chat_id INTEGER NOT NULL,
order_id TEXT UNIQUE NOT NULL,
wallet_address TEXT NOT NULL,
amount_usd REAL NOT NULL,
currency TEXT DEFAULT 'USDC',
network TEXT DEFAULT 'base',
status TEXT DEFAULT 'pending',
payment_url TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
completed_at TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(user_id)
)
''')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_portfolio_chat_id ON portfolio_history(chat_id)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_wallet_performance_address ON wallet_performance(wallet_address)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_positions_user_id ON user_positions(user_id)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_positions_wallet ON user_positions(wallet_address)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_fonbnk_orders_user_id ON fonbnk_orders(user_id)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_fonbnk_orders_order_id ON fonbnk_orders(order_id)')
conn.commit()
conn.close()
print("✅ Database initialized with enhanced user management system")
def get_or_create_user(chat_id, username=None, first_name=None, last_name=None):
"""Get existing user or create new user with unique ID"""
try:
conn = sqlite3.connect(DB_FILE)
cursor = conn.cursor()
# Check if user exists
cursor.execute('SELECT user_id, username, first_name, last_name FROM users WHERE chat_id = ?', (chat_id,))
user = cursor.fetchone()
if user:
# Update last activity
cursor.execute('UPDATE users SET last_activity = CURRENT_TIMESTAMP WHERE chat_id = ?', (chat_id,))
conn.commit()
conn.close()
user_id, username, first_name, last_name = user
return {
'user_id': user_id,
'chat_id': chat_id,
'username': username,
'first_name': first_name,
'last_name': last_name,
'is_new': False
}
else:
# Create new user
cursor.execute('''
INSERT INTO users (chat_id, username, first_name, last_name)
VALUES (?, ?, ?, ?)
''', (chat_id, username, first_name, last_name))
user_id = cursor.lastrowid
conn.commit()
conn.close()
print(f"✅ Created new user: ID {user_id}, Chat ID {chat_id}")
return {
'user_id': user_id,
'chat_id': chat_id,
'username': username,
'first_name': first_name,
'last_name': last_name,
'is_new': True
}
except Exception as e:
print(f"❌ Error in get_or_create_user: {e}")
conn.close()
return None
def get_user_by_chat_id(chat_id):
"""Get user information by chat_id"""
try:
conn = sqlite3.connect(DB_FILE)
cursor = conn.cursor()
cursor.execute('SELECT user_id, username, first_name, last_name FROM users WHERE chat_id = ?', (chat_id,))
user = cursor.fetchone()
conn.close()
if user:
user_id, username, first_name, last_name = user
return {
'user_id': user_id,
'chat_id': chat_id,
'username': username,
'first_name': first_name,
'last_name': last_name
}
return None
except Exception as e:
print(f"❌ Error getting user by chat_id: {e}")
return None
def update_user_activity(chat_id):
"""Update user's last activity timestamp"""
try:
conn = sqlite3.connect(DB_FILE)
cursor = conn.cursor()
cursor.execute('UPDATE users SET last_activity = CURRENT_TIMESTAMP WHERE chat_id = ?', (chat_id,))
conn.commit()
conn.close()
except Exception as e:
print(f"❌ Error updating user activity: {e}")
def migrate_existing_users():
"""Migrate existing users from old database structure to new user ID system"""
try:
conn = sqlite3.connect(DB_FILE)
cursor = conn.cursor()
# Check if users table exists
cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='users'")
users_table_exists = cursor.fetchone() is not None
if not users_table_exists:
print("🔄 Users table doesn't exist - database will be created with new structure")
conn.close()
return
# Check if we need to migrate (look for tracked_wallets without user_id)
cursor.execute("PRAGMA table_info(tracked_wallets)")
columns = [column[1] for column in cursor.fetchall()]
if 'user_id' not in columns:
print("🔄 Database structure is up to date")
conn.close()
return
# Check if there are any existing records in tracked_wallets
cursor.execute("SELECT COUNT(*) FROM tracked_wallets")
existing_records = cursor.fetchone()[0]
if existing_records == 0:
print("✅ No existing data to migrate")
conn.close()
return
# Find existing chat_ids that don't have user records
cursor.execute('''
SELECT DISTINCT tw.chat_id
FROM tracked_wallets tw
LEFT JOIN users u ON tw.chat_id = u.chat_id
WHERE u.chat_id IS NULL
''')
orphaned_chat_ids = cursor.fetchall()
if not orphaned_chat_ids:
print("✅ No orphaned data found - migration complete")
conn.close()
return
print(f"🔄 Found {len(orphaned_chat_ids)} chat_ids to migrate...")
migrated_count = 0
for (chat_id,) in orphaned_chat_ids:
try:
# Create user record for orphaned chat_id
cursor.execute('''
INSERT INTO users (chat_id, username, first_name, last_name)
VALUES (?, ?, ?, ?)
''', (chat_id, None, None, None))
user_id = cursor.lastrowid
# Update tracked_wallets to include user_id
cursor.execute('''
UPDATE tracked_wallets
SET user_id = ?
WHERE chat_id = ?
''', (user_id, chat_id))
# Update user_settings to include user_id (if table exists)
try:
cursor.execute("PRAGMA table_info(user_settings)")
settings_columns = [column[1] for column in cursor.fetchall()]
if 'user_id' in settings_columns:
cursor.execute('''
UPDATE user_settings
SET user_id = ?
WHERE chat_id = ?
''', (user_id, chat_id))
except Exception as e:
print(f"⚠️ Could not update user_settings: {e}")
# Update connected_wallets to include user_id (if table exists)
try:
cursor.execute("PRAGMA table_info(connected_wallets)")
connected_columns = [column[1] for column in cursor.fetchall()]
if 'user_id' in connected_columns:
cursor.execute('''
UPDATE connected_wallets
SET user_id = ?
WHERE chat_id = ?
''', (user_id, chat_id))
except Exception as e:
print(f"⚠️ Could not update connected_wallets: {e}")
# Update wallet_keys to include user_id (if table exists)
try:
cursor.execute("PRAGMA table_info(wallet_keys)")
keys_columns = [column[1] for column in cursor.fetchall()]
if 'user_id' in keys_columns:
cursor.execute('''
UPDATE wallet_keys
SET user_id = ?
WHERE chat_id = ?
''', (user_id, chat_id))
except Exception as e:
print(f"⚠️ Could not update wallet_keys: {e}")
# Update bot_transactions to include user_id (if table exists)
try:
cursor.execute("PRAGMA table_info(bot_transactions)")
tx_columns = [column[1] for column in cursor.fetchall()]
if 'user_id' in tx_columns:
cursor.execute('''
UPDATE bot_transactions
SET user_id = ?
WHERE chat_id = ?
''', (user_id, chat_id))
except Exception as e:
print(f"⚠️ Could not update bot_transactions: {e}")
migrated_count += 1
print(f"✅ Migrated chat_id {chat_id} to user_id {user_id}")
except Exception as e:
print(f"❌ Error migrating chat_id {chat_id}: {e}")
continue
conn.commit()
conn.close()
print(f"🎉 Migration complete! Migrated {migrated_count} users")
except Exception as e:
print(f"❌ Error during migration: {e}")
conn.close()
def load_wallets_from_db():
"""Load tracked wallets from database into memory"""
global user_wallets
try:
conn = sqlite3.connect(DB_FILE)
cursor = conn.cursor()
cursor.execute('''
SELECT u.chat_id, tw.wallet_address
FROM tracked_wallets tw
JOIN users u ON tw.user_id = u.user_id
''')
rows = cursor.fetchall()
user_wallets = {}
for chat_id, wallet_address in rows:
if chat_id not in user_wallets:
user_wallets[chat_id] = []
user_wallets[chat_id].append(wallet_address)
total_wallets = sum(len(wallets) for wallets in user_wallets.values())
print(f"✅ Loaded {total_wallets} wallets for {len(user_wallets)} users from database")
conn.close()
except Exception as e:
print(f"❌ Error loading wallets from database: {e}")
def save_wallet_to_db(chat_id, wallet_address):
"""Save a wallet to the database"""
try:
user = get_user_by_chat_id(chat_id)
if not user:
print(f"❌ User not found for chat_id {chat_id}")
return False
conn = sqlite3.connect(DB_FILE)
cursor = conn.cursor()
cursor.execute(
'INSERT OR IGNORE INTO tracked_wallets (user_id, chat_id, wallet_address) VALUES (?, ?, ?)',
(user['user_id'], chat_id, wallet_address)
)
conn.commit()
conn.close()
print(f"✅ Saved wallet {wallet_address} for user {user['user_id']} (chat_id: {chat_id}) to database")
return True
except Exception as e:
print(f"❌ Error saving wallet to database: {e}")
return False
def remove_wallet_from_db(chat_id, wallet_address):
"""Remove a wallet from the database"""
try:
user = get_user_by_chat_id(chat_id)
if not user:
print(f"❌ User not found for chat_id {chat_id}")
return False
conn = sqlite3.connect(DB_FILE)
cursor = conn.cursor()
cursor.execute(
'DELETE FROM tracked_wallets WHERE user_id = ? AND wallet_address = ?',
(user['user_id'], wallet_address.lower())
)
conn.commit()
conn.close()
print(f"✅ Removed wallet {wallet_address} for user {user['user_id']} from database")
return True
except Exception as e:
print(f"❌ Error removing wallet from database: {e}")
return False
def calculate_portfolio_metrics(chat_id):
"""
Calculate comprehensive portfolio performance metrics
Args:
chat_id (int): Telegram chat ID
Returns:
dict: Portfolio metrics including ROI, Sharpe ratio, etc.
"""
try:
wallets = user_wallets.get(chat_id, [])
if not wallets:
return None
total_investment = 0
current_value = 0
returns = []
daily_returns = []
for wallet_address in wallets:
# Get wallet performance data
wallet_data = wallet_performance.get(wallet_address, {})
if wallet_data:
investment = wallet_data.get('initial_investment', 0)
current_val = wallet_data.get('current_value', 0)
wallet_return = wallet_data.get('total_return', 0)
total_investment += investment
current_value += current_val
returns.append(wallet_return)
# Calculate daily returns for Sharpe ratio
daily_ret = wallet_data.get('daily_returns', [])
daily_returns.extend(daily_ret)
if total_investment == 0:
return None
# Calculate metrics
total_roi = ((current_value - total_investment) / total_investment) * 100
avg_return = statistics.mean(returns) if returns else 0
# Sharpe ratio (assuming risk-free rate of 2%)
if daily_returns:
excess_returns = [ret - (0.02 / 365) for ret in daily_returns] # Daily risk-free rate
if len(excess_returns) > 1:
mean_excess = statistics.mean(excess_returns)
std_excess = statistics.stdev(excess_returns) if len(excess_returns) > 1 else 0
sharpe_ratio = mean_excess / std_excess if std_excess > 0 else 0
else:
sharpe_ratio = 0
else:
sharpe_ratio = 0
# Maximum drawdown
if daily_returns:
cumulative_returns = []
running_max = []
current_cumulative = 1.0
current_max = 1.0
for ret in daily_returns:
current_cumulative *= (1 + ret)
current_max = max(current_max, current_cumulative)
cumulative_returns.append(current_cumulative)
running_max.append(current_max)
drawdowns = [(cum - max_val) / max_val for cum, max_val in zip(cumulative_returns, running_max)]
max_drawdown = min(drawdowns) * 100 if drawdowns else 0
else:
max_drawdown = 0
# Win rate
winning_wallets = sum(1 for r in returns if r > 0)
win_rate = (winning_wallets / len(returns)) * 100 if returns else 0
return {
'total_investment': total_investment,
'current_value': current_value,
'total_roi': total_roi,
'avg_return': avg_return,
'sharpe_ratio': sharpe_ratio,
'max_drawdown': max_drawdown,
'win_rate': win_rate,
'num_wallets': len(wallets),
'winning_wallets': winning_wallets
}
except Exception as e:
print(f"Error calculating portfolio metrics: {e}")
return None
def update_wallet_performance(wallet_address, transaction_data):
"""
Update wallet performance metrics based on new transaction
Args:
wallet_address (str): Wallet address
transaction_data (dict): Transaction information
"""
try:
if wallet_address not in wallet_performance:
wallet_performance[wallet_address] = {
'initial_investment': 0,
'current_value': 0,
'total_return': 0,
'daily_returns': [],
'transactions': [],
'last_updated': datetime.now()
}
wallet_data = wallet_performance[wallet_address]
# Add transaction to history
wallet_data['transactions'].append(transaction_data)
# Calculate daily return
value_eth = float(transaction_data.get('value', 0)) / 1e18
if value_eth > 0:
# Simple daily return calculation (can be enhanced)
daily_return = value_eth * 0.01 # Placeholder - would need actual price data
wallet_data['daily_returns'].append(daily_return)
# Keep only last 30 days of returns
if len(wallet_data['daily_returns']) > 30:
wallet_data['daily_returns'] = wallet_data['daily_returns'][-30:]
# Update current value (simplified calculation)
wallet_data['current_value'] += value_eth
# Calculate total return
if wallet_data['initial_investment'] > 0:
wallet_data['total_return'] = ((wallet_data['current_value'] - wallet_data['initial_investment']) /
wallet_data['initial_investment']) * 100
wallet_data['last_updated'] = datetime.now()
except Exception as e:
print(f"Error updating wallet performance: {e}")
def get_portfolio_summary(chat_id):
"""
Get comprehensive portfolio summary for user
Args:
chat_id (int): Telegram chat ID
Returns:
str: Formatted portfolio summary message
"""
try:
metrics = calculate_portfolio_metrics(chat_id)
if not metrics:
return """
📊 <b>Portfolio Summary</b>
❌ No portfolio data available.
💡 <b>Start tracking wallets to build your portfolio!</b>
"""
# Format numbers
def format_currency(amount):
if amount >= 1000000:
return f"${amount/1000000:.2f}M"
elif amount >= 1000:
return f"${amount/1000:.2f}K"
else:
return f"${amount:.2f}"
def format_percentage(value):
return f"{value:+.2f}%" if value != 0 else "0.00%"
# Performance emoji
roi_emoji = "🚀" if metrics['total_roi'] > 0 else "📉"
sharpe_emoji = "⭐" if metrics['sharpe_ratio'] > 1 else "📊"
summary = f"""
📊 <b>Portfolio Performance Summary</b>
💰 <b>Total Investment:</b> {format_currency(metrics['total_investment'])}
💎 <b>Current Value:</b> {format_currency(metrics['current_value'])}
{roi_emoji} <b>Total ROI:</b> {format_percentage(metrics['total_roi'])}
📈 <b>Average Return:</b> {format_percentage(metrics['avg_return'])}
{sharpe_emoji} <b>Sharpe Ratio:</b> {metrics['sharpe_ratio']:.2f}
📉 <b>Max Drawdown:</b> {format_percentage(metrics['max_drawdown'])}
🎯 <b>Win Rate:</b> {metrics['win_rate']:.1f}%
📋 <b>Portfolio Stats:</b>
• Wallets Tracked: {metrics['num_wallets']}
• Winning Wallets: {metrics['winning_wallets']}
• Losing Wallets: {metrics['num_wallets'] - metrics['winning_wallets']}
💡 <b>Performance Insights:</b>
"""
# Add insights based on metrics
if metrics['total_roi'] > 20:
summary += "• 🚀 Excellent performance! Your portfolio is outperforming the market.\n"
elif metrics['total_roi'] > 0:
summary += "• 📈 Good performance! Your portfolio is generating positive returns.\n"
else:
summary += "• 📉 Consider reviewing your wallet selection strategy.\n"
if metrics['sharpe_ratio'] > 1:
summary += "• ⭐ High risk-adjusted returns! Your portfolio is efficient.\n"
elif metrics['sharpe_ratio'] > 0:
summary += "• 📊 Moderate risk-adjusted returns.\n"
else:
summary += "• ⚠️ Consider diversifying to improve risk-adjusted returns.\n"
if metrics['win_rate'] > 60:
summary += "• 🎯 High win rate! You're picking successful wallets.\n"
elif metrics['win_rate'] > 40:
summary += "• 📊 Moderate win rate. Consider refining your selection criteria.\n"
else:
summary += "• 🔍 Low win rate. Focus on higher-scoring wallets.\n"
return summary
except Exception as e:
print(f"Error generating portfolio summary: {e}")
return "❌ Error generating portfolio summary."
def save_portfolio_snapshot(chat_id):
"""
Save current portfolio state to database
Args:
chat_id (int): Telegram chat ID
"""
try:
metrics = calculate_portfolio_metrics(chat_id)
if not metrics:
return
conn = sqlite3.connect(DB_FILE)
cursor = conn.cursor()
cursor.execute('''
INSERT INTO portfolio_history (chat_id, portfolio_value, total_roi, num_wallets)
VALUES (?, ?, ?, ?)
''', (chat_id, metrics['current_value'], metrics['total_roi'], metrics['num_wallets']))
conn.commit()
conn.close()
except Exception as e:
print(f"Error saving portfolio snapshot: {e}")
def get_wallet_balance_multi_chain(wallet_address):
"""
Get wallet balance across multiple chains
Args:
wallet_address (str): Wallet address
Returns:
dict: Balance information for each chain
"""
try:
balances = {}
chains = ["ethereum", "base", "polygon", "arbitrum", "optimism", "bsc"]
for chain in chains:
try:
balance = get_wallet_balance(wallet_address, chain)
if balance is not None:
balances[chain] = balance
except Exception as e:
print(f"Error getting {chain} balance: {e}")
continue
return balances
except Exception as e:
print(f"Error getting multi-chain balances: {e}")
return {}
def get_cross_chain_activity(wallet_address):
"""
Analyze wallet activity across multiple chains
Args:
wallet_address (str): Wallet address
Returns:
dict: Cross-chain activity summary
"""
try:
chains = ["ethereum", "base", "polygon", "arbitrum", "optimism", "bsc"]
chain_activity = {}
total_transactions = 0
total_volume = 0
for chain in chains:
transactions = get_transactions_from_chain(wallet_address, chain)
if transactions:
chain_volume = sum(float(tx.get('value', 0)) / 1e18 for tx in transactions)
chain_activity[chain] = {
'transaction_count': len(transactions),
'volume': chain_volume,
'last_activity': max(int(tx['timeStamp']) for tx in transactions) if transactions else 0
}
total_transactions += len(transactions)
total_volume += chain_volume
# Determine primary chain
primary_chain = max(chain_activity.items(), key=lambda x: x[1]['volume'])[0] if chain_activity else None
return {
'chain_activity': chain_activity,
'total_transactions': total_transactions,
'total_volume': total_volume,
'primary_chain': primary_chain,
'active_chains': len(chain_activity)
}
except Exception as e:
print(f"Error analyzing cross-chain activity: {e}")
return {}
# Flask app
app = Flask(__name__)
CORS(app, origins=['http://localhost:3000', 'http://localhost:3001', 'http://127.0.0.1:3000', 'http://127.0.0.1:3001'])
logging.basicConfig(level=logging.INFO)
# --- Supabase Setup ---
from supabase import create_client, Client
SUPABASE_URL = os.getenv('SUPABASE_URL')
SUPABASE_KEY = os.getenv('SUPABASE_KEY')
supabase: Client = create_client(SUPABASE_URL, SUPABASE_KEY)
# --- Supabase Wallet Functions ---
def add_wallet_to_supabase(address, chain):
data = {"address": address, "chain": chain}
res = supabase.table("wallets").insert(data).execute()
return res.status_code == 201
def get_wallets_from_supabase():
res = supabase.table("wallets").select("*").execute()
return res.data if res.status_code == 200 else []
def delete_wallet_from_supabase(address):
res = supabase.table("wallets").delete().eq("address", address).execute()
return res.status_code == 200
# --- Flask API Endpoints for Wallet Tracking ---
@app.route('/api/wallets', methods=['GET'])
def api_get_wallets():
wallets = get_wallets_from_supabase()
return jsonify(wallets)
@app.route('/api/wallets', methods=['POST'])
def api_add_wallet():
data = request.json
address = data.get('address')
chain = data.get('chain', 'Base')
if not address:
return jsonify({"error": "Missing address"}), 400
success = add_wallet_to_supabase(address, chain)
return jsonify({"success": success}), (200 if success else 500)
@app.route('/api/wallets/<address>', methods=['DELETE'])
def api_delete_wallet(address):
success = delete_wallet_from_supabase(address)
return jsonify({"success": success}), (200 if success else 500)