-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmonitor.js
More file actions
263 lines (218 loc) · 8.88 KB
/
Copy pathmonitor.js
File metadata and controls
263 lines (218 loc) · 8.88 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
const { ethers } = require('ethers');
const axios = require('axios');
const cron = require('node-cron');
require('dotenv').config();
class BotMonitor {
constructor() {
this.provider = new ethers.providers.JsonRpcProvider(process.env.RPC_URL || 'https://arb1.arbitrum.io/rpc');
this.wallet = process.env.BOT_PRIVATE_KEY ? new ethers.Wallet(process.env.BOT_PRIVATE_KEY, this.provider) : null;
this.alerts = {
lowBalance: false,
highGas: false,
noActivity: false,
errors: []
};
this.stats = {
startTime: Date.now(),
settlements: 0,
totalProfit: ethers.BigNumber.from(0),
gasSpent: ethers.BigNumber.from(0),
lastActivity: Date.now()
};
this.thresholds = {
MIN_BALANCE: ethers.utils.parseEther('0.005'), // 0.005 ETH
MAX_GAS_PRICE: ethers.utils.parseUnits('0.5', 'gwei'), // 0.5 gwei
INACTIVITY_MINUTES: 30,
ERROR_THRESHOLD: 5
};
}
async checkWalletBalance() {
if (!this.wallet) return;
const balance = await this.wallet.getBalance();
const balanceETH = parseFloat(ethers.utils.formatEther(balance));
console.log(`Wallet Balance: ${balanceETH.toFixed(6)} ETH`);
if (balance.lt(this.thresholds.MIN_BALANCE)) {
if (!this.alerts.lowBalance) {
this.alerts.lowBalance = true;
await this.sendAlert('🚨 LOW BALANCE ALERT', `Wallet balance is ${balanceETH.toFixed(6)} ETH. Refill needed!`, 'error');
}
} else {
this.alerts.lowBalance = false;
}
return balanceETH;
}
async checkGasPrice() {
const gasPrice = await this.provider.getGasPrice();
const gasPriceGwei = parseFloat(ethers.utils.formatUnits(gasPrice, 'gwei'));
console.log(`Current Gas Price: ${gasPriceGwei.toFixed(3)} gwei`);
if (gasPrice.gt(this.thresholds.MAX_GAS_PRICE)) {
if (!this.alerts.highGas) {
this.alerts.highGas = true;
await this.sendAlert('⚠️ HIGH GAS ALERT', `Gas price is ${gasPriceGwei.toFixed(3)} gwei`, 'warning');
}
} else {
this.alerts.highGas = false;
}
return gasPriceGwei;
}
async checkBotActivity() {
// Check if bot log file exists and read recent activity
const fs = require('fs');
const path = require('path');
const logPath = path.join(__dirname, 'bot.log');
if (fs.existsSync(logPath)) {
const stats = fs.statSync(logPath);
const lastModified = stats.mtime;
const minutesSinceActivity = (Date.now() - lastModified) / 1000 / 60;
console.log(`Last bot activity: ${minutesSinceActivity.toFixed(1)} minutes ago`);
if (minutesSinceActivity > this.thresholds.INACTIVITY_MINUTES) {
if (!this.alerts.noActivity) {
this.alerts.noActivity = true;
await this.sendAlert(
'⏰ INACTIVITY ALERT',
`No bot activity for ${minutesSinceActivity.toFixed(0)} minutes`,
'warning'
);
}
} else {
this.alerts.noActivity = false;
}
// Parse recent settlements from log
try {
const logs = fs.readFileSync(logPath, 'utf8').split('\n').slice(-100);
const settlements = logs.filter(line => line.includes('Settlement complete')).length;
console.log(`Recent settlements: ${settlements}`);
} catch (error) {
console.error('Error reading log file:', error.message);
}
}
}
async checkOracleStatus() {
const ORACLE_ADDRESS = '0xa935db8cb0f45256e3df77cbff1980cf7aeffbe4';
const ORACLE_ABI = ["function nextReportId() view returns (uint256)"];
const oracle = new ethers.Contract(ORACLE_ADDRESS, ORACLE_ABI, this.provider);
try {
const nextId = await oracle.nextReportId();
console.log(`Oracle Next Report ID: ${nextId}`);
return nextId.toNumber();
} catch (error) {
console.error('Error checking oracle:', error.message);
this.alerts.errors.push('Oracle check failed');
return 0;
}
}
async checkSystemHealth() {
console.log('\n=== SYSTEM HEALTH CHECK ===');
console.log(`Timestamp: ${new Date().toISOString()}`);
const [balance, gasPrice, nextReportId] = await Promise.all([
this.checkWalletBalance(),
this.checkGasPrice(),
this.checkOracleStatus()
]);
await this.checkBotActivity();
// Calculate uptime
const uptimeHours = (Date.now() - this.stats.startTime) / 1000 / 60 / 60;
console.log(`Monitor Uptime: ${uptimeHours.toFixed(2)} hours`);
// Error threshold check
if (this.alerts.errors.length > this.thresholds.ERROR_THRESHOLD) {
await this.sendAlert(
'🔥 CRITICAL ERROR THRESHOLD',
`${this.alerts.errors.length} errors detected`,
'critical'
);
this.alerts.errors = []; // Reset after alert
}
console.log('===========================\n');
return {
healthy: !this.alerts.lowBalance && !this.alerts.highGas && !this.alerts.noActivity,
balance,
gasPrice,
nextReportId,
uptime: uptimeHours
};
}
async sendAlert(title, message, severity = 'info') {
const webhook = process.env.DISCORD_WEBHOOK;
if (!webhook) return;
const colors = {
info: 0x3498db,
warning: 0xf39c12,
error: 0xe74c3c,
critical: 0x9b59b6
};
try {
await axios.post(webhook, {
embeds: [{
title,
description: message,
color: colors[severity],
timestamp: new Date().toISOString(),
footer: {
text: 'OpenOracle Settlement Bot Monitor'
}
}]
});
} catch (error) {
console.error('Failed to send Discord alert:', error.message);
}
}
async generateReport() {
const health = await this.checkSystemHealth();
const report = {
timestamp: new Date().toISOString(),
health: health.healthy ? 'HEALTHY' : 'ISSUES DETECTED',
metrics: {
walletBalance: `${health.balance.toFixed(6)} ETH`,
gasPrice: `${health.gasPrice.toFixed(3)} gwei`,
nextReportId: health.nextReportId,
uptime: `${health.uptime.toFixed(2)} hours`
},
alerts: {
lowBalance: this.alerts.lowBalance,
highGas: this.alerts.highGas,
noActivity: this.alerts.noActivity,
errorCount: this.alerts.errors.length
}
};
// Save report
const fs = require('fs');
const reportPath = `./reports/health-${Date.now()}.json`;
if (!fs.existsSync('./reports')) {
fs.mkdirSync('./reports');
}
fs.writeFileSync(reportPath, JSON.stringify(report, null, 2));
console.log(`Health report saved: ${reportPath}`);
return report;
}
start() {
console.log('Starting bot monitor...');
// Initial check
this.checkSystemHealth();
// Schedule periodic checks
cron.schedule('*/5 * * * *', () => {
console.log('Running scheduled health check...');
this.checkSystemHealth();
});
// Generate hourly reports
cron.schedule('0 * * * *', () => {
console.log('Generating hourly report...');
this.generateReport();
});
// Daily summary
cron.schedule('0 0 * * *', async () => {
const report = await this.generateReport();
await this.sendAlert(
'📊 Daily Summary',
`Health: ${report.health}\nBalance: ${report.metrics.walletBalance}\nUptime: ${report.metrics.uptime}`,
'info'
);
});
console.log('Monitor is running. Press Ctrl+C to stop.');
}
}
// Start monitor
if (require.main === module) {
const monitor = new BotMonitor();
monitor.start();
}
module.exports = { BotMonitor };