-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreport_balance.py
192 lines (159 loc) · 5.07 KB
/
report_balance.py
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
import sqlite3
from datetime import datetime
import yagmail
import os
from dotenv import load_dotenv
import json
from tabulate import tabulate
from config import DB_NAME
# Load environment variables
load_dotenv()
# Email settings
EMAIL_USER = os.getenv('EMAIL_USER')
EMAIL_PASSWORD = os.getenv('EMAIL_PASSWORD')
EMAIL_TO = os.getenv('EMAIL_TO')
BALANCE_THRESHOLD = float(os.getenv('BALANCE_THRESHOLD', '0.1'))
# Chain settings
CHAINS = {
'ethereum': {
'name': 'Ethereum Mainnet',
'symbol': 'ETH'
},
'avalanche': {
'name': 'Avalanche C-Chain',
'symbol': 'AVAX'
},
'base': {
'name': 'Base Chain',
'symbol': 'ETH'
},
'bsc': {
'name': 'BNB Smart Chain',
'symbol': 'BNB'
},
'polygon': {
'name': 'Polygon',
'symbol': 'MATIC'
},
'arbitrum': {
'name': 'Arbitrum One',
'symbol': 'ETH'
}
}
def setup_database():
"""Set up database tables"""
conn = sqlite3.connect(DB_NAME)
cursor = conn.cursor()
# Balance history table
cursor.execute('''
CREATE TABLE IF NOT EXISTS balance_history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
address TEXT,
chain_id TEXT,
balance REAL,
check_date TIMESTAMP,
UNIQUE(address, chain_id, check_date)
)
''')
conn.commit()
conn.close()
def format_datetime(dt):
"""Convert datetime to readable format"""
if isinstance(dt, str):
try:
dt = datetime.fromisoformat(dt)
except:
return dt
return dt.strftime('%Y-%m-%d %H:%M:%S')
def get_high_balance_accounts():
"""Get accounts with balance above threshold"""
conn = sqlite3.connect(DB_NAME)
cursor = conn.cursor()
# Get latest check date
cursor.execute('SELECT MAX(check_date) FROM balance_history')
latest_date = cursor.fetchone()[0]
if not latest_date:
return []
# Get accounts with balance above threshold
cursor.execute('''
SELECT
b.address,
b.chain_id,
b.balance,
a.private_key,
a.chains_with_transactions
FROM balance_history b
JOIN active_addresses a ON b.address = a.address
WHERE b.check_date = ? AND b.balance >= ?
ORDER BY b.balance DESC
''', (latest_date, BALANCE_THRESHOLD))
high_balance_accounts = cursor.fetchall()
conn.close()
return high_balance_accounts, latest_date
def create_report_content(accounts, check_date):
"""Create email report content"""
if not accounts:
return f"No accounts found with balance above threshold ({BALANCE_THRESHOLD})"
content = [f"Balance Report ({format_datetime(check_date)})\n"]
content.append(f"Balance Threshold: {BALANCE_THRESHOLD}\n")
# Account information in table format
headers = ["Address", "Private Key", "Chain", "Balance", "Active Chains"]
table_data = []
for addr, chain_id, balance, private_key, chains in accounts:
chains_list = json.loads(chains)
table_data.append([
addr,
private_key,
CHAINS[chain_id]['name'],
f"{balance:.8f} {CHAINS[chain_id]['symbol']}",
", ".join(chains_list)
])
content.append(tabulate(table_data, headers=headers, tablefmt="grid"))
# Calculate total balance by chain
chain_totals = {}
for _, chain_id, balance, _, _ in accounts:
if chain_id not in chain_totals:
chain_totals[chain_id] = 0
chain_totals[chain_id] += balance
content.append("\n=== Total Balance by Chain ===")
for chain_id, total in chain_totals.items():
content.append(f"{CHAINS[chain_id]['name']}: {total:.8f} {CHAINS[chain_id]['symbol']}")
return "\n".join(content)
def send_email_report(content):
"""Send email report"""
if not all([EMAIL_USER, EMAIL_PASSWORD, EMAIL_TO]):
raise ValueError("Incomplete email settings. Please check your .env file.")
subject = f"Ethereum Key Search Report - {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
try:
# Initialize email client
yag = yagmail.SMTP(EMAIL_USER, EMAIL_PASSWORD)
# Send email
yag.send(
to=EMAIL_TO,
subject=subject,
contents=content
)
print("Email report sent successfully")
except Exception as e:
print(f"Email sending error: {str(e)}")
finally:
try:
yag.close()
except:
pass
def main():
"""Main execution function"""
try:
setup_database()
# Get high balance accounts
accounts, check_date = get_high_balance_accounts()
# Create report content
report_content = create_report_content(accounts, check_date)
if accounts: # Only send email if accounts found
send_email_report(report_content)
else:
print(report_content)
except Exception as e:
print(f"An error occurred: {str(e)}")
if __name__ == "__main__":
main()