-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
456 lines (387 loc) ยท 16.8 KB
/
server.js
File metadata and controls
456 lines (387 loc) ยท 16.8 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
const express = require('express');
const cors = require('cors');
const fetch = require('node-fetch');
const path = require('path');
const webpush = require('web-push');
const TelegramBot = require('node-telegram-bot-api');
require('dotenv').config();
const app = express();
const PORT = process.env.PORT || 3000;
// Middleware
app.use(cors());
app.use(express.json());
app.use(express.static('.'));
// Configure web push notifications
if (process.env.VAPID_PUBLIC_KEY && process.env.VAPID_PRIVATE_KEY) {
webpush.setVapidDetails(
process.env.VAPID_EMAIL || 'mailto:admin@ethduties.com',
process.env.VAPID_PUBLIC_KEY,
process.env.VAPID_PRIVATE_KEY
);
}
// Initialize Telegram bot if token is provided
let telegramBot = null;
if (process.env.TELEGRAM_BOT_TOKEN) {
telegramBot = new TelegramBot(process.env.TELEGRAM_BOT_TOKEN, { polling: true });
telegramBot.onText(/\/start/, (msg) => {
const chatId = msg.chat.id;
telegramBot.sendMessage(chatId,
'Welcome to ETH Duties Tracker! ๐\n\n' +
'Your chat ID is: `' + chatId + '`\n\n' +
'Add this chat ID to the webapp to receive notifications about your validator duties.',
{ parse_mode: 'Markdown' }
);
});
}
// Store for push subscriptions (in production, use a database)
const pushSubscriptions = new Map();
const telegramSubscriptions = new Map();
// Beacon chain API proxy endpoints
app.post('/api/beacon/*', async (req, res) => {
try {
const beaconUrl = req.body.beaconUrl || 'http://localhost:5052';
const apiPath = req.params[0];
// Include query parameters from the original request
const queryString = req.url.includes('?') ? req.url.split('?')[1] : '';
const fullUrl = `${beaconUrl}/${apiPath}${queryString ? '?' + queryString : ''}`;
const options = {
method: req.body.method || 'GET',
headers: {
'Content-Type': 'application/json',
}
};
if (req.body.data) {
options.body = JSON.stringify(req.body.data);
}
const response = await fetch(fullUrl, options);
const data = await response.json();
res.json(data);
} catch (error) {
console.error('Proxy error:', error);
res.status(500).json({ error: error.message });
}
});
// Get sync committee duties
app.post('/api/sync-duties', async (req, res) => {
try {
const { beaconUrl, validators, epoch } = req.body;
const validatorIndices = validators.filter(v => !v.startsWith('0x'));
// Sync committee assignments are stable for 256 epochs
const syncCommitteePeriod = Math.floor(epoch / 256);
const nextSyncPeriodFirstEpoch = (syncCommitteePeriod + 1) * 256;
// Fetch current sync committee
const currentResponse = await fetch(`${beaconUrl}/eth/v1/beacon/states/head/sync_committees`);
const currentData = await currentResponse.json();
// Fetch next sync committee using specific epoch
const nextResponse = await fetch(`${beaconUrl}/eth/v1/beacon/states/head/sync_committees?epoch=${nextSyncPeriodFirstEpoch}`);
const nextData = await nextResponse.json();
if (!currentData.data && !nextData.data) {
return res.json({ data: [] });
}
// Check which validators are in the current and next sync committees
const syncDuties = [];
const currentCommittee = currentData.data ? currentData.data.validators : [];
const nextCommittee = nextData.data ? nextData.data.validators : [];
validators.forEach(validator => {
const currentIndex = currentCommittee.indexOf(validator);
const nextIndex = nextCommittee.indexOf(validator);
if (currentIndex !== -1) {
syncDuties.push({
validator,
period: 'current',
committee_index: currentIndex,
until_epoch: (syncCommitteePeriod + 1) * 256
});
}
if (nextIndex !== -1) {
syncDuties.push({
validator,
period: 'next',
committee_index: nextIndex,
from_epoch: (syncCommitteePeriod + 1) * 256
});
}
});
res.json({ data: syncDuties });
} catch (error) {
console.error('Sync duties error:', error);
res.status(500).json({ error: error.message });
}
});
// Push notification subscription
app.post('/api/notifications/subscribe', (req, res) => {
const { subscription, validators } = req.body;
const key = subscription.endpoint;
pushSubscriptions.set(key, {
subscription,
validators
});
res.json({ success: true });
});
// Telegram notification subscription
app.post('/api/telegram/subscribe', (req, res) => {
const { chatId, validators } = req.body;
if (!telegramBot) {
return res.status(400).json({ error: 'Telegram bot not configured' });
}
telegramSubscriptions.set(chatId, validators);
const validatorList = validators.map(v => {
if (v.startsWith('0x')) {
return `${v.slice(0, 10)}...${v.slice(-8)}`;
}
return `[${v}](https://beaconcha.in/validator/${v})`;
}).join('\nโข ');
telegramBot.sendMessage(chatId,
`๐ Welcome to ETH Duties Tracker! ๐\n\n` +
`โ
Successfully subscribed to validator duty notifications!\n\n` +
`๐ Tracking ${validators.length} validator(s):\nโข ${validatorList}\n\n` +
`You'll receive notifications for:\n` +
`๐ฐ Block proposals\n` +
`๐ Attestations\n` +
`๐ Sync committee duties\n\n` +
`โ๏ธ`,
{
parse_mode: 'Markdown',
disable_web_page_preview: true
}
);
res.json({ success: true });
});
// Update Telegram subscription (silent update when validators change)
app.post('/api/telegram/update', async (req, res) => {
const { chatId, validators, isNewValidator, newValidatorOnly } = req.body;
if (!telegramBot) {
return res.status(400).json({ error: 'Telegram bot not configured' });
}
const oldValidators = telegramSubscriptions.get(chatId) || [];
// If this is a new validator only notification, handle it specially
if (isNewValidator && newValidatorOnly) {
// Update the subscription first
telegramSubscriptions.set(chatId, validators);
// Only send notification for the new validator
let validatorDisplay;
if (newValidatorOnly.startsWith('0x')) {
// Try to fetch validator index for pubkey
try {
const beaconUrl = req.body.beaconUrl || 'http://localhost:5052';
const response = await fetch(`${beaconUrl}/eth/v1/beacon/states/head/validators/${newValidatorOnly}`);
if (response.ok) {
const data = await response.json();
if (data.data && data.data.index) {
validatorDisplay = `[${data.data.index}](https://beaconcha.in/validator/${data.data.index}) (${newValidatorOnly.slice(0, 10)}...${newValidatorOnly.slice(-4)})`;
}
}
} catch (error) {
console.error('Error fetching validator info:', error);
}
if (!validatorDisplay) {
validatorDisplay = `${newValidatorOnly.slice(0, 10)}...${newValidatorOnly.slice(-4)}`;
}
} else {
validatorDisplay = `[${newValidatorOnly}](https://beaconcha.in/validator/${newValidatorOnly})`;
}
const message = `๐ Subscription Updated\n\nโ Added:\nโข ${validatorDisplay}\n\nTotal validators tracked: ${validators.length}`;
try {
await telegramBot.sendMessage(chatId, message, {
parse_mode: 'Markdown',
disable_web_page_preview: true
});
res.json({ success: true });
} catch (error) {
console.error('Telegram update error:', error);
res.status(500).json({ error: error.message });
}
return;
}
// Normal update flow
// Determine what changed BEFORE updating the subscription
const added = validators.filter(v => !oldValidators.includes(v));
const removed = oldValidators.filter(v => !validators.includes(v));
// Now update the subscription
telegramSubscriptions.set(chatId, validators);
if (added.length === 0 && removed.length === 0) {
return res.json({ success: true, message: 'No changes' });
}
let message = '๐ Subscription Updated\n\n';
if (added.length > 0) {
const addedList = await Promise.all(added.map(async v => {
if (v.startsWith('0x')) {
// Try to fetch validator index for pubkey
try {
const beaconUrl = req.body.beaconUrl || 'http://localhost:5052';
const response = await fetch(`${beaconUrl}/eth/v1/beacon/states/head/validators/${v}`);
if (response.ok) {
const data = await response.json();
if (data.data && data.data.index) {
return `[${data.data.index}](https://beaconcha.in/validator/${data.data.index}) (${v.slice(0, 10)}...${v.slice(-4)})`;
}
}
} catch (error) {
console.error('Error fetching validator info:', error);
}
return `${v.slice(0, 10)}...${v.slice(-4)}`;
}
return `[${v}](https://beaconcha.in/validator/${v})`;
}));
message += `โ Added:\nโข ${addedList.join('\nโข ')}\n\n`;
}
if (removed.length > 0) {
const removedList = removed.map(v => {
if (v.startsWith('0x')) {
return `${v.slice(0, 10)}...${v.slice(-8)}`;
}
return `${v}`;
}).join('\nโข ');
message += `โ Removed:\nโข ${removedList}\n\n`;
}
message += `Total validators tracked: ${validators.length}`;
try {
await telegramBot.sendMessage(chatId, message, {
parse_mode: 'Markdown',
disable_web_page_preview: true
});
res.json({ success: true });
} catch (error) {
console.error('Telegram update error:', error);
res.status(500).json({ error: error.message });
}
});
// Notification settings update
app.post('/api/telegram/settings-update', async (req, res) => {
const { chatId, settings } = req.body;
if (!telegramBot) {
return res.status(400).json({ error: 'Telegram bot not configured' });
}
try {
let message = 'โ๏ธ Notification Settings Updated\n\n';
const duties = [];
if (settings.notifyProposer) duties.push('๐ฐ Block proposals');
if (settings.notifyAttester) duties.push('๐ Attestations');
if (settings.notifySync) duties.push('๐ Sync committee');
if (duties.length > 0) {
message += `Notifications enabled for:\n${duties.join('\n')}\n\n`;
message += `โฐ Alert timing: ${settings.notifyMinutes} minutes before duty`;
} else {
message += '๐ All notifications disabled';
}
await telegramBot.sendMessage(chatId, message, {
parse_mode: 'Markdown',
disable_web_page_preview: true
});
res.json({ success: true });
} catch (error) {
console.error('Settings update notification error:', error);
res.status(500).json({ error: error.message });
}
});
// Send Telegram notification directly
app.post('/api/notify/telegram', async (req, res) => {
const { chatId, message } = req.body;
if (!telegramBot) {
return res.status(400).json({ error: 'Telegram bot not configured' });
}
try {
// Parse validator index from message and create clickable link
let formattedMessage = message;
const validatorMatch = message.match(/Validator #(\d+)/);
if (validatorMatch) {
const validatorIndex = validatorMatch[1];
// Use Markdown format for clickable link
formattedMessage = message.replace(
`Validator #${validatorIndex}`,
`Validator [#${validatorIndex}](https://beaconcha.in/validator/${validatorIndex})`
);
}
await telegramBot.sendMessage(chatId, formattedMessage, {
parse_mode: 'Markdown',
disable_web_page_preview: true
});
res.json({ success: true });
} catch (error) {
console.error('Telegram notification error:', error);
res.status(500).json({ error: error.message });
}
});
// Send notification endpoint
app.post('/api/notify', async (req, res) => {
const { type, validator, validatorDisplay, duty, urgency } = req.body;
console.log('Received notification request:', { type, validator, validatorDisplay });
// Send push notifications
let notificationsSent = 0;
console.log(`Checking ${pushSubscriptions.size} push subscriptions`);
for (const [key, data] of pushSubscriptions.entries()) {
console.log('Checking subscription validators:', data.validators, 'against validator:', validator, 'type:', typeof validator);
// Check if this subscription includes the validator (handle both string and number)
const validatorStr = validator.toString();
const validatorNum = parseInt(validator);
const hasValidator = data.validators.some(v =>
v === validator ||
v === validatorStr ||
v === validatorNum ||
v.toString() === validatorStr
);
if (hasValidator) {
console.log('Found matching subscription!');
// Create notification with new format matching Telegram style
let title, body;
if (type === 'Proposer') {
title = '๐๐ฐ BLOCK PROPOSAL! ๐๐ฐ';
body = `Validator ${validatorDisplay || validator} - ${duty.timeUntil}`;
} else if (type === 'Attester') {
title = '๐ Attestation Duty';
body = `Validator ${validatorDisplay || validator} - ${duty.timeUntil}`;
} else if (type === 'Sync Committee') {
title = '๐๐ SYNC COMMITTEE ๐๐';
body = `Validator ${validatorDisplay || validator} - Active now`;
} else if (type === 'Next Sync Committee') {
title = '๐ฎ๐ NEXT SYNC COMMITTEE ๐๐ฎ';
body = `Validator ${validatorDisplay || validator} - Starting ${duty.timeUntil}`;
} else if (type === 'Block Confirmed' && duty.blockDetails) {
title = '๐๐ฐ BLOCK CONFIRMED! ๐๐ฐ';
const details = duty.blockDetails;
body = `${validatorDisplay || validator} - ${details.totalReward.toFixed(3)} ETH earned! (${details.txCount} txs)`;
} else {
title = `${type} Duty`;
body = `Validator ${validatorDisplay || validator} - ${duty.timeUntil}`;
}
const payload = JSON.stringify({
title,
body,
icon: '/icon-192.png',
badge: '/badge-72.png',
data: { duty, urgency }
});
try {
await webpush.sendNotification(data.subscription, payload);
notificationsSent++;
console.log('Push notification sent successfully');
} catch (error) {
console.error('Push notification error:', error);
pushSubscriptions.delete(key);
}
}
}
console.log(`Sent ${notificationsSent} push notifications`);
// Note: Telegram notifications are now sent directly via /api/notify/telegram
// to avoid duplicate notifications
res.json({ success: true });
});
// Get VAPID public key for push notifications
app.get('/api/vapid-public-key', (req, res) => {
res.json({ publicKey: process.env.VAPID_PUBLIC_KEY || '' });
});
// Health check endpoint
app.get('/health', (_, res) => {
res.status(200).json({
status: 'ok',
timestamp: new Date().toISOString(),
uptime: process.uptime(),
telegram: !!telegramBot
});
});
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
if (telegramBot) {
console.log('Telegram bot is active');
}
});