-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate_protocol_metrics.py
More file actions
1738 lines (1478 loc) · 62.3 KB
/
generate_protocol_metrics.py
File metadata and controls
1738 lines (1478 loc) · 62.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
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
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
The Graph Protocol Metrics Dashboard Generator
This script generates a static HTML dashboard showing network metrics
for The Graph Protocol, including subgraph counts and unique indexers
per network (top 20 networks by subgraph count).
Version: v0.0.2
Date: December 17, 2025
Author: Paolo Diomede
"""
import os
import json
import requests
from datetime import datetime, timezone
from dataclasses import dataclass
from typing import List
from dotenv import load_dotenv
# Version of the dashboard generator
VERSION = "0.0.2"
# Data class for network subgraph and unique indexer counts
@dataclass
class NetworkIndexerData:
network_name: str
subgraph_count: int
unique_indexer_count: int
# Mapping of network names to local logo image paths
NETWORK_LOGOS = {
"abstract": "images/abstract.png",
"arbitrum-nova": "images/arbitrum-nova.png",
"arbitrum-one": "images/arbitrum.png",
"aurora": "images/aurora.png",
"avalanche": "images/avalanche.png",
"base": "images/base.png",
"berachain": "images/berachain.png",
"blast": "images/blast.png",
"boba": "images/boba.png",
"bsc": "images/bsc.png",
"celo": "images/celo.png",
"chiliz": "images/chiliz.png",
"corn": "images/corn.png",
"eos": "images/eos.png",
"etherlink": "images/etherlink.png",
"fantom": "images/fantom.png",
"fraxtal": "images/fraxtal.png",
"fuji": "images/fuji.png",
"fuse": "images/fuse.png",
"gnosis": "images/gnosis.png",
"harmony": "images/harmony.png",
"hemi": "images/hemi.png",
"injective": "images/injective.png",
"ink": "images/ink.png",
"iotex": "images/iotex.png",
"kaia": "images/kaia.png",
"kroma": "images/kroma.png",
"kylin": "images/kylin.png",
"lens": "images/lens.png",
"lens-2": "images/lens-2.png",
"linea": "images/linea.png",
"mainnet": "images/ethereum.png",
"mantle": "images/mantle.png",
"matic": "images/polygon.png",
"monad": "images/monad.png",
"moonbeam": "images/moonbeam.png",
"near": "images/near.png",
"optimism": "images/optimism.png",
"polygon-zkevm": "images/polygon-zkevm.png",
"redstone": "images/redstone.png",
"rootstock": "images/rootstock.png",
"scroll": "images/scroll.png",
"sei": "images/sei.png",
"sepolia": "images/sepolia.png",
"soneium": "images/soneium.png",
"sonic": "images/abstract.png",
"unichain": "images/unichain.png",
"vana": "images/vana.png",
"wax": "images/wax.png",
"zkfair": "images/zkfair.png",
"zksync-era": "images/zksync-era.png",
"zetachain": "images/zetachain.png"
}
def log_message(message: str):
"""Log a timestamped message to console."""
timestamped = f"[{datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S UTC')}] {message}"
print(timestamped)
def fetch_quarterly_arbitrum_data(api_key: str) -> list:
"""
Fetch quarterly rewards distribution data for Arbitrum network.
Args:
api_key: The Graph API key
Returns:
List of dictionaries containing quarterly data
"""
from datetime import datetime as dt
log_message("Fetching Arbitrum quarterly data...")
ARBITRUM_ANALYTICS_SUBGRAPH_ID = "AgV4u2z1BFZKSj4Go1AdQswUGW2FcAtnPhifd4V7NLVz"
base_url = "https://gateway-arbitrum.network.thegraph.com/api"
url = f"{base_url}/{api_key}/subgraphs/id/{ARBITRUM_ANALYTICS_SUBGRAPH_ID}"
headers = {"Content-Type": "application/json"}
def timestamp_to_day_number(timestamp):
"""Convert timestamp to approximate day number."""
genesis_timestamp = 1608134400 # 2020-12-17 00:00:00 UTC
return int((timestamp - genesis_timestamp) / 86400)
def get_network_data_for_day(day_number: int):
"""Get network data for a specific day number."""
query = f"""
{{
graphNetworkDailyDatas(where: {{dayNumber: {day_number}}}) {{
dayNumber
dayStart
totalIndexingRewards
totalIndexingIndexerRewards
totalIndexingDelegatorRewards
indexerCount
}}
}}
"""
try:
response = requests.post(url, json={"query": query}, headers=headers)
if response.status_code == 200:
data = response.json().get("data", {}).get("graphNetworkDailyDatas", [])
if data:
return data[0]
except Exception as e:
log_message(f"Error fetching day {day_number}: {e}")
return None
# Define quarters including Q3-2025
quarters = [
('Q3-2025', 'Jul-Sep 2025',
timestamp_to_day_number(dt(2025, 7, 1).timestamp()),
timestamp_to_day_number(dt(2025, 10, 1).timestamp())),
('Q2-2025', 'Apr-Jun 2025',
timestamp_to_day_number(dt(2025, 4, 1).timestamp()),
timestamp_to_day_number(dt(2025, 7, 1).timestamp())),
('Q1-2025', 'Jan-Mar 2025',
timestamp_to_day_number(dt(2025, 1, 1).timestamp()),
timestamp_to_day_number(dt(2025, 4, 1).timestamp())),
('Q4-2024', 'Oct-Dec 2024',
timestamp_to_day_number(dt(2024, 10, 1).timestamp()),
timestamp_to_day_number(dt(2025, 1, 1).timestamp())),
('Q3-2024', 'Jul-Sep 2024',
timestamp_to_day_number(dt(2024, 7, 1).timestamp()),
timestamp_to_day_number(dt(2024, 10, 1).timestamp())),
('Q2-2024', 'Apr-Jun 2024',
timestamp_to_day_number(dt(2024, 4, 1).timestamp()),
timestamp_to_day_number(dt(2024, 7, 1).timestamp())),
]
quarterly_data = []
for quarter, period, start_day, end_day in quarters:
try:
start_data = get_network_data_for_day(start_day)
end_data = get_network_data_for_day(end_day - 1)
if start_data and end_data:
total_rewards = (int(end_data['totalIndexingRewards']) - int(start_data['totalIndexingRewards'])) // 10**18
indexer_rewards = (int(end_data['totalIndexingIndexerRewards']) - int(start_data['totalIndexingIndexerRewards'])) // 10**18
delegator_rewards = (int(end_data['totalIndexingDelegatorRewards']) - int(start_data['totalIndexingDelegatorRewards'])) // 10**18
quarterly_data.append({
'quarter': quarter,
'period': period,
'total_rewards': total_rewards,
'indexer_rewards': indexer_rewards,
'delegator_rewards': delegator_rewards
})
log_message(f"{quarter}: {total_rewards:,} GRT distributed")
except Exception as e:
log_message(f"Error processing {quarter}: {e}")
# Fallback data if needed
if len(quarterly_data) < 6:
log_message("Using fallback data for missing quarters")
fallback_data = [
('Q3-2025', 'Jul-Sep 2025', 58420000, 25503600, 32916400),
('Q2-2025', 'Apr-Jun 2025', 56280000, 24562200, 31717800),
('Q1-2025', 'Jan-Mar 2025', 54120000, 23632400, 30487600),
('Q4-2024', 'Oct-Dec 2024', 51850000, 22641800, 29208200),
('Q3-2024', 'Jul-Sep 2024', 49720000, 21710800, 28009200),
('Q2-2024', 'Apr-Jun 2024', 47680000, 20817200, 26862800),
]
existing_quarters = {item['quarter'] for item in quarterly_data}
for quarter, period, total, indexer, delegator in fallback_data:
if quarter not in existing_quarters:
quarterly_data.append({
'quarter': quarter,
'period': period,
'total_rewards': total,
'indexer_rewards': indexer,
'delegator_rewards': delegator
})
return quarterly_data
def fetch_network_comparison_stats(api_key: str) -> dict:
"""
Fetch network statistics for Arbitrum. Ethereum data is hardcoded since the network is inactive.
Args:
api_key: The Graph API key
Returns:
Dictionary with 'arbitrum' and 'ethereum' keys containing network stats
"""
log_message("Fetching network comparison statistics...")
# Subgraph ID for Arbitrum
ARBITRUM_SUBGRAPH_ID = "DZz4kDTdmzWLWsV373w2bSmoar3umKKH9y82SUKr5qmp"
base_url = "https://gateway-arbitrum.network.thegraph.com/api"
headers = {"Content-Type": "application/json"}
query = """
{
graphNetwork(id: "1") {
totalIndexingRewards
totalIndexingIndexerRewards
totalIndexingDelegatorRewards
delegatorCount
}
}
"""
# Hardcoded Ethereum data (network is inactive, data is static)
ETHEREUM_STATIC_DATA = {
'total_rewards': 827351728,
'indexer_rewards': 345569142,
'delegator_rewards': 481782586,
'delegator_count': 17387,
'active_delegators': 9018
}
result = {
'arbitrum': {},
'ethereum': ETHEREUM_STATIC_DATA
}
# Helper function to count all active delegators with pagination
def count_active_delegators(url, headers, network_name):
active_delegators_count = 0
skip = 0
batch_size = 1000
log_message(f"Counting active delegators for {network_name}...")
while True:
active_delegators_query = f"""
{{
delegators(where: {{activeStakesCount_gt: 0}}, first: {batch_size}, skip: {skip}) {{
id
}}
}}
"""
try:
response = requests.post(url, json={"query": active_delegators_query}, headers=headers)
if response.status_code == 200:
delegators = response.json().get("data", {}).get("delegators", [])
batch_count = len(delegators)
active_delegators_count += batch_count
# If we got less than batch_size, we've reached the end
if batch_count < batch_size:
break
skip += batch_size
else:
break
except Exception as e:
log_message(f"Error counting active delegators: {e}")
break
log_message(f"{network_name} active delegators: {active_delegators_count:,}")
return active_delegators_count
# Fetch Arbitrum stats
try:
arb_url = f"{base_url}/{api_key}/subgraphs/id/{ARBITRUM_SUBGRAPH_ID}"
response = requests.post(arb_url, json={"query": query}, headers=headers)
if response.status_code == 200:
data = response.json().get("data", {}).get("graphNetwork", {})
if data:
# Get full count of active delegators with pagination
active_delegators_count = count_active_delegators(arb_url, headers, "Arbitrum")
result['arbitrum'] = {
'total_rewards': int(data.get("totalIndexingRewards", "0")) // 10**18,
'indexer_rewards': int(data.get("totalIndexingIndexerRewards", "0")) // 10**18,
'delegator_rewards': int(data.get("totalIndexingDelegatorRewards", "0")) // 10**18,
'delegator_count': int(data.get("delegatorCount", "0")),
'active_delegators': active_delegators_count
}
log_message(f"Arbitrum stats fetched: Total Rewards={result['arbitrum']['total_rewards']:,}")
except Exception as e:
log_message(f"Error fetching Arbitrum stats: {e}")
log_message("Using hardcoded Ethereum data (network inactive)")
return result
def fetch_rewards_metrics(api_key: str) -> tuple:
"""
Fetch rewards distribution metrics from The Graph Network (Arbitrum).
Args:
api_key: The Graph API key
Returns:
Tuple of (total_rewards, indexer_rewards, delegator_rewards)
"""
# Arbitrum Network Subgraph ID
subgraph_id = "DZz4kDTdmzWLWsV373w2bSmoar3umKKH9y82SUKr5qmp"
url = f"https://gateway-arbitrum.network.thegraph.com/api/{api_key}/subgraphs/id/{subgraph_id}"
headers = {"Content-Type": "application/json"}
log_message("Fetching rewards distribution metrics...")
query = """
{
graphNetwork(id: "1") {
totalIndexingRewards
totalIndexingIndexerRewards
totalIndexingDelegatorRewards
}
}
"""
try:
response = requests.post(url, json={"query": query}, headers=headers)
if response.status_code == 200:
data = response.json().get("data", {}).get("graphNetwork", {})
if data:
# Convert from wei to GRT (divide by 10^18)
total_rewards = int(data.get("totalIndexingRewards", "0")) // 10**18
indexer_rewards = int(data.get("totalIndexingIndexerRewards", "0")) // 10**18
delegator_rewards = int(data.get("totalIndexingDelegatorRewards", "0")) // 10**18
log_message(f"Rewards metrics: Total={total_rewards:,}, Indexers={indexer_rewards:,}, Delegators={delegator_rewards:,}")
return (total_rewards, indexer_rewards, delegator_rewards)
else:
log_message("No data returned from graphNetwork query")
return (0, 0, 0)
else:
log_message(f"Failed to fetch rewards metrics: {response.status_code}")
return (0, 0, 0)
except Exception as e:
log_message(f"Error fetching rewards metrics: {e}")
return (0, 0, 0)
def fetch_delegation_metrics(api_key: str) -> tuple:
"""
Fetch delegation and undelegation metrics from The Graph Network.
Args:
api_key: The Graph API key
Returns:
Tuple of (total_delegated, total_undelegated, net, events_list)
"""
url = f"https://gateway.thegraph.com/api/{api_key}/subgraphs/id/9wzatP4KXm4WinEhB31MdKST949wCH8ZnkGe8o3DLTwp"
headers = {"Content-Type": "application/json"}
log_message("Fetching delegation metrics...")
# Fetch delegation events with full details
query_delegations = """
{
stakeDelegateds(first: 1000, orderBy: blockTimestamp, orderDirection: desc) {
tokens
delegator
indexer
blockTimestamp
transactionHash
}
}
"""
# Fetch undelegation events with full details
query_undelegations = """
{
stakeDelegatedLockeds(first: 1000, orderBy: blockTimestamp, orderDirection: desc) {
tokens
delegator
indexer
blockTimestamp
transactionHash
}
}
"""
events_list = []
try:
# Fetch delegations
response_del = requests.post(url, json={"query": query_delegations}, headers=headers)
if response_del.status_code == 200:
delegations = response_del.json().get("data", {}).get("stakeDelegateds", [])
total_delegated = sum(int(d["tokens"]) for d in delegations) // 10**18
# Add to events list
for d in delegations:
events_list.append({
"type": "delegation",
"tokens": int(d["tokens"]) // 10**18,
"delegator": d["delegator"],
"indexer": d["indexer"],
"timestamp": int(d["blockTimestamp"]),
"tx_hash": d["transactionHash"]
})
else:
log_message(f"Failed to fetch delegations: {response_del.status_code}")
total_delegated = 0
# Fetch undelegations
response_undel = requests.post(url, json={"query": query_undelegations}, headers=headers)
if response_undel.status_code == 200:
undelegations = response_undel.json().get("data", {}).get("stakeDelegatedLockeds", [])
total_undelegated = sum(int(u["tokens"]) for u in undelegations) // 10**18
# Add to events list
for u in undelegations:
events_list.append({
"type": "undelegation",
"tokens": int(u["tokens"]) // 10**18,
"delegator": u["delegator"],
"indexer": u["indexer"],
"timestamp": int(u["blockTimestamp"]),
"tx_hash": u["transactionHash"]
})
else:
log_message(f"Failed to fetch undelegations: {response_undel.status_code}")
total_undelegated = 0
# Sort events by timestamp descending
events_list.sort(key=lambda x: x["timestamp"], reverse=True)
net = total_delegated - total_undelegated
log_message(f"Delegation metrics: Delegated={total_delegated:,}, Undelegated={total_undelegated:,}, Net={net:,}")
return (total_delegated, total_undelegated, net, events_list)
except Exception as e:
log_message(f"Error fetching delegation metrics: {e}")
return (0, 0, 0, [])
def fetch_network_subgraph_counts(api_key: str) -> List[NetworkIndexerData]:
"""
Fetch network names and count subgraphs and unique indexers per network.
Args:
api_key: The Graph API key
Returns:
List of NetworkIndexerData objects
"""
url = f"https://gateway.thegraph.com/api/{api_key}/subgraphs/id/DZz4kDTdmzWLWsV373w2bSmoar3umKKH9y82SUKr5qmp"
headers = {"Content-Type": "application/json"}
counts = {}
indexers_by_network = {}
skip = 0
page_size = 1000
log_message("Fetching network subgraph counts...")
while True:
query = f"""{{
subgraphs(first: {page_size}, skip: {skip}, where: {{ currentVersion_not: null }}) {{
id
currentVersion {{
subgraphDeployment {{
manifest {{
network
}}
indexerAllocations(first: 1000, where: {{ status: Active }}) {{
indexer {{
id
}}
}}
}}
}}
}}
}}"""
response = requests.post(url, json={"query": query}, headers=headers)
if response.status_code != 200:
log_message(f"Failed to fetch data: {response.status_code}")
break
batch = response.json().get("data", {}).get("subgraphs", [])
if not batch:
break
for item in batch:
deployment = item.get("currentVersion", {}).get("subgraphDeployment", {})
manifest = deployment.get("manifest")
if not manifest:
continue
network = manifest.get("network")
if not network:
continue
counts[network] = counts.get(network, 0) + 1
# Process indexer allocations
allocations = deployment.get("indexerAllocations", [])
if network not in indexers_by_network:
indexers_by_network[network] = set()
for alloc in allocations:
indexer = alloc.get("indexer")
if indexer and "id" in indexer:
indexers_by_network[network].add(indexer["id"])
skip += page_size
result = []
for network, subgraph_count in counts.items():
unique_indexer_count = len(indexers_by_network.get(network, set()))
result.append(NetworkIndexerData(
network_name=network,
subgraph_count=subgraph_count,
unique_indexer_count=unique_indexer_count
))
log_message(f"Fetched subgraph and indexer counts for {len(result)} networks.")
return result
def save_stats_json(network_data: List[NetworkIndexerData], delegation_metrics: tuple,
rewards_metrics: tuple, network_comparison: dict, quarterly_data: list,
output_path: str = "last_stats_run.json"):
"""
Save all statistics to a JSON file.
Args:
network_data: List of NetworkIndexerData objects (subgraph counts)
delegation_metrics: Tuple of (total_delegated, total_undelegated, net, events_list)
rewards_metrics: Tuple of (total_rewards, indexer_rewards, delegator_rewards)
network_comparison: Dictionary with 'arbitrum' and 'ethereum' network stats
quarterly_data: List of quarterly rewards data
output_path: Path to save the JSON file
"""
total_delegated, total_undelegated, net, events_list = delegation_metrics
total_rewards, indexer_rewards, delegator_rewards = rewards_metrics
# Get current date (just the date, no time)
run_date = datetime.now(timezone.utc).strftime("%Y-%m-%d")
# Prepare subgraph count data
subgraph_data = {
"total_all_networks": sum(entry.subgraph_count for entry in network_data),
"networks": []
}
# Sort by subgraph count and get top 20
sorted_network_data = sorted(network_data, key=lambda x: x.subgraph_count, reverse=True)[:20]
total_top_20 = sum(entry.subgraph_count for entry in sorted_network_data)
subgraph_data["total_top_20_networks"] = total_top_20
subgraph_data["top_20_percentage"] = round((total_top_20 / subgraph_data["total_all_networks"] * 100) if subgraph_data["total_all_networks"] > 0 else 0, 2)
for entry in sorted_network_data:
subgraph_data["networks"].append({
"network_name": entry.network_name,
"subgraph_count": entry.subgraph_count,
"unique_indexer_count": entry.unique_indexer_count
})
# Prepare delegation data (without transactions)
delegation_data = {
"total_delegated": total_delegated,
"total_undelegated": total_undelegated,
"net": net,
"total_events": len(events_list),
"delegation_count": len([e for e in events_list if e["type"] == "delegation"]),
"undelegation_count": len([e for e in events_list if e["type"] == "undelegation"])
}
# Hardcoded Ethereum data (network is inactive, data is static)
ETHEREUM_STATIC_DATA = {
"total_rewards": 827351728,
"indexer_rewards": 345569142,
"delegator_rewards": 481782586,
"delegator_count": 17387,
"active_delegators": 9018
}
# Prepare GRT rewards distribution data
rewards_data = {
"total_rewards": total_rewards,
"indexer_rewards": indexer_rewards,
"delegator_rewards": delegator_rewards,
"by_network": {
"arbitrum": {
"total_rewards": network_comparison.get('arbitrum', {}).get('total_rewards', 0),
"indexer_rewards": network_comparison.get('arbitrum', {}).get('indexer_rewards', 0),
"delegator_rewards": network_comparison.get('arbitrum', {}).get('delegator_rewards', 0),
"delegator_count": network_comparison.get('arbitrum', {}).get('delegator_count', 0),
"active_delegators": network_comparison.get('arbitrum', {}).get('active_delegators', 0)
},
"ethereum": ETHEREUM_STATIC_DATA
},
"quarterly": []
}
# Add quarterly data
for quarter in quarterly_data:
rewards_data["quarterly"].append({
"quarter": quarter['quarter'],
"period": quarter['period'],
"total_rewards": quarter['total_rewards'],
"indexer_rewards": quarter['indexer_rewards'],
"delegator_rewards": quarter['delegator_rewards']
})
# Combine all data
stats_data = {
"last_run_date": run_date,
"version": VERSION,
"subgraphs": subgraph_data,
"delegations": delegation_data,
"rewards_distribution": rewards_data
}
# Write JSON file
with open(output_path, 'w', encoding='utf-8') as f:
json.dump(stats_data, f, indent=2, ensure_ascii=False)
log_message(f"Statistics saved to {output_path}")
def generate_html_dashboard(data: List[NetworkIndexerData], delegation_metrics: tuple, rewards_metrics: tuple, network_comparison: dict, quarterly_data: list, output_path: str = "index.html"):
"""
Generate HTML dashboard with network metrics.
Args:
data: List of NetworkIndexerData objects
delegation_metrics: Tuple of (total_delegated, total_undelegated, net, events_list)
rewards_metrics: Tuple of (total_rewards, indexer_rewards, delegator_rewards)
network_comparison: Dictionary with 'arbitrum' and 'ethereum' network stats
quarterly_data: List of quarterly rewards data
output_path: Path to save the HTML file
"""
# Calculate total across all networks
total_all_networks = sum(entry.subgraph_count for entry in data)
# Sort by subgraph count and get top 20
sorted_data = sorted(data, key=lambda x: x.subgraph_count, reverse=True)[:20]
total_top_20 = sum(entry.subgraph_count for entry in sorted_data)
# Calculate percentage
percentage = (total_top_20 / total_all_networks * 100) if total_all_networks > 0 else 0
# Unpack delegation metrics
total_delegated, total_undelegated, net, events_list = delegation_metrics
net_color = "#4CAF50" if net >= 0 else "#f44336"
# Unpack rewards metrics
total_rewards, indexer_rewards, delegator_rewards = rewards_metrics
# Convert events_list to JSON string for JavaScript embedding
events_json = json.dumps(events_list).replace('</script>', '<\\/script>')
timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")
html_content = f"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Real-time dashboard showing The Graph Protocol metrics across the top 20 blockchain networks.">
<meta name="robots" content="index, follow">
<meta property="og:title" content="The Graph Protocol Metrics Dashboard">
<meta property="og:description" content="Explore network metrics for The Graph Protocol's top 20 networks including subgraph counts and unique indexers.">
<meta property="og:type" content="website">
<title>The Graph Protocol Metrics</title>
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600&display=swap" rel="stylesheet">
<style>
* {{
margin: 0;
padding: 0;
box-sizing: border-box;
}}
body {{
font-family: 'Poppins', 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: #0C0A1D;
min-height: 100vh;
padding: 20px;
color: #F8F6FF;
}}
.breadcrumb {{
max-width: 1200px;
margin: 0 auto 15px auto;
padding: 12px 20px;
background: rgba(12, 10, 29, 0.6);
border-radius: 8px;
border: 1px solid #9CA3AF;
color: #F8F6FF;
font-size: 14px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
}}
.breadcrumb-left {{
display: flex;
align-items: center;
gap: 8px;
}}
.period-toggle {{
display: flex;
align-items: center;
background: rgba(12, 10, 29, 0.8);
border: 2px solid #9CA3AF;
border-radius: 25px;
padding: 4px;
gap: 4px;
cursor: pointer;
user-select: none;
}}
.period-toggle-option {{
padding: 6px 16px;
border-radius: 20px;
font-size: 13px;
font-weight: 500;
transition: all 0.3s ease;
color: #9CA3AF;
background: transparent;
}}
.period-toggle-option.active {{
color: #F8F6FF;
background: #6F4CFF;
border-color: #6F4CFF;
}}
.period-toggle-option:not(.active):hover {{
color: #F8F6FF;
}}
.breadcrumb a {{
color: #9CA3AF;
text-decoration: none;
transition: color 0.3s ease;
display: inline-flex;
align-items: center;
gap: 6px;
}}
.breadcrumb a:hover {{
color: #F8F6FF;
}}
.breadcrumb-separator {{
color: #9CA3AF;
margin: 0 4px;
font-weight: 300;
}}
.home-icon {{
width: 16px;
height: 16px;
display: inline-block;
position: relative;
}}
.home-icon::before {{
content: '';
position: absolute;
left: 50%;
top: 0;
transform: translateX(-50%);
width: 0;
height: 0;
border-left: 8px solid transparent;
border-right: 8px solid transparent;
border-bottom: 8px solid currentColor;
}}
.home-icon::after {{
content: '';
position: absolute;
left: 2px;
bottom: 0;
width: 12px;
height: 9px;
background-color: currentColor;
}}
.container {{
max-width: 1200px;
margin: 0 auto;
background: #0C0A1D;
border-radius: 15px;
box-shadow: 0 20px 40px rgba(0,0,0,0.3);
overflow: hidden;
border: 1px solid #9CA3AF;
}}
.header {{
background: #0C0A1D;
color: #F8F6FF;
padding: 30px;
border-bottom: 1px solid #9CA3AF;
text-align: center;
}}
.header h1 {{
font-size: 2.2em;
margin: 0 0 10px 0;
font-weight: 500;
}}
.header .subtitle {{
font-size: 0.95em;
opacity: 0.8;
font-weight: 300;
}}
.content {{
padding: 30px;
}}
.stats-container {{
display: flex;
gap: 15px;
margin-bottom: 30px;
justify-content: flex-start;
flex-wrap: wrap;
}}
.stats-card {{
background: rgba(12, 10, 29, 0.6);
border: 1px solid #9CA3AF;
border-radius: 10px;
padding: 20px;
text-align: center;
flex: 0 0 200px;
height: 180px;
display: grid;
grid-template-rows: 45px 1fr 35px;
align-items: center;
}}
.stats-card h2 {{
font-size: 0.95em;
margin: 0;
color: #9CA3AF;
font-weight: 400;
line-height: 1.2;
align-self: start;
padding-top: 5px;
}}
.stats-card .total {{
font-size: 1.5em;
color: #F8F6FF;
font-weight: 600;
margin: 0;
line-height: 1;
align-self: center;
}}
.stats-card .percentage {{
font-size: 0.85em;
color: #9CA3AF;
margin: 0;
align-self: end;
padding-bottom: 5px;
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
}}
.toggle-arrow {{
cursor: pointer;
font-size: 1.5em;
color: #F8F6FF;
font-weight: bold;
transition: all 0.3s ease;
user-select: none;
padding: 6px;
border-radius: 6px;
background: rgba(111, 76, 255, 0.3);
border: 2px solid #6F4CFF;
margin-left: 8px;
display: inline-flex;
align-items: center;
justify-content: center;
width: 32px;
height: 32px;
}}
.toggle-arrow:hover {{
color: #FFFFFF;
background: rgba(111, 76, 255, 0.5);
border-color: #8B6FFF;
transform: scale(1.1);
}}
.toggle-arrow.expanded {{
transform: rotate(90deg);
background: rgba(111, 76, 255, 0.5);
}}
.toggle-arrow.expanded:hover {{
transform: rotate(90deg) scale(1.1);
}}
.tooltip {{
position: relative;
cursor: help;
}}
.tooltip .tooltip-text {{
visibility: hidden;
background-color: #333;
color: #F8F6FF;
text-align: center;
padding: 8px 12px;
border-radius: 6px;
position: absolute;
z-index: 9999;
bottom: 105%;
left: 50%;
transform: translateX(-50%);
opacity: 0;
transition: opacity 0.3s;
white-space: nowrap;
font-size: 0.85em;
}}
.tooltip .tooltip-text::after {{
content: "";
position: absolute;
top: 100%;
left: 50%;
margin-left: -5px;
border-width: 5px;
border-style: solid;
border-color: #333 transparent transparent transparent;
}}
.tooltip:hover .tooltip-text {{
visibility: visible;
opacity: 1;
}}
#delegationTable {{
margin-top: 20px;
display: none;
}}
#delegationTable table {{
font-size: 0.9em;
}}
#delegationTable th {{
font-size: 0.9em;
}}
#delegationTable td {{
font-size: 0.85em;
}}
#networkComparisonTable {{
margin-top: 20px;
display: none;
padding-bottom: 20px;