-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrisk-score.ts
More file actions
448 lines (400 loc) Β· 13.1 KB
/
risk-score.ts
File metadata and controls
448 lines (400 loc) Β· 13.1 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
/**
* Composite Indexer Risk Score
*
* Ten dimensions, each scored 0β100, combined with transparent weights
* into a single 0β100 composite score. Higher = better for delegators.
*
* Dimensions & weights:
* REO compliance 20% β gates rewards; most critical signal
* Allocation efficiency 13% β operational competence
* Self-stake ratio 12% β skin in the game
* Delegator cut 10% β how much delegators keep (reward + query fee cuts)
* Over-delegation 10% β delegation safety margin
* Transparency 9% β presence and accountability
* Delegator APY 8% β actual returns delivered to delegators
* Query volume 7% β actual work served (query fees collected)
* Cut stability 7% β trust / predictability
* Delegation trend 4% β crowd signal (noisy, low weight)
*/
export interface ScoreBreakdown {
reo: number;
selfStake: number;
queryVolume: number;
delegatorCut: number;
cutStability: number;
allocationEfficiency: number;
overDelegation: number;
transparency: number;
delegationTrend: number;
delegatorAPY: number;
}
export interface IndexerScore {
composite: number; // 0β100 weighted score
breakdown: ScoreBreakdown; // per-dimension scores (each 0β100)
grade: 'A' | 'B' | 'C' | 'D' | 'F';
}
export const SCORE_WEIGHTS: Record<keyof ScoreBreakdown, number> = {
reo: 20,
allocationEfficiency: 13,
selfStake: 12,
delegatorCut: 10,
overDelegation: 10,
transparency: 9,
delegatorAPY: 8,
queryVolume: 7,
cutStability: 7,
delegationTrend: 4,
};
export const SCORE_LABELS: Record<keyof ScoreBreakdown, string> = {
reo: 'REO Compliance',
selfStake: 'Self-Stake',
queryVolume: 'Query Volume',
delegatorCut: 'Delegator Cut',
cutStability: 'Cut Stability',
allocationEfficiency: 'Allocation Efficiency',
overDelegation: 'Delegation Safety',
transparency: 'Transparency',
delegationTrend: 'Delegation Trend',
delegatorAPY: 'Delegator APY',
};
// --- Individual dimension scorers ---
/**
* REO compliance: eligible with plenty of renewal runway = 100, ineligible = 0
*/
function scoreREO(
status: 'eligible' | 'ineligible' | 'unknown',
daysRemaining: number | null,
source: 'oracle' | 'heuristic',
): number {
if (status === 'ineligible') return 0;
if (source === 'oracle' && status === 'eligible' && daysRemaining !== null) {
if (daysRemaining >= 7) return 100;
if (daysRemaining >= 3) return 80;
if (daysRemaining > 0) return 60;
return 20; // eligible but overdue renewal β oracle lag?
}
// Heuristic or unknown β partial credit
if (status === 'eligible') return 50;
return 25;
}
/**
* Self-stake: absolute GRT staked by the indexer β skin in the game.
* Scored on absolute value, NOT ratio. Having more delegation does not
* reduce this score. Linear interpolation between anchor points.
*
* Anchors (GRT β score):
* 10M+ β 100, 5M β 95, 1M β 80, 500K β 65,
* 200K β 50, 100K β 35 (protocol minimum), 0 β 5
*/
function scoreSelfStake(selfStakeGRT: number): number {
if (selfStakeGRT <= 0) return 0;
const anchors: [number, number][] = [
[10_000_000, 100],
[5_000_000, 95],
[1_000_000, 80],
[500_000, 65],
[200_000, 50],
[100_000, 35],
[0, 5],
];
if (selfStakeGRT >= anchors[0][0]) return anchors[0][1];
for (let i = 0; i < anchors.length - 1; i++) {
const [hi, hiScore] = anchors[i];
const [lo, loScore] = anchors[i + 1];
if (selfStakeGRT >= lo) {
const t = (selfStakeGRT - lo) / (hi - lo);
return Math.round(loScore + t * (hiScore - loScore));
}
}
return 5;
}
/**
* Cut stability: how long since last parameter change.
* Longer = more predictable for delegators. Cooldown set = bonus signal.
* Greedy cuts (>=100%) are hard-capped regardless of stability.
*/
function scoreCutStability(
lastUpdate: number,
cooldown: number,
rewardCutPPM?: number,
): number {
// Hard cap for greedy indexers β delegators earn nothing
if (rewardCutPPM !== undefined) {
if (rewardCutPPM >= 1_000_000) return 5;
if (rewardCutPPM >= 900_000) return Math.min(30, scoreCutStabilityInner(lastUpdate, cooldown));
}
return scoreCutStabilityInner(lastUpdate, cooldown);
}
function scoreCutStabilityInner(
lastUpdate: number,
cooldown: number,
): number {
const now = Math.floor(Date.now() / 1000);
const daysSinceChange = (now - lastUpdate) / 86400;
let score: number;
if (daysSinceChange >= 180) score = 100;
else if (daysSinceChange >= 90) score = 85;
else if (daysSinceChange >= 30) score = 65;
else if (daysSinceChange >= 7) score = 45;
else score = 30;
// Bonus: having a cooldown set shows good faith
if (cooldown > 0) score = Math.min(score + 10, 100);
return score;
}
/**
* Allocation efficiency: how well the indexer uses provisioned stake.
* allocated / provisioned ratio β higher utilisation = more competent operations.
*/
function scoreAllocationEfficiency(
allocationCount: number,
allocatedTokens: string,
provisionedGRT: number | null,
): number {
if (allocationCount === 0) return 0;
if (!provisionedGRT || provisionedGRT === 0) return 40; // allocating but no provision data
const allocated = Number(BigInt(allocatedTokens.split('.')[0] || '0')) / 1e18;
const ratio = Math.min(allocated / provisionedGRT, 1);
if (ratio >= 0.8) return 100;
if (ratio >= 0.6) return 80;
if (ratio >= 0.4) return 60;
if (ratio >= 0.2) return 40;
return 20;
}
/**
* Over-delegation risk: how close to max capacity.
* Lower utilisation = more room for new delegators without dilution.
*/
function scoreOverDelegation(utilizationPercent: number): number {
if (utilizationPercent >= 100) return 0;
if (utilizationPercent >= 95) return 15;
if (utilizationPercent >= 85) return 35;
if (utilizationPercent >= 70) return 55;
if (utilizationPercent >= 50) return 75;
return 100;
}
/**
* Transparency & presence: has the indexer bothered to be identifiable?
*/
function scoreTransparency(
hasENS: boolean,
hasURL: boolean,
hasDisplayName: boolean,
): number {
let score = 0;
if (hasENS) score += 40;
if (hasURL) score += 30;
if (hasDisplayName) score += 30;
return score;
}
/**
* Query volume: cumulative query fees collected in GRT.
* Indexers actually serving queries = doing real work. Higher fees = more useful.
*
* Anchors (GRT β score):
* 100K+ β 100, 50K β 90, 10K β 70, 1K β 50,
* 100 β 30, >0 β 15, 0 β 0
*/
function scoreQueryVolume(queryFeesCollectedGRT: number): number {
if (queryFeesCollectedGRT <= 0) return 0;
const anchors: [number, number][] = [
[100_000, 100],
[50_000, 90],
[10_000, 70],
[1_000, 50],
[100, 30],
[0, 15],
];
if (queryFeesCollectedGRT >= anchors[0][0]) return anchors[0][1];
for (let i = 0; i < anchors.length - 1; i++) {
const [hi, hiScore] = anchors[i];
const [lo, loScore] = anchors[i + 1];
if (queryFeesCollectedGRT >= lo) {
const t = (queryFeesCollectedGRT - lo) / (hi - lo);
return Math.round(loScore + t * (hiScore - loScore));
}
}
return 0;
}
/**
* Delegator cut: how much of the rewards delegators actually keep.
* Uses the **effective cut** (what delegators actually experience) when available,
* falling back to raw cut. Effective cut accounts for the indexer's own stake
* ratio β indexers with low delegation ratios need higher raw cuts to earn a
* reasonable return, but their effective cut is lower.
*
* Cut anchors (percentage β score):
* 0% β 100, 5% β 95, 10% β 85, 15% β 75, 20% β 68,
* 25% β 60, 50% β 35, 75% β 15, 100% β 0
*
* Query fee cut penalty: up to -15 points (linear, 100% fee cut = -15).
*/
function scoreDelegatorCut(
rewardCutPPM: number,
queryFeeCutPPM: number,
effectiveCutPercent?: number | null,
): number {
// Prefer effective cut (what delegators actually experience) over raw cut
const rewardCutPercent = effectiveCutPercent != null
? Math.min(Math.max(effectiveCutPercent, 0), 100)
: Math.min(rewardCutPPM / 10_000, 100);
const anchors: [number, number][] = [
[0, 100],
[5, 95],
[10, 85],
[15, 75],
[20, 68],
[25, 60],
[50, 35],
[75, 15],
[100, 0],
];
let rewardScore: number;
if (rewardCutPercent <= anchors[0][0]) {
rewardScore = anchors[0][1];
} else if (rewardCutPercent >= anchors[anchors.length - 1][0]) {
rewardScore = anchors[anchors.length - 1][1];
} else {
rewardScore = anchors[0][1]; // fallback
for (let i = 0; i < anchors.length - 1; i++) {
const [lo, loScore] = anchors[i];
const [hi, hiScore] = anchors[i + 1];
if (rewardCutPercent >= lo && rewardCutPercent <= hi) {
const t = (rewardCutPercent - lo) / (hi - lo);
rewardScore = Math.round(loScore + t * (hiScore - loScore));
break;
}
}
}
// Query fee cut penalty: 0% cut = 0 penalty, 100% cut = -15
const queryFeePercent = Math.min(queryFeeCutPPM / 10_000, 100);
const queryPenalty = Math.round((queryFeePercent / 100) * 15);
return Math.max(0, rewardScore - queryPenalty);
}
/**
* Delegator APY: actual returns delivered to delegators.
* Uses rolling 30d realised APY when available (most honest),
* falls back to estimated delegator APR.
*
* Anchors (APY% β score):
* 20%+ β 100, 15% β 90, 10% β 75, 7% β 60, 5% β 50,
* 3% β 35, 1% β 20, 0% β 0
*/
function scoreDelegatorAPY(
rollingAPY30d: number | null,
delegatorAPR: number,
): number {
// Prefer realised APY (backward-looking) over estimated APR (forward-looking)
const apy = rollingAPY30d != null && rollingAPY30d > 0
? rollingAPY30d
: delegatorAPR;
if (apy <= 0) return 0;
const anchors: [number, number][] = [
[20, 100],
[15, 90],
[10, 75],
[7, 60],
[5, 50],
[3, 35],
[1, 20],
[0, 0],
];
if (apy >= anchors[0][0]) return anchors[0][1];
for (let i = 0; i < anchors.length - 1; i++) {
const [hi, hiScore] = anchors[i];
const [lo, loScore] = anchors[i + 1];
if (apy >= lo) {
const t = (apy - lo) / (hi - lo);
return Math.round(loScore + t * (hiScore - loScore));
}
}
return 0;
}
/**
* Delegation trend: net flow relative to total delegated.
* Positive inflow = crowd confidence. Neutral = baseline. Outflow = warning.
*/
function scoreDelegationTrend(
netFlowGRT: number,
totalDelegatedGRT: number,
): number {
if (totalDelegatedGRT === 0) return 50; // no delegation history = neutral
const flowPercent = (netFlowGRT / totalDelegatedGRT) * 100;
// Strong inflow (>2% of total delegated in 7d)
if (flowPercent >= 2) return 100;
if (flowPercent >= 0.5) return 80;
if (flowPercent >= 0) return 60;
// Outflow
if (flowPercent >= -1) return 40;
if (flowPercent >= -3) return 20;
return 0;
}
// --- Composite scorer ---
function gradeFromScore(score: number): 'A' | 'B' | 'C' | 'D' | 'F' {
if (score >= 80) return 'A';
if (score >= 65) return 'B';
if (score >= 50) return 'C';
if (score >= 35) return 'D';
return 'F';
}
export interface ScoreInput {
reoStatus: 'eligible' | 'ineligible' | 'unknown';
reoDaysRemaining: number | null;
reoSource: 'oracle' | 'heuristic';
selfStakeGRT: number;
lastDelegationParameterUpdate: number;
delegatorParameterCooldown: number;
allocationCount: number;
allocatedTokens: string;
provisionedGRT: number | null;
delegationUtilization: number;
ensName: string | null;
url: string | null;
name: string;
id: string;
rewardCutPPM: number;
queryFeeCutPPM: number;
effectiveCutPercent?: number | null;
queryFeesCollectedGRT: number;
netFlowGRT: number;
delegatedGRT: number;
rollingAPY30d?: number | null;
delegatorAPR?: number;
}
export function calculateIndexerScore(input: ScoreInput): IndexerScore {
const breakdown: ScoreBreakdown = {
reo: scoreREO(input.reoStatus, input.reoDaysRemaining, input.reoSource),
selfStake: scoreSelfStake(input.selfStakeGRT),
queryVolume: scoreQueryVolume(input.queryFeesCollectedGRT),
delegatorCut: scoreDelegatorCut(input.rewardCutPPM, input.queryFeeCutPPM, input.effectiveCutPercent),
cutStability: scoreCutStability(
input.lastDelegationParameterUpdate,
input.delegatorParameterCooldown,
input.rewardCutPPM,
),
allocationEfficiency: scoreAllocationEfficiency(
input.allocationCount,
input.allocatedTokens,
input.provisionedGRT,
),
overDelegation: scoreOverDelegation(input.delegationUtilization),
transparency: scoreTransparency(
!!input.ensName,
!!input.url,
input.name !== input.id, // display name set if name !== raw address
),
delegationTrend: scoreDelegationTrend(input.netFlowGRT, input.delegatedGRT),
delegatorAPY: scoreDelegatorAPY(input.rollingAPY30d ?? null, input.delegatorAPR ?? 0),
};
// Weighted composite
const composite = Math.round(
Object.entries(SCORE_WEIGHTS).reduce(
(sum, [key, weight]) => sum + breakdown[key as keyof ScoreBreakdown] * (weight / 100),
0
)
);
return {
composite,
breakdown,
grade: gradeFromScore(composite),
};
}