-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmainnet-bridge-per-epoch.js
More file actions
650 lines (547 loc) Β· 29.6 KB
/
mainnet-bridge-per-epoch.js
File metadata and controls
650 lines (547 loc) Β· 29.6 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
#!/usr/bin/env node
/**
* Enhanced PoCW Subnet to Mainnet Bridge - Per-Epoch Submission
*
* This module handles real-time epoch submission to mainnet as each epoch
* completes (every 3 rounds), rather than batching all epochs at the end.
*
* Architecture:
* 1. Integrates with the Go subnet system via callback mechanism
* 2. Submits each epoch immediately when EpochFinalized event occurs
* 3. Provides real-time KEY token mining per completed epoch
* 4. Maintains epoch tracking and statistics
*/
const { ethers } = require('ethers');
const { spawn } = require('child_process');
const fs = require('fs').promises;
const path = require('path');
const http = require('http');
const url = require('url');
class PerEpochMainnetBridge {
constructor() {
this.provider = null;
this.contracts = {};
this.wallets = {};
this.subnetProcess = null;
this.epochSubmissions = new Map(); // Track submitted epochs
this.httpServer = null;
// Network configuration
this.RPC_URL = "http://localhost:8545";
this.DGRAPH_URL = "http://localhost:8080";
// Account configuration
this.accounts = {
deployer: {
address: "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266",
privateKey: "0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80"
},
validator1: {
address: "0x70997970C51812dc3A010C7d01b50e0d17dc79C8",
privateKey: "0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d"
},
miner: {
address: "0x9965507D1a55bcC2695C58ba16FB37d819B0A4dc",
privateKey: "0x8b3a350cf5c34c9194ca85829a2df0ec3153be0318b5e2d3348e872092edffba"
}
};
}
async initialize() {
console.log("π Per-Epoch PoCW Mainnet Bridge Initializing...");
console.log("βββββββββββββββββββββββββββββββββββββββββββββββ");
// Initialize ethers provider
this.provider = new ethers.JsonRpcProvider(this.RPC_URL);
// Create wallets
this.wallets.validator1 = new ethers.Wallet(this.accounts.validator1.privateKey, this.provider);
this.wallets.miner = new ethers.Wallet(this.accounts.miner.privateKey, this.provider);
// Load contract addresses and ABIs
await this.loadContracts();
// Start HTTP server for Go integration
await this.startHttpServer();
console.log("β
Bridge initialized successfully!");
console.log(`π Validator-1: ${this.accounts.validator1.address}`);
console.log(`βοΈ Miner: ${this.accounts.miner.address}`);
}
async loadContracts() {
try {
// Load contract addresses
const addressesPath = path.join(__dirname, 'contract_addresses.json');
const addressesData = await fs.readFile(addressesPath, 'utf8');
const addresses = JSON.parse(addressesData);
// Find contract addresses by searching for known patterns
let hetuAddress, keyAddress, registryAddress, verifierAddress;
for (const [address, name] of Object.entries(addresses)) {
if (name.includes('HETU Token')) hetuAddress = address;
else if (name.includes('Intelligence Token') || name.includes('KEY')) keyAddress = address;
else if (name.includes('Subnet Registry')) registryAddress = address;
else if (name.includes('Enhanced PoCW') || name.includes('Verifier')) verifierAddress = address;
}
if (!hetuAddress || !keyAddress || !registryAddress || !verifierAddress) {
throw new Error('Could not find all required contract addresses');
}
// Load ABIs
const verifierABI = [
"function submitAndDistributeEpoch(string memory subnetId, bytes memory vlcGraphData, address[] memory successfulMiners, uint256 successfulTasks, uint256 failedTasks) external",
"function getMinerStats(address miner) external view returns (tuple(address owner, uint256 successfulTasks, uint256 totalTasks, uint256 totalIntelligenceMined, uint256 reputationScore, uint256 lastActiveEpoch, uint256 joinedTimestamp, bool isActive))",
"function subnetIdToHash(string memory subnetId) external view returns (bytes32)"
];
const keyABI = [
"function balanceOf(address account) external view returns (uint256)",
"function totalSupply() external view returns (uint256)"
];
// Create contract instances
this.contracts.verifier = new ethers.Contract(verifierAddress, verifierABI, this.wallets.validator1);
this.contracts.key = new ethers.Contract(keyAddress, keyABI, this.provider);
console.log(`π Loaded contracts:`);
console.log(` EnhancedPoCWVerifier: ${verifierAddress}`);
console.log(` KEY Token: ${keyAddress}`);
} catch (error) {
throw new Error(`Failed to load contracts: ${error.message}`);
}
}
// Callback function to handle epoch finalized events from the Go subnet
async handleEpochFinalized(epochNumber, subnetId, epochData) {
try {
console.log(`\nπ EPOCH ${epochNumber} FINALIZED - IMMEDIATE MAINNET SUBMISSION`);
console.log("βββββββββββββββββββββββββββββββββββββββββββββββ");
console.log(`π Subnet: ${subnetId}`);
console.log(`π Epoch: ${epochNumber}`);
console.log(`π Completed Rounds: ${epochData.CompletedRounds.length}`);
console.log(`β° VLC Clock State:`, epochData.VLCClockState);
// Check if already submitted (prevent duplicates)
const epochKey = `${subnetId}-${epochNumber}`;
if (this.epochSubmissions.has(epochKey)) {
console.log(`β οΈ Epoch ${epochNumber} already submitted, skipping...`);
return;
}
// Extract current epoch data from Dgraph
const { vlcGraphData, successfulTasks, failedTasks, miners } = await this.extractCurrentEpochData(subnetId, epochNumber);
// Submit to mainnet
const result = await this.submitEpochToMainnet(subnetId, vlcGraphData, miners, successfulTasks, failedTasks);
// Mark as submitted
this.epochSubmissions.set(epochKey, {
epochNumber,
subnetId,
txHash: result.txHash,
blockNumber: result.blockNumber,
keyMined: result.keyMined,
timestamp: Date.now()
});
console.log(`β
Epoch ${epochNumber} submitted successfully!`);
console.log(`π° KEY Mined: ${result.keyMined} KEY tokens`);
console.log(`π€ Transaction: ${result.txHash}`);
console.log(`π¦ Block: ${result.blockNumber}`);
} catch (error) {
console.error(`β Failed to submit epoch ${epochNumber}:`, error.message);
}
}
// Extract VLC data for the current completed epoch
async extractCurrentEpochData(subnetId, epochNumber) {
try {
console.log(`π Extracting VLC data for epoch ${epochNumber}...`);
// Query Dgraph for events from this specific epoch
const query = `
{
events(func: has(event_id)) @filter(eq(subnet_id, "${subnetId}")) {
uid
event_id
event_name
event_type
vlc_clock
parents {
uid
event_id
}
timestamp
description
request_id
}
}`;
const response = await fetch(`${this.DGRAPH_URL}/query`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ query })
});
if (!response.ok) {
throw new Error('Failed to query Dgraph');
}
const data = await response.json();
const events = data.data.events || [];
console.log(`β
Extracted ${events.length} events from Dgraph`);
// Filter events for current epoch (rough estimation based on timing or event patterns)
// In a real implementation, you would track epoch boundaries more precisely
const epochEvents = this.filterEventsForCurrentEpoch(events, epochNumber);
// Count successful and failed tasks from the epoch
const { successfulTasks, failedTasks } = this.analyzeEpochTasks(epochEvents);
// Generate comprehensive VLC graph data for this epoch
const vlcGraphData = this.generateEpochVLCData(subnetId, epochNumber, epochEvents, successfulTasks, failedTasks);
console.log(`π Epoch ${epochNumber}: ${successfulTasks} successful, ${failedTasks} failed tasks`);
return {
vlcGraphData,
successfulTasks,
failedTasks,
miners: [this.accounts.miner.address]
};
} catch (error) {
console.error("β Error extracting epoch data:", error.message);
// Fallback to simulated data for this epoch
return this.generateSimulatedEpochData(subnetId, epochNumber);
}
}
// Filter events that belong to the current epoch
filterEventsForCurrentEpoch(events, epochNumber) {
// For simplicity, assume the most recent events belong to the current epoch
// In a production system, you would have explicit epoch boundaries
const eventsPerEpoch = 10; // Approximate events per epoch (3 rounds * ~3 events per round + epoch events)
const startIndex = Math.max(0, events.length - (eventsPerEpoch * (4 - epochNumber)));
const endIndex = events.length - (eventsPerEpoch * (3 - epochNumber));
return events.slice(startIndex, Math.min(endIndex, events.length));
}
// Analyze epoch events to count successful/failed tasks
analyzeEpochTasks(epochEvents) {
const successfulTasks = epochEvents.filter(e =>
e.event_name === 'RoundSuccess' ||
e.description?.includes('OUTPUT DELIVERED TO USER')
).length;
const failedTasks = epochEvents.filter(e =>
e.event_name === 'RoundFailed' ||
e.description?.includes('OUTPUT REJECTED')
).length;
return { successfulTasks, failedTasks };
}
// Generate VLC graph data for a specific epoch
generateEpochVLCData(subnetId, epochNumber, epochEvents, successfulTasks, failedTasks) {
return {
subnetId,
epochNumber,
events: epochEvents.map(event => ({
id: event.event_id || `epoch_${epochNumber}_${event.uid}`,
name: event.event_name || 'Unknown',
vlcClock: event.vlc_clock || {},
parents: (event.parents || []).map(p => p.event_id || p.uid),
timestamp: event.timestamp || Date.now(),
description: event.description || `Epoch ${epochNumber} event`,
requestId: event.request_id || null
})),
miners: [this.accounts.miner.address],
validators: [
this.accounts.validator1.address,
"0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC",
"0x90F79bf6EB2c4f870365E785982E1f101E93b906",
"0x15d34AAf54267DB7D7c367839AAf71A00a2C6A65"
],
summary: {
epochNumber,
totalTasks: successfulTasks + failedTasks,
successfulTasks,
failedTasks,
validationStatus: "complete",
consensusReached: true
},
statistics: {
epochProcessingTime: 7500, // 3 rounds * ~2500ms per round
eventsInEpoch: epochEvents.length,
avgEventsPerRound: epochEvents.length / 3
}
};
}
// Generate simulated epoch data as fallback
generateSimulatedEpochData(subnetId, epochNumber) {
console.log(`π Generating simulated data for epoch ${epochNumber}...`);
const currentTime = Date.now();
const events = [];
// Simulate 3 rounds (1 per round for this epoch)
const tasksInEpoch = 1; // Typically 1 task per epoch in our 7-task demo
for (let round = 1; round <= 3; round++) {
const baseTime = currentTime - (3000 - round * 1000);
const globalTaskId = (epochNumber - 1) * 1 + 1; // Map to global task sequence
if (globalTaskId <= 7) { // Only if within our 7-task demo
// User input
events.push({
id: `user_input_epoch_${epochNumber}_round_${round}`,
name: "UserInput",
vlcClock: { 1: globalTaskId-1, 2: globalTaskId },
parents: events.length > 0 ? [events[events.length-1].id] : [],
timestamp: baseTime,
description: `Epoch ${epochNumber} Round ${round}: User submits task`,
requestId: `req-${subnetId}-${globalTaskId}`
});
// Miner output
events.push({
id: `miner_output_epoch_${epochNumber}_round_${round}`,
name: "MinerOutput",
vlcClock: { 1: globalTaskId, 2: globalTaskId },
parents: [`user_input_epoch_${epochNumber}_round_${round}`],
timestamp: baseTime + 500,
description: `Epoch ${epochNumber} Round ${round}: Miner provides solution`,
requestId: `req-${subnetId}-${globalTaskId}`
});
// Round success
events.push({
id: `round_${epochNumber}_${round}_complete`,
name: "RoundSuccess",
vlcClock: { 1: globalTaskId, 2: globalTaskId + 1 },
parents: [`miner_output_epoch_${epochNumber}_round_${round}`],
timestamp: baseTime + 1000,
description: `Epoch ${epochNumber} Round ${round}: OUTPUT DELIVERED TO USER`,
requestId: `req-${subnetId}-${globalTaskId}`
});
}
}
const vlcGraphData = this.generateEpochVLCData(subnetId, epochNumber, events, 1, 0);
return {
vlcGraphData,
successfulTasks: 1,
failedTasks: 0,
miners: [this.accounts.miner.address]
};
}
// Submit epoch data to mainnet
async submitEpochToMainnet(subnetId, vlcGraphData, miners, successfulTasks, failedTasks) {
console.log(`\nβ‘ Submitting epoch ${vlcGraphData.epochNumber} to mainnet...`);
console.log("βββββββββββββββββββββββββββββββββββββββββββββββ");
// Convert VLC data to bytes
const vlcDataString = JSON.stringify(vlcGraphData);
const vlcDataBytes = ethers.toUtf8Bytes(vlcDataString);
console.log(`π Submitting epoch data:`);
console.log(` Subnet: ${subnetId}`);
console.log(` Epoch: ${vlcGraphData.epochNumber}`);
console.log(` Tasks: ${successfulTasks} successful, ${failedTasks} failed`);
console.log(` VLC Events: ${vlcGraphData.events.length}`);
console.log(` Data Size: ${vlcDataBytes.length} bytes`);
// Get pre-submission balances
const minerBalanceBefore = await this.contracts.key.balanceOf(this.accounts.miner.address);
const validator1BalanceBefore = await this.contracts.key.balanceOf(this.accounts.validator1.address);
try {
// Submit epoch and mine KEY tokens
console.log(`\nπ Validator-1 posting epoch ${vlcGraphData.epochNumber} to mainnet...`);
const tx = await this.contracts.verifier.submitAndDistributeEpoch(
vlcGraphData.subnetId,
vlcDataBytes,
miners,
successfulTasks,
failedTasks
);
console.log(`π€ Transaction submitted: ${tx.hash}`);
console.log("β³ Waiting for confirmation...");
const receipt = await tx.wait();
console.log(`β
Transaction confirmed in block: ${receipt.blockNumber}`);
// Check post-submission balances
const minerBalanceAfter = await this.contracts.key.balanceOf(this.accounts.miner.address);
const validator1BalanceAfter = await this.contracts.key.balanceOf(this.accounts.validator1.address);
const minerEarned = ethers.formatEther(minerBalanceAfter - minerBalanceBefore);
const validator1Earned = ethers.formatEther(validator1BalanceAfter - validator1BalanceBefore);
const totalMined = ethers.formatEther((minerBalanceAfter - minerBalanceBefore) + (validator1BalanceAfter - validator1BalanceBefore));
console.log(`\nπ EPOCH ${vlcGraphData.epochNumber} KEY MINING COMPLETE!`);
console.log("βββββββββββββββββββββββββββββββββββββββββββββββ");
console.log(`π° Miner earned: ${minerEarned} KEY`);
console.log(`π Validator-1 earned: ${validator1Earned} KEY`);
console.log(`π Total KEY mined: ${totalMined} KEY`);
return {
txHash: tx.hash,
blockNumber: receipt.blockNumber,
keyMined: totalMined,
gasUsed: receipt.gasUsed.toString()
};
} catch (error) {
console.error(`β Epoch submission failed: ${error.message}`);
throw error;
}
}
// Get summary of all submitted epochs
getSubmissionSummary() {
console.log(`\nπ EPOCH SUBMISSION SUMMARY`);
console.log("βββββββββββββββββββββββββββββββββββββββββββββββ");
console.log(`π Total Epochs Submitted: ${this.epochSubmissions.size}`);
let totalKeyMined = 0;
for (const [epochKey, submission] of this.epochSubmissions.entries()) {
console.log(` Epoch ${submission.epochNumber}: ${submission.keyMined} KEY (tx: ${submission.txHash.substring(0, 10)}...)`);
totalKeyMined += parseFloat(submission.keyMined);
}
console.log(`π° Total KEY Mined: ${totalKeyMined} KEY across all epochs`);
console.log("βββββββββββββββββββββββββββββββββββββββββββββββ");
}
// Start HTTP server to receive epoch data from Go
async startHttpServer() {
const PORT = 3001;
this.httpServer = http.createServer((req, res) => {
// Handle CORS
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
if (req.method === 'OPTIONS') {
res.writeHead(200);
res.end();
return;
}
const parsedUrl = url.parse(req.url, true);
if (req.method === 'POST' && parsedUrl.pathname === '/submit-epoch') {
this.handleEpochSubmission(req, res);
} else if (req.method === 'GET' && parsedUrl.pathname === '/health') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ status: 'healthy', service: 'per-epoch-bridge' }));
} else {
res.writeHead(404, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Not Found' }));
}
});
return new Promise((resolve, reject) => {
this.httpServer.listen(PORT, (err) => {
if (err) {
reject(err);
} else {
console.log(`π HTTP server listening on port ${PORT}`);
console.log(`π‘ Ready to receive epoch data from Go at http://localhost:${PORT}/submit-epoch`);
resolve();
}
});
});
}
// Handle epoch submission from Go
async handleEpochSubmission(req, res) {
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', async () => {
try {
const epochData = JSON.parse(body);
console.log(`\nπ RECEIVED EPOCH SUBMISSION FROM GO`);
console.log(`βββββββββββββββββββββββββββββββββββββββββββββββ`);
console.log(`π Epoch: ${epochData.epochNumber}`);
console.log(`π Subnet: ${epochData.subnetId}`);
console.log(`β° Timestamp: ${new Date(epochData.timestamp * 1000).toISOString()}`);
console.log(`π Rounds: ${epochData.completedRounds.length}`);
console.log(`π Detailed Rounds: ${epochData.detailedRounds ? epochData.detailedRounds.length : 'undefined'}`);
console.log(`π VLC State: ${JSON.stringify(epochData.vlcClockState)}`);
// Debug detailed round data
if (epochData.detailedRounds && epochData.detailedRounds.length > 0) {
console.log(`π DEBUG - Detailed rounds received:`);
epochData.detailedRounds.forEach((round, index) => {
console.log(` Round ${index + 1}: ${round.userInput ? round.userInput.substring(0, 40) + '...' : 'No input'}`);
});
} else {
console.log(`β DEBUG - No detailed rounds in payload`);
}
// Submit to blockchain
await this.submitEpochToBlockchain(epochData);
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
success: true,
epochNumber: epochData.epochNumber,
message: 'Epoch submitted successfully'
}));
} catch (error) {
console.error('β Error handling epoch submission:', error.message);
res.writeHead(500, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
success: false,
error: error.message
}));
}
});
}
// Submit epoch data to blockchain using the received data
async submitEpochToBlockchain(epochData) {
try {
console.log(`π€ Submitting Epoch ${epochData.epochNumber} to blockchain...`);
// Convert Go epoch data to blockchain format
const vlcGraphData = this.encodeVLCGraphData(epochData);
const successfulMiners = [this.accounts.miner.address];
// Use actual successful/failed counts from detailed round data
let successfulTasks = (epochData.detailedRounds || []).filter(r => r.success).length;
let failedTasks = (epochData.detailedRounds || []).filter(r => !r.success).length;
console.log(`π Task breakdown: ${successfulTasks} successful, ${failedTasks} failed (total: ${successfulTasks + failedTasks})`);
// Verify we have the expected task counts
const totalRoundsInEpoch = successfulTasks + failedTasks;
if (totalRoundsInEpoch === 0) {
console.log(`β οΈ WARNING: No detailed round data available, falling back to completedRounds count`);
// Fallback to legacy method if detailed rounds are unavailable
successfulTasks = epochData.completedRounds ? epochData.completedRounds.length : 0;
failedTasks = 0;
}
// Submit to contract
const tx = await this.contracts.verifier.submitAndDistributeEpoch(
epochData.subnetId,
vlcGraphData,
successfulMiners,
successfulTasks,
failedTasks
);
console.log(`π€ Transaction submitted: ${tx.hash}`);
const receipt = await tx.wait();
console.log(`β
Transaction confirmed in block ${receipt.blockNumber}`);
// Track submission
const submissionKey = `${epochData.subnetId}-epoch-${epochData.epochNumber}`;
this.epochSubmissions.set(submissionKey, {
epochNumber: epochData.epochNumber,
subnetId: epochData.subnetId,
txHash: tx.hash,
blockNumber: receipt.blockNumber,
timestamp: epochData.timestamp,
keyMined: "0" // Would calculate from logs
});
console.log(`π Epoch ${epochData.epochNumber} submitted successfully!`);
console.log(`βββββββββββββββββββββββββββββββββββββββββββββββ`);
return {
txHash: tx.hash,
blockNumber: receipt.blockNumber,
gasUsed: receipt.gasUsed.toString()
};
} catch (error) {
console.error(`β Blockchain submission failed: ${error.message}`);
throw error;
}
}
// Encode VLC graph data for blockchain submission
encodeVLCGraphData(epochData) {
// Create a structured representation of the VLC graph for this epoch
const vlcGraph = {
epochNumber: epochData.epochNumber,
vlcClockState: epochData.vlcClockState,
detailedRounds: epochData.detailedRounds || [], // Include detailed round data
epochEventId: epochData.epochEventId || '',
parentRoundEventId: epochData.parentRoundEventId || '',
timestamp: Math.floor(Date.now() / 1000)
// Removed redundant fields: completedRounds, totalRounds, successfulRounds, failedRounds
// These are now calculated and passed separately to smart contract
};
// Convert to hex-encoded bytes for smart contract
const jsonString = JSON.stringify(vlcGraph);
const hexData = '0x' + Buffer.from(jsonString, 'utf8').toString('hex');
console.log(`π Encoded VLC graph data: ${jsonString.length} bytes`);
console.log(`π Epoch summary: ${vlcGraph.totalRounds} rounds (${vlcGraph.successfulRounds} success, ${vlcGraph.failedRounds} failed)`);
// Log detailed round information
if (epochData.detailedRounds && epochData.detailedRounds.length > 0) {
console.log(`π Round details:`);
epochData.detailedRounds.forEach(round => {
const status = round.success ? 'β
' : 'β';
const inputPreview = round.userInput.length > 40 ? round.userInput.substring(0, 40) + '...' : round.userInput;
console.log(` Round ${round.roundNumber}: ${status} "${inputPreview}"`);
});
}
return hexData;
}
}
// Export the class for use in integration scripts
module.exports = PerEpochMainnetBridge;
// If run directly, start in interactive mode
if (require.main === module) {
const bridge = new PerEpochMainnetBridge();
async function main() {
try {
await bridge.initialize();
console.log(`\nπ Per-Epoch Bridge Ready!`);
console.log("βββββββββββββββββββββββββββββββββββββββββββββββ");
console.log("To use this bridge:");
console.log("1. Set up epoch callback in subnet coordinator");
console.log("2. Each completed epoch (3 rounds) triggers immediate submission");
console.log("3. KEY tokens are mined in real-time per epoch");
console.log("");
console.log("Example usage:");
console.log("const bridge = new PerEpochMainnetBridge();");
console.log("coordinator.GraphAdapter.SetEpochFinalizedCallback(bridge.handleEpochFinalized.bind(bridge));");
} catch (error) {
console.error("β Bridge initialization failed:", error.message);
}
}
main().catch(console.error);
}