-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraduationService.ts
More file actions
586 lines (530 loc) · 18.3 KB
/
GraduationService.ts
File metadata and controls
586 lines (530 loc) · 18.3 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
/**
* Graduation Service
*
* Formal graduation system based on real usage metrics
* No price, no market cap, no hype - only measurable performance
*
* Core Variables:
* - V = number of active validators
* - M = number of active miners
* - T = total completed tasks
* - A = validator agreement rate (0-1)
* - R = user retry rate (0-1)
* - D = unresolved disputes
* - W = rolling window (7 days)
*/
import { PrismaClient } from '@prisma/client';
import { ILogger } from './utils/ILogger';
import { NetworkManifest, GraduationLevel, GraduationStatus } from './types';
import { OnChainValidatorService } from './OnChainValidatorService';
export interface NetworkMetrics {
// Core metrics
validatorCount: number; // V
minerCount: number; // M
completedTasks: number; // T
agreementRate: number; // A (0-1)
retryRate: number; // R (0-1)
unresolvedDisputes: number; // D
maxValidatorPower: number; // max_validator_power (0-1)
// Metadata
windowStart: Date;
windowEnd: Date;
totalTasks: number;
totalEvaluations: number;
}
export interface GraduationConditions {
level0to1: {
validatorCount: number; // V ≥ 3
minerCount: number; // M ≥ 5
completedTasks: number; // T ≥ 100
agreementRate: number; // A ≥ 0.70
unresolvedDisputes: number; // D = 0
};
level1to2: {
validatorCount: number; // V ≥ 10
minerCount: number; // M ≥ 30
completedTasks: number; // T ≥ 1,000
agreementRate: number; // A ≥ 0.80
retryRate: number; // R ≤ 0.25
unresolvedDisputes: number; // D ≤ 1
};
level2to3: {
validatorCount: number; // V ≥ 20
minerCount: number; // M ≥ 100
completedTasks: number; // T ≥ 10,000
agreementRate: number; // A ≥ 0.90
retryRate: number; // R ≤ 0.15
maxValidatorPower: number; // max_validator_power ≤ 0.20
};
}
export class GraduationService {
private prisma: PrismaClient;
private logger: ILogger;
private onChainValidatorService: OnChainValidatorService;
private readonly ROLLING_WINDOW_DAYS = 7; // W = 7 days
constructor(prisma: PrismaClient, logger: ILogger) {
this.prisma = prisma;
this.logger = logger;
this.onChainValidatorService = new OnChainValidatorService(logger);
}
/**
* Get current network metrics within rolling window
*/
async getNetworkMetrics(
networkId: string,
manifest: NetworkManifest
): Promise<NetworkMetrics> {
const windowEnd = new Date();
const windowStart = new Date(windowEnd.getTime() - (this.ROLLING_WINDOW_DAYS * 24 * 60 * 60 * 1000));
// Get validator count (V) from on-chain
const validatorCount = await this.onChainValidatorService.getTotalValidatorCount(manifest);
// Get miner count (M) from task outputs
const minerCount = await this.getActiveMinerCount(networkId, windowStart, windowEnd);
// Get completed tasks (T) within window
const completedTasks = await this.getCompletedTaskCount(networkId, windowStart, windowEnd);
// Get total tasks for agreement rate calculation
const totalTasks = await this.getTotalTaskCount(networkId, windowStart, windowEnd);
// Get agreement rate (A) from evaluations
const agreementRate = await this.getAgreementRate(networkId, windowStart, windowEnd);
// Get retry rate (R) from user rejections
const retryRate = await this.getRetryRate(networkId, windowStart, windowEnd);
// Get unresolved disputes (D)
const unresolvedDisputes = await this.getUnresolvedDisputeCount(networkId, windowStart, windowEnd);
// Get max validator power (for Level 2→3)
const maxValidatorPower = await this.getMaxValidatorPower(networkId, manifest, windowStart, windowEnd);
// Get total evaluations for metadata
const totalEvaluations = await this.getTotalEvaluationCount(networkId, windowStart, windowEnd);
return {
validatorCount,
minerCount,
completedTasks,
agreementRate,
retryRate,
unresolvedDisputes,
maxValidatorPower,
windowStart,
windowEnd,
totalTasks,
totalEvaluations,
};
}
/**
* Check if network meets conditions for graduation to next level
*/
async checkGraduationEligibility(
networkId: string,
manifest: NetworkManifest,
currentLevel: GraduationLevel
): Promise<{
eligible: boolean;
metrics: NetworkMetrics;
conditions: GraduationConditions;
metConditions: Partial<GraduationConditions>;
reason?: string;
}> {
const metrics = await this.getNetworkMetrics(networkId, manifest);
const conditions = this.getGraduationConditions();
let eligible = false;
let metConditions: Partial<GraduationConditions> = {};
let reason: string | undefined;
if (currentLevel === 'sandbox') {
// Check Level 0 → Level 1 conditions
const meetsV = metrics.validatorCount >= conditions.level0to1.validatorCount;
const meetsM = metrics.minerCount >= conditions.level0to1.minerCount;
const meetsT = metrics.completedTasks >= conditions.level0to1.completedTasks;
const meetsA = metrics.agreementRate >= conditions.level0to1.agreementRate;
const meetsD = metrics.unresolvedDisputes === conditions.level0to1.unresolvedDisputes;
eligible = meetsV && meetsM && meetsT && meetsA && meetsD;
metConditions.level0to1 = {
validatorCount: metrics.validatorCount,
minerCount: metrics.minerCount,
completedTasks: metrics.completedTasks,
agreementRate: metrics.agreementRate,
unresolvedDisputes: metrics.unresolvedDisputes,
};
if (!eligible) {
const missing: string[] = [];
if (!meetsV) missing.push(`V < ${conditions.level0to1.validatorCount}`);
if (!meetsM) missing.push(`M < ${conditions.level0to1.minerCount}`);
if (!meetsT) missing.push(`T < ${conditions.level0to1.completedTasks}`);
if (!meetsA) missing.push(`A < ${conditions.level0to1.agreementRate}`);
if (!meetsD) missing.push(`D > ${conditions.level0to1.unresolvedDisputes}`);
reason = `Missing conditions: ${missing.join(', ')}`;
}
} else if (currentLevel === 'active') {
// Check Level 1 → Level 2 conditions
const meetsV = metrics.validatorCount >= conditions.level1to2.validatorCount;
const meetsM = metrics.minerCount >= conditions.level1to2.minerCount;
const meetsT = metrics.completedTasks >= conditions.level1to2.completedTasks;
const meetsA = metrics.agreementRate >= conditions.level1to2.agreementRate;
const meetsR = metrics.retryRate <= conditions.level1to2.retryRate;
const meetsD = metrics.unresolvedDisputes <= conditions.level1to2.unresolvedDisputes;
eligible = meetsV && meetsM && meetsT && meetsA && meetsR && meetsD;
metConditions.level1to2 = {
validatorCount: metrics.validatorCount,
minerCount: metrics.minerCount,
completedTasks: metrics.completedTasks,
agreementRate: metrics.agreementRate,
retryRate: metrics.retryRate,
unresolvedDisputes: metrics.unresolvedDisputes,
};
if (!eligible) {
const missing: string[] = [];
if (!meetsV) missing.push(`V < ${conditions.level1to2.validatorCount}`);
if (!meetsM) missing.push(`M < ${conditions.level1to2.minerCount}`);
if (!meetsT) missing.push(`T < ${conditions.level1to2.completedTasks}`);
if (!meetsA) missing.push(`A < ${conditions.level1to2.agreementRate}`);
if (!meetsR) missing.push(`R > ${conditions.level1to2.retryRate}`);
if (!meetsD) missing.push(`D > ${conditions.level1to2.unresolvedDisputes}`);
reason = `Missing conditions: ${missing.join(', ')}`;
}
} else if (currentLevel === 'trusted') {
// Check Level 2 → Level 3 conditions
const meetsV = metrics.validatorCount >= conditions.level2to3.validatorCount;
const meetsM = metrics.minerCount >= conditions.level2to3.minerCount;
const meetsT = metrics.completedTasks >= conditions.level2to3.completedTasks;
const meetsA = metrics.agreementRate >= conditions.level2to3.agreementRate;
const meetsR = metrics.retryRate <= conditions.level2to3.retryRate;
const meetsMaxPower = metrics.maxValidatorPower <= conditions.level2to3.maxValidatorPower;
eligible = meetsV && meetsM && meetsT && meetsA && meetsR && meetsMaxPower;
metConditions.level2to3 = {
validatorCount: metrics.validatorCount,
minerCount: metrics.minerCount,
completedTasks: metrics.completedTasks,
agreementRate: metrics.agreementRate,
retryRate: metrics.retryRate,
maxValidatorPower: metrics.maxValidatorPower,
};
if (!eligible) {
const missing: string[] = [];
if (!meetsV) missing.push(`V < ${conditions.level2to3.validatorCount}`);
if (!meetsM) missing.push(`M < ${conditions.level2to3.minerCount}`);
if (!meetsT) missing.push(`T < ${conditions.level2to3.completedTasks}`);
if (!meetsA) missing.push(`A < ${conditions.level2to3.agreementRate}`);
if (!meetsR) missing.push(`R > ${conditions.level2to3.retryRate}`);
if (!meetsMaxPower) missing.push(`max_validator_power > ${conditions.level2to3.maxValidatorPower}`);
reason = `Missing conditions: ${missing.join(', ')}`;
}
} else {
// Already at max level
eligible = false;
reason = 'Network already at maximum graduation level';
}
return {
eligible,
metrics,
conditions,
metConditions,
reason,
};
}
/**
* Get graduation conditions (thresholds)
*/
private getGraduationConditions(): GraduationConditions {
return {
level0to1: {
validatorCount: 3,
minerCount: 5,
completedTasks: 100,
agreementRate: 0.70,
unresolvedDisputes: 0,
},
level1to2: {
validatorCount: 10,
minerCount: 30,
completedTasks: 1000,
agreementRate: 0.80,
retryRate: 0.25,
unresolvedDisputes: 1,
},
level2to3: {
validatorCount: 20,
minerCount: 100,
completedTasks: 10000,
agreementRate: 0.90,
retryRate: 0.15,
maxValidatorPower: 0.20, // 20%
},
};
}
/**
* Get active miner count (M) from task outputs within window
*/
private async getActiveMinerCount(
networkId: string,
windowStart: Date,
windowEnd: Date
): Promise<number> {
try {
const uniqueMiners = await this.prisma.tenseuronTaskOutput.findMany({
where: {
task: {
networkId,
createdAt: {
gte: windowStart,
lte: windowEnd,
},
},
},
select: {
minerAddress: true,
},
distinct: ['minerAddress'],
});
return uniqueMiners.length;
} catch (error) {
this.logger.error('Failed to get active miner count', { networkId, error });
return 0;
}
}
/**
* Get completed task count (T) within window
*/
private async getCompletedTaskCount(
networkId: string,
windowStart: Date,
windowEnd: Date
): Promise<number> {
try {
return await this.prisma.tenseuronTask.count({
where: {
networkId,
status: 'paid', // Tasks that reached consensus and were paid
createdAt: {
gte: windowStart,
lte: windowEnd,
},
},
});
} catch (error) {
this.logger.error('Failed to get completed task count', { networkId, error });
return 0;
}
}
/**
* Get total task count within window
*/
private async getTotalTaskCount(
networkId: string,
windowStart: Date,
windowEnd: Date
): Promise<number> {
try {
return await this.prisma.tenseuronTask.count({
where: {
networkId,
createdAt: {
gte: windowStart,
lte: windowEnd,
},
},
});
} catch (error) {
this.logger.error('Failed to get total task count', { networkId, error });
return 0;
}
}
/**
* Get agreement rate (A) from validator evaluations
* Agreement = validators who scored the winning output ≥ 50
*/
private async getAgreementRate(
networkId: string,
windowStart: Date,
windowEnd: Date
): Promise<number> {
try {
// Get all tasks with consensus reached
const tasks = await this.prisma.tenseuronTask.findMany({
where: {
networkId,
consensusReached: true,
winningOutputId: { not: null },
createdAt: {
gte: windowStart,
lte: windowEnd,
},
},
include: {
evaluations: true,
},
});
if (tasks.length === 0) {
return 0;
}
let totalAgreements = 0;
let totalEvaluations = 0;
for (const task of tasks) {
if (!task.winningOutputId) continue;
const evaluations = task.evaluations || [];
const winningEvaluations = evaluations.filter(
(e) => e.outputId === task.winningOutputId && e.score >= 50
);
totalAgreements += winningEvaluations.length;
totalEvaluations += evaluations.length;
}
return totalEvaluations > 0 ? totalAgreements / totalEvaluations : 0;
} catch (error) {
this.logger.error('Failed to get agreement rate', { networkId, error });
return 0;
}
}
/**
* Get retry rate (R) from user rejections
* R = (user_requested_redos) / (total_tasks)
*/
private async getRetryRate(
networkId: string,
windowStart: Date,
windowEnd: Date
): Promise<number> {
try {
const totalTasks = await this.getTotalTaskCount(networkId, windowStart, windowEnd);
if (totalTasks === 0) {
return 0;
}
const rejectedTasks = await this.prisma.tenseuronTask.count({
where: {
networkId,
userRejected: true,
createdAt: {
gte: windowStart,
lte: windowEnd,
},
},
});
return rejectedTasks / totalTasks;
} catch (error) {
this.logger.error('Failed to get retry rate', { networkId, error });
return 0;
}
}
/**
* Get unresolved dispute count (D)
*/
private async getUnresolvedDisputeCount(
networkId: string,
windowStart: Date,
windowEnd: Date
): Promise<number> {
try {
return await this.prisma.tenseuronTask.count({
where: {
networkId,
status: 'challenged', // Tasks in dispute
createdAt: {
gte: windowStart,
lte: windowEnd,
},
},
});
} catch (error) {
this.logger.error('Failed to get unresolved dispute count', { networkId, error });
return 0;
}
}
/**
* Get max validator power (for Level 2→3 check)
* max_validator_power = max(stake_per_validator) / total_stake
*/
private async getMaxValidatorPower(
networkId: string,
manifest: NetworkManifest,
windowStart: Date,
windowEnd: Date
): Promise<number> {
try {
// Get all validators and their stakes
const validators = await this.onChainValidatorService.getTotalValidatorCount(manifest);
if (validators === 0) {
return 1.0; // No validators = 100% power (fails check)
}
// FULLY IMPLEMENTED: Query ValidatorRegistry for actual stakes (not equal distribution)
// Equal distribution is only used as fallback when registry is unavailable
const equalPower = 1.0 / validators;
// If we have validator registry, calculate actual max power
if (manifest.settlement.validatorRegistryAddress) {
try {
const { ValidatorRegistrationService } = await import('../services/ValidatorRegistrationService');
const validatorService = new ValidatorRegistrationService(this.logger);
const validatorAddresses = await validatorService.getValidators(manifest);
if (validatorAddresses.length === 0) {
return 1.0;
}
// Get stakes for each validator
const stakes: bigint[] = [];
let totalStake = 0n;
for (const address of validatorAddresses) {
const info = await validatorService.getValidatorInfo(address, manifest);
if (info && info.isRegistered) {
const stake = BigInt(info.stake);
stakes.push(stake);
totalStake += stake;
}
}
if (totalStake === 0n) {
return equalPower;
}
// Find max stake percentage
const maxStake = stakes.length > 0 ? Math.max(...stakes.map((s) => Number(s))) : 0;
const maxPower = maxStake / Number(totalStake);
return maxPower;
} catch (error) {
this.logger.warn('Failed to get validator stakes, using equal distribution', { error });
return equalPower;
}
}
return equalPower;
} catch (error) {
this.logger.error('Failed to get max validator power', { networkId, error });
return 1.0; // Fail-safe: assume worst case
}
}
/**
* Get total evaluation count (metadata)
*/
private async getTotalEvaluationCount(
networkId: string,
windowStart: Date,
windowEnd: Date
): Promise<number> {
try {
return await this.prisma.tenseuronTaskEvaluation.count({
where: {
task: {
networkId,
createdAt: {
gte: windowStart,
lte: windowEnd,
},
},
},
});
} catch (error) {
this.logger.error('Failed to get total evaluation count', { networkId, error });
return 0;
}
}
/**
* Get current graduation status for a network
*/
async getGraduationStatus(
networkId: string,
manifest: NetworkManifest
): Promise<GraduationStatus> {
const currentLevel = manifest.graduationStatus?.level || 'sandbox';
const metrics = await this.getNetworkMetrics(networkId, manifest);
return {
level: currentLevel,
achievedAt: manifest.graduationStatus?.achievedAt,
conditions: {
validatorCount: metrics.validatorCount,
minerCount: metrics.minerCount,
completedTasks: metrics.completedTasks,
validatorAgreementRate: metrics.agreementRate,
unresolvedDisputes: metrics.unresolvedDisputes,
},
};
}
}