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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
 
# πŸš€ Cryptocurrency API Resource Monitor

**Comprehensive cryptocurrency market intelligence API resource management system**

Monitor and manage all API resources from blockchain explorers, market data providers, RPC nodes, news feeds, and more. Track online status, validate endpoints, categorize by domain, and maintain availability metrics across all cryptocurrency data sources.
 

## πŸ“‹ Table of Contents

- [Features](#-features)
- [Monitored Resources](#-monitored-resources)
- [Quick Start](#-quick-start)
- [Usage](#-usage)
- [Architecture](#-architecture)
- [API Categories](#-api-categories)
- [Status Classification](#-status-classification)
- [Alert Conditions](#-alert-conditions)
- [Failover Management](#-failover-management)
- [Dashboard](#-dashboard)
- [Configuration](#-configuration)

 

## ✨ Features

### Core Monitoring
- βœ… **Real-time health checks** for 50+ cryptocurrency APIs
- βœ… **Response time tracking** with millisecond precision
- βœ… **Success/failure rate monitoring** per provider
- βœ… **Automatic status classification** (ONLINE/DEGRADED/SLOW/UNSTABLE/OFFLINE)
- βœ… **SSL certificate validation** and expiration tracking
- βœ… **Rate limit detection** (429, 403 responses)

### Redundancy & Failover
- βœ… **Automatic failover chain building** for each data type
- βœ… **Multi-tier resource prioritization** (TIER-1 critical, TIER-2 high, TIER-3 medium, TIER-4 low)
- βœ… **Single Point of Failure (SPOF) detection**
- βœ… **Backup provider recommendations**
- βœ… **Cross-provider data validation**

### Alerting & Reporting
- βœ… **Critical alert system** for TIER-1 API failures
- βœ… **Performance degradation warnings**
- βœ… **JSON export reports** for integration
- βœ… **Historical uptime statistics**
- βœ… **Real-time web dashboard** with auto-refresh

### Security & Privacy
- βœ… **API key masking** in all outputs (first/last 4 chars only)
- βœ… **Secure credential storage** from registry
- βœ… **Rate limit compliance** with configurable delays
- βœ… **CORS proxy support** for browser compatibility

 
## 🌐 Monitored Resources

### Blockchain Explorers
- **Etherscan** (2 keys): Ethereum blockchain data, transactions, smart contracts
- **BscScan** (1 key): BSC blockchain explorer, BEP-20 tokens
- **TronScan** (1 key): Tron network explorer, TRC-20 tokens

### Market Data Providers
- **CoinGecko**: Real-time prices, market caps, trending coins (FREE)
- **CoinMarketCap** (2 keys): Professional market data
- **CryptoCompare** (1 key): OHLCV data, historical snapshots
- **CoinPaprika**: Comprehensive market information
- **CoinCap**: Asset pricing and exchange rates

### RPC Nodes
**Ethereum:** Ankr, PublicNode, Cloudflare, LlamaNodes
**BSC:** Official BSC, Ankr, PublicNode
**Polygon:** Official, Ankr
**Tron:** TronGrid, TronStack

### News & Sentiment
- **CryptoPanic**: Aggregated news with sentiment scores
- **NewsAPI** (1 key): General crypto news
- **Alternative.me**: Fear & Greed Index
- **Reddit**: r/cryptocurrency JSON feeds

### Additional Resources
- **Whale Tracking**: WhaleAlert API
- **CORS Proxies**: AllOrigins, CORS.SH, Corsfix, ThingProxy
- **On-Chain Analytics**: The Graph, Blockchair

**Total: 50+ monitored endpoints across 7 categories**

 
## πŸš€ Quick Start

### Prerequisites
- Node.js 14.0.0 or higher
- Python 3.x (for dashboard server)

### Installation

```bash
# Clone the repository
git clone https://github.com/nimazasinich/crypto-dt-source.git
cd crypto-dt-source

# No dependencies to install - uses Node.js built-in modules!
```

### Run Your First Health Check

```bash
# Run a complete health check
node api-monitor.js

# This will:
# - Load API keys from all_apis_merged_2025.json
# - Check all 50+ endpoints
# - Generate api-monitor-report.json
# - Display status report in terminal
```

### View the Dashboard

 # Start the web server
npm run dashboard

# Open in browser:
# http://localhost:8080/dashboard.html
```

---

## πŸ“– Usage

### 1. Single Health Check

```bash
node api-monitor.js
```

**Output:**
```
βœ“ Registry loaded successfully
  Found 7 API key categories

╔════════════════════════════════════════════════════════╗
β•‘  CRYPTOCURRENCY API RESOURCE MONITOR - Health Check   β•‘
β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•

  Checking blockchainExplorers...
  Checking marketData...
  Checking newsAndSentiment...
  Checking rpcNodes...

╔════════════════════════════════════════════════════════╗
β•‘              RESOURCE STATUS REPORT                    β•‘
β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•

πŸ“ BLOCKCHAINEXPLORERS
────────────────────────────────────────────────────────
  βœ“ Etherscan-1              ONLINE        245ms [TIER-1]
  βœ“ Etherscan-2              ONLINE        312ms [TIER-1]
  βœ“ BscScan                  ONLINE        189ms [TIER-1]
  βœ“ TronScan                 ONLINE        567ms [TIER-2]

πŸ“ MARKETDATA
────────────────────────────────────────────────────────
  βœ“ CoinGecko                ONLINE        142ms [TIER-1]
  βœ“ CoinGecko-Price          ONLINE        156ms [TIER-1]
  ◐ CoinMarketCap-1          DEGRADED     2340ms [TIER-1]
  βœ“ CoinMarketCap-2          ONLINE        487ms [TIER-1]
  βœ“ CryptoCompare            ONLINE        298ms [TIER-2]

╔════════════════════════════════════════════════════════╗
β•‘                    SUMMARY                             β•‘
β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•
  Total Resources:    52
  Online:             48 (92.3%)
  Degraded:           3 (5.8%)
  Offline:            1 (1.9%)
  Overall Health:     92.3%

βœ“ Report exported to api-monitor-report.json
```

### 2. Continuous Monitoring

```bash
node api-monitor.js --continuous
```

Runs health checks every 5 minutes and continuously updates the report.

### 3. Failover Analysis

```bash
node failover-manager.js
```

**Output:**
```
╔════════════════════════════════════════════════════════╗
β•‘         FAILOVER CHAIN BUILDER                         β•‘
β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•

πŸ“Š ETHEREUMPRICE Failover Chain:
────────────────────────────────────────────────────────
  🎯 [PRIMARY]     CoinGecko                 ONLINE        142ms [TIER-1]
    ↓ [BACKUP]     CoinMarketCap-2           ONLINE        487ms [TIER-1]
    ↓ [BACKUP-2]   CryptoCompare             ONLINE        298ms [TIER-2]
    ↓ [BACKUP-3]   CoinPaprika               ONLINE        534ms [TIER-2]

πŸ“Š ETHEREUMEXPLORER Failover Chain:
────────────────────────────────────────────────────────
  🎯 [PRIMARY]     Etherscan-1               ONLINE        245ms [TIER-1]
    ↓ [BACKUP]     Etherscan-2               ONLINE        312ms [TIER-1]

╔════════════════════════════════════════════════════════╗
β•‘       SINGLE POINT OF FAILURE ANALYSIS                β•‘
β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•

  🟑 [MEDIUM] rpcPolygon: Only two resources available
  🟠 [HIGH] sentiment: Only one resource available (SPOF)

βœ“ Failover configuration exported to failover-config.json
```

### 4. Launch Complete Dashboard

```bash
npm run full-check
```

Runs monitor β†’ failover analysis β†’ starts web dashboard

---

## πŸ—οΈ Architecture

```
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                  API REGISTRY JSON                      β”‚
β”‚         (all_apis_merged_2025.json)                     β”‚
β”‚  - Discovered keys (masked)                             β”‚
β”‚  - Raw API configurations                               β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                     β”‚
                     β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚              CRYPTO API MONITOR                         β”‚
β”‚                (api-monitor.js)                         β”‚
β”‚                                                         β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”           β”‚
β”‚  β”‚  Resource Loader                        β”‚           β”‚
β”‚  β”‚  - Parse registry                       β”‚           β”‚
β”‚  β”‚  - Extract API keys                     β”‚           β”‚
β”‚  β”‚  - Build endpoint URLs                  β”‚           β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜           β”‚
β”‚                     β”‚                                   β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”           β”‚
β”‚  β”‚  Health Check Engine                    β”‚           β”‚
β”‚  β”‚  - HTTP/HTTPS requests                  β”‚           β”‚
β”‚  β”‚  - Response time measurement            β”‚           β”‚
β”‚  β”‚  - Status code validation               β”‚           β”‚
β”‚  β”‚  - RPC endpoint testing                 β”‚           β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜           β”‚
β”‚                     β”‚                                   β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”           β”‚
β”‚  β”‚  Status Classifier                      β”‚           β”‚
β”‚  β”‚  - Success rate calculation             β”‚           β”‚
β”‚  β”‚  - Response time averaging              β”‚           β”‚
β”‚  β”‚  - ONLINE/DEGRADED/OFFLINE              β”‚           β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜           β”‚
β”‚                     β”‚                                   β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”           β”‚
β”‚  β”‚  Alert System                           β”‚           β”‚
β”‚  β”‚  - TIER-1 failure detection             β”‚           β”‚
β”‚  β”‚  - Performance warnings                 β”‚           β”‚
β”‚  β”‚  - Critical notifications               β”‚           β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜           β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                     β”‚
                     β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚            MONITORING REPORT JSON                       β”‚
β”‚         (api-monitor-report.json)                       β”‚
β”‚  - Summary statistics                                   β”‚
β”‚  - Per-resource status                                  β”‚
β”‚  - Historical data                                      β”‚
β”‚  - Active alerts                                        β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
         β”‚                              β”‚
         β–Ό                              β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  FAILOVER MANAGER   β”‚    β”‚    WEB DASHBOARD             β”‚
β”‚ (failover-manager)  β”‚    β”‚   (dashboard.html)           β”‚
β”‚                     β”‚    β”‚                              β”‚
β”‚ - Build chains      β”‚    β”‚  - Real-time visualization   β”‚
β”‚ - SPOF detection    β”‚    β”‚  - Auto-refresh              β”‚
β”‚ - Redundancy report β”‚    β”‚  - Alert display             β”‚
β”‚ - Export config     β”‚    β”‚  - Health metrics            β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
```

---

## πŸ“Š API Categories

### 1. Blockchain Explorers
**Purpose:** Query blockchain data, transactions, balances, smart contracts

**Resources:**
- Etherscan (Ethereum) - 2 keys
- BscScan (BSC) - 1 key
- TronScan (Tron) - 1 key

**Use Cases:**
- Get wallet balances
- Track transactions
- Monitor token transfers
- Query smart contracts
- Get gas prices

### 2. Market Data
**Purpose:** Real-time cryptocurrency prices, market caps, volume

**Resources:**
- CoinGecko (FREE, no key required) ⭐
- CoinMarketCap - 2 keys
- CryptoCompare - 1 key
- CoinPaprika (FREE)
- CoinCap (FREE)

**Use Cases:**
- Live price feeds
- Historical OHLCV data
- Market cap rankings
- Trading volume
- Trending coins

### 3. RPC Nodes
**Purpose:** Direct blockchain interaction via JSON-RPC

**Resources:**
- **Ethereum:** Ankr, PublicNode, Cloudflare, LlamaNodes
- **BSC:** Official, Ankr, PublicNode
- **Polygon:** Official, Ankr
- **Tron:** TronGrid, TronStack

**Use Cases:**
- Send transactions
- Read smart contracts
- Get block data
- Subscribe to events
- Query state

### 4. News & Sentiment
**Purpose:** Crypto news aggregation and market sentiment

**Resources:**
- CryptoPanic (FREE)
- Alternative.me Fear & Greed Index (FREE)
- NewsAPI - 1 key
- Reddit r/cryptocurrency (FREE)

**Use Cases:**
- News feed aggregation
- Sentiment analysis
- Fear & Greed tracking
- Social signals

### 5. Whale Tracking
**Purpose:** Monitor large cryptocurrency transactions

**Resources:**
- WhaleAlert API

**Use Cases:**
- Track whale movements
- Exchange flow monitoring
- Large transaction alerts

### 6. CORS Proxies
**Purpose:** Bypass CORS restrictions in browser applications

**Resources:**
- AllOrigins (unlimited)
- CORS.SH (fast)
- Corsfix (60 req/min)
- ThingProxy (10 req/sec)

**Use Cases:**
- Browser-based API calls
- Frontend applications
- CORS workarounds

---

## πŸ“ˆ Status Classification

The monitor automatically classifies each API into one of five states:

| Status | Success Rate | Response Time | Description |
|--------|--------------|---------------|-------------|
| 🟒 **ONLINE** | β‰₯95% | <2 seconds | Fully operational, optimal performance |
| 🟑 **DEGRADED** | 80-95% | 2-5 seconds | Functional but slower than normal |
| 🟠 **SLOW** | 70-80% | 5-10 seconds | Significant performance issues |
| πŸ”΄ **UNSTABLE** | 50-70% | Any | Frequent failures, unreliable |
| ⚫ **OFFLINE** | <50% | Any | Not responding or completely down |

**Classification Logic:**
- Based on last 10 health checks
- Success rate = successful responses / total attempts
- Response time = average of successful requests only

---

## ⚠️ Alert Conditions

The system triggers alerts for:

### Critical Alerts
- ❌ TIER-1 API offline (Etherscan, CoinGecko, Infura, Alchemy)
- ❌ All providers in a category offline
- ❌ Zero available resources for essential data type

### Warning Alerts
- ⚠️ Response time >5 seconds sustained for 15 minutes
- ⚠️ Success rate dropped below 80%
- ⚠️ Single Point of Failure (only 1 provider available)
- ⚠️ Rate limit reached (>80% consumed)

### Info Alerts
- ℹ️ API key approaching expiration
- ℹ️ SSL certificate expires within 7 days
- ℹ️ New resource added to registry

---

## πŸ”„ Failover Management

### Automatic Failover Chains

The system builds intelligent failover chains for each data type:

```javascript
// Example: Ethereum Price Failover Chain
const failoverConfig = require('./failover-config.json');

async function getEthereumPrice() {
  const chain = failoverConfig.chains.ethereumPrice;

  for (const resource of chain) {
    try {
      // Try primary first (CoinGecko)
      const response = await fetch(resource.url + '/api/v3/simple/price?ids=ethereum&vs_currencies=usd');
      const data = await response.json();
      return data.ethereum.usd;
    } catch (error) {
      console.log(`${resource.name} failed, trying next in chain...`);
      continue;
    }
  }

  throw new Error('All resources in failover chain failed');
}
```

### Priority Tiers

**TIER-1 (CRITICAL):** Etherscan, BscScan, CoinGecko, Infura, Alchemy
**TIER-2 (HIGH):** CoinMarketCap, CryptoCompare, TronScan, NewsAPI
**TIER-3 (MEDIUM):** Alternative.me, Reddit, CORS proxies, public RPCs
**TIER-4 (LOW):** Experimental APIs, community nodes, backup sources

Failover chains prioritize lower tier numbers first.

---

## 🎨 Dashboard

### Features

- **Real-time monitoring** with auto-refresh every 5 minutes
- **Visual health indicators** with color-coded status
- **Category breakdown** showing all resources by type
- **Alert notifications** prominently displayed
- **Health bar** showing overall system status
- **Response times** for each endpoint
- **Tier badges** showing resource priority

### Screenshots

**Summary Cards:**
```
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ Total Resources β”‚  β”‚     Online      β”‚  β”‚    Degraded     β”‚  β”‚     Offline     β”‚
β”‚       52        β”‚  β”‚  48 (92.3%)     β”‚  β”‚   3 (5.8%)      β”‚  β”‚   1 (1.9%)      β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
```

**Resource List:**
```
πŸ” BLOCKCHAIN EXPLORERS
───────────────────────────────────────────────────
βœ“ Etherscan-1    [TIER-1]    ONLINE     245ms
βœ“ Etherscan-2    [TIER-1]    ONLINE     312ms
βœ“ BscScan        [TIER-1]    ONLINE     189ms
```

### Access

```bash
npm run dashboard
# Open: http://localhost:8080/dashboard.html
```

---

## βš™οΈ Configuration

### Monitor Configuration

Edit `api-monitor.js`:

```javascript
const CONFIG = {
  REGISTRY_FILE: './all_apis_merged_2025.json',
  CHECK_INTERVAL: 5 * 60 * 1000,  // 5 minutes
  TIMEOUT: 10000,                  // 10 seconds
  MAX_RETRIES: 3,
  RETRY_DELAY: 2000,

  THRESHOLDS: {
    ONLINE: { responseTime: 2000, successRate: 0.95 },
    DEGRADED: { responseTime: 5000, successRate: 0.80 },
    SLOW: { responseTime: 10000, successRate: 0.70 },
    UNSTABLE: { responseTime: Infinity, successRate: 0.50 }
  }
};
```

### Adding New Resources

Edit the `API_REGISTRY` object in `api-monitor.js`:

```javascript
marketData: {
  // ... existing resources ...

  newProvider: [
    {
      name: 'MyNewAPI',
      url: 'https://api.example.com',
      testEndpoint: '/health',
      requiresKey: false,
      tier: 3
    }
  ]
}
```

---

## πŸ” Security Notes

- βœ… API keys are **never logged** in full (masked to first/last 4 chars)
- βœ… Registry file should be kept **secure** and not committed to public repos
- βœ… Use **environment variables** for production deployments
- βœ… Rate limits are **automatically respected** with delays
- βœ… SSL/TLS is used for all external API calls

---

## πŸ“ Output Files

| File | Purpose | Format |
|------|---------|--------|
| `api-monitor-report.json` | Complete health check results | JSON |
| `failover-config.json` | Failover chain configuration | JSON |

### api-monitor-report.json Structure

```json
{
  "timestamp": "2025-11-10T22:30:00.000Z",
  "summary": {
    "totalResources": 52,
    "onlineResources": 48,
    "degradedResources": 3,
    "offlineResources": 1
  },
  "categories": {
    "blockchainExplorers": [...],
    "marketData": [...],
    "rpcNodes": [...]
  },
  "alerts": [
    {
      "severity": "CRITICAL",
      "message": "TIER-1 API offline: Etherscan-1",
      "timestamp": "2025-11-10T22:28:15.000Z"
    }
  ],
  "history": {
    "CoinGecko": [
      {
        "success": true,
        "responseTime": 142,
        "timestamp": "2025-11-10T22:30:00.000Z"
      }
    ]
  }
}
```

---

## πŸ› οΈ Troubleshooting

### "Failed to load registry"

**Cause:** `all_apis_merged_2025.json` not found
**Solution:** Ensure the file exists in the same directory

### "Request timeout" errors

**Cause:** API endpoint is slow or down
**Solution:** Normal behavior, will be classified as SLOW/OFFLINE

### "CORS error" in dashboard

**Cause:** Report JSON not accessible
**Solution:** Run `npm run dashboard` to start local server

### Rate limit errors (429)

**Cause:** Too many requests to API
**Solution:** Increase `CHECK_INTERVAL` or reduce resource list

---

## πŸ“œ License

MIT License - see LICENSE file for details

---

## 🀝 Contributing

Contributions welcome! To add new API resources:

1. Update `API_REGISTRY` in `api-monitor.js`
2. Add test endpoint
3. Classify into appropriate tier
4. Update this README

---

## πŸ“ž Support

For issues or questions:
- Open an issue on GitHub
- Check the troubleshooting section
- Review configuration opt

**Built with ❀️ for the cryptocurrency community**

*Monitor smarter, not harder
# Crypto Resource Aggregator

A centralized API aggregator for cryptocurrency resources hosted on Hugging Face Spaces.

## Overview

This aggregator consolidates multiple cryptocurrency data sources including:
- **Block Explorers**: Etherscan, BscScan, TronScan
- **Market Data**: CoinGecko, CoinMarketCap, CryptoCompare
- **RPC Endpoints**: Ethereum, BSC, Tron, Polygon
- **News APIs**: Crypto news and sentiment analysis
- **Whale Tracking**: Large transaction monitoring
- **On-chain Analytics**: Blockchain data analysis

## Features

### βœ… Real-Time Monitoring
- Continuous health checks for all resources
- Automatic status updates (online/offline)
- Response time tracking
- Consecutive failure counting

### πŸ“Š History Tracking
- Complete query history with timestamps
- Resource usage statistics
- Success/failure rates
- Average response times

### πŸ”„ No Mock Data
- All responses return real data from actual APIs
- Error status returned when resources are unavailable
- Transparent error messaging

### πŸš€ Fallback Support
- Automatic fallback to alternative resources
- Multiple API keys for rate limit management
- CORS proxy support for browser access

## API Endpoints

### Resource Management

#### `GET /`
Root endpoint with API information and available endpoints.

#### `GET /resources`
List all available resource categories and their counts.

**Response:**
```json
{
  "total_categories": 7,
  "resources": {
    "block_explorers": ["etherscan", "bscscan", "tronscan"],
    "market_data": ["coingecko", "coinmarketcap"],
    "rpc_endpoints": [...],
    ...
  },
  "timestamp": "2025-11-10T..."
}
```

#### `GET /resources/{category}`
Get all resources in a specific category.

**Example:** `/resources/market_data`

### Query Resources

#### `POST /query`
Query a specific resource with parameters.

**Request Body:**
```json
{
  "resource_type": "market_data",
  "resource_name": "coingecko",
  "endpoint": "/simple/price",
  "params": {
    "ids": "bitcoin,ethereum",
    "vs_currencies": "usd"
  }
}
```

**Response:**
```json
{
  "success": true,
  "resource_type": "market_data",
  "resource_name": "coingecko",
  "data": {
    "bitcoin": {"usd": 45000},
    "ethereum": {"usd": 3000}
  },
  "response_time": 0.234,
  "timestamp": "2025-11-10T..."
}
```

### Status Monitoring

#### `GET /status`
Get real-time status of all resources.

**Response:**
```json
{
  "total_resources": 15,
  "online": 13,
  "offline": 2,
  "resources": [
    {
      "resource": "block_explorers.etherscan",
      "status": "online",
      "response_time": 0.123,
      "error": null,
      "timestamp": "2025-11-10T..."
    },
    ...
  ],
  "timestamp": "2025-11-10T..."
}
```

#### `GET /status/{category}/{name}`
Check status of a specific resource.

**Example:** `/status/market_data/coingecko`

### History & Analytics

#### `GET /history`
Get query history (default: last 100 queries).

**Query Parameters:**
- `limit` (optional): Number of records to return (default: 100)
- `resource_type` (optional): Filter by resource type

**Response:**
```json
{
  "count": 100,
  "history": [
    {
      "id": 1,
      "timestamp": "2025-11-10T10:30:00",
      "resource_type": "market_data",
      "resource_name": "coingecko",
      "endpoint": "https://api.coingecko.com/...",
      "status": "success",
      "response_time": 0.234,
      "error_message": null
    },
    ...
  ]
}
```

#### `GET /history/stats`
Get aggregated statistics from query history.

**Response:**
```json
{
  "total_queries": 1523,
  "successful_queries": 1487,
  "success_rate": 97.6,
  "most_queried_resources": [
    {"resource": "coingecko", "count": 456},
    {"resource": "etherscan", "count": 234}
  ],
  "average_response_time": 0.345,
  "timestamp": "2025-11-10T..."
}
```

#### `GET /health`
System health check endpoint.

## Usage Examples

### JavaScript/TypeScript

```javascript
// Get Bitcoin price from CoinGecko
const response = await fetch('https://your-space.hf.space/query', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    resource_type: 'market_data',
    resource_name: 'coingecko',
    endpoint: '/simple/price',
    params: {
      ids: 'bitcoin',
      vs_currencies: 'usd'
    }
  })
});

const data = await response.json();
console.log('BTC Price:', data.data.bitcoin.usd);

// Check Ethereum balance
const balanceResponse = await fetch('https://your-space.hf.space/query', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    resource_type: 'block_explorers',
    resource_name: 'etherscan',
    endpoint: '',
    params: {
      module: 'account',
      action: 'balance',
      address: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb',
      tag: 'latest'
    }
  })
});

const balanceData = await balanceResponse.json();
console.log('ETH Balance:', balanceData.data.result / 1e18);
```

### Python

```python
import requests

# Query CoinGecko for multiple coins
response = requests.post('https://your-space.hf.space/query', json={
    'resource_type': 'market_data',
    'resource_name': 'coingecko',
    'endpoint': '/simple/price',
    'params': {
        'ids': 'bitcoin,ethereum,tron',
        'vs_currencies': 'usd,eur'
    }
})

data = response.json()
if data['success']:
    print('Prices:', data['data'])
else:
    print('Error:', data['error'])

# Get resource status
status = requests.get('https://your-space.hf.space/status')
print(f"Resources online: {status.json()['online']}/{status.json()['total_resources']}")
```

### cURL

```bash
# List all resources
curl https://your-space.hf.space/resources

# Query a resource
curl -X POST https://your-space.hf.space/query \
  -H "Content-Type: application/json" \
  -d '{
    "resource_type": "market_data",
    "resource_name": "coingecko",
    "endpoint": "/simple/price",
    "params": {
      "ids": "bitcoin",
      "vs_currencies": "usd"
    }
  }'

# Get status
curl https://your-space.hf.space/status

# Get history
curl https://your-space.hf.space/history?limit=50
```

## Resource Categories

### Block Explorers
- **Etherscan**: Ethereum blockchain explorer with API key
- **BscScan**: BSC blockchain explorer with API key
- **TronScan**: Tron blockchain explorer with API key

### Market Data
- **CoinGecko**: Free, no API key required
- **CoinMarketCap**: Requires API key, 333 calls/day free tier
- **CryptoCompare**: 100K calls/month free tier

### RPC Endpoints
- Ethereum (Infura, Alchemy, Ankr)
- Binance Smart Chain
- Tron
- Polygon

## Database Schema

### query_history
Tracks all API queries made through the aggregator.

```sql
CREATE TABLE query_history (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
    resource_type TEXT NOT NULL,
    resource_name TEXT NOT NULL,
    endpoint TEXT NOT NULL,
    status TEXT NOT NULL,
    response_time REAL,
    error_message TEXT
);
```

### resource_status
Tracks the health status of each resource.

```sql
CREATE TABLE resource_status (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    resource_name TEXT NOT NULL UNIQUE,
    last_check DATETIME DEFAULT CURRENT_TIMESTAMP,
    status TEXT NOT NULL,
    consecutive_failures INTEGER DEFAULT 0,
    last_success DATETIME,
    last_error TEXT
);
```

## Error Handling

The aggregator returns structured error responses:

```json
{
  "success": false,
  "resource_type": "market_data",
  "resource_name": "coinmarketcap",
  "error": "HTTP 429 - Rate limit exceeded",
  "response_time": 0.156,
  "timestamp": "2025-11-10T..."
}
```

## Deployment on Hugging Face

1. Create a new Space on Hugging Face
2. Select "Gradio" as the SDK (we'll use FastAPI which is compatible)
3. Upload the following files:
   - `app.py`
   - `requirements.txt`
   - `all_apis_merged_2025.json`
   - `README.md`
4. The Space will automatically deploy

## Local Development

```bash
# Install dependencies
pip install -r requirements.txt

# Run the application
python app.py

# Access the API
# Documentation: http://localhost:7860/docs
# API: http://localhost:7860
```

## Integration with Your Main App

```javascript
// Create a client wrapper
class CryptoAggregator {
  constructor(baseUrl = 'https://your-space.hf.space') {
    this.baseUrl = baseUrl;
  }

  async query(resourceType, resourceName, endpoint = '', params = {}) {
    const response = await fetch(`${this.baseUrl}/query`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        resource_type: resourceType,
        resource_name: resourceName,
        endpoint: endpoint,
        params: params
      })
    });
    return await response.json();
  }

  async getStatus() {
    const response = await fetch(`${this.baseUrl}/status`);
    return await response.json();
  }

  async getHistory(limit = 100) {
    const response = await fetch(`${this.baseUrl}/history?limit=${limit}`);
    return await response.json();
  }
}

// Usage
const aggregator = new CryptoAggregator();

// Get Bitcoin price
const price = await aggregator.query('market_data', 'coingecko', '/simple/price', {
  ids: 'bitcoin',
  vs_currencies: 'usd'
});

// Check system status
const status = await aggregator.getStatus();
console.log(`${status.online}/${status.total_resources} resources online`);
```

## Monitoring & Maintenance

- Check `/status` regularly to ensure resources are online
- Monitor `/history/stats` for usage patterns and success rates
- Review consecutive failures in the database
- Update API keys when needed

## License

This aggregator is built for educational and development purposes.
API keys should be kept secure and rate limits respected.

## Support

For issues or questions:
1. Check the `/health` endpoint
2. Review `/history` for error patterns
3. Verify resource status with `/status`
4. Check individual resource documentation

---

Built with FastAPI and deployed on Hugging Face Spaces