File size: 10,537 Bytes
b190b45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**

 * API Configuration for Frontend

 * Connects to Smart Fallback System with 305+ resources

 */

// Auto-detect API base URL
const API_BASE_URL = window.location.origin;

// API Configuration
window.API_CONFIG = {
    // Base URLs
    baseUrl: API_BASE_URL,
    apiUrl: `${API_BASE_URL}/api`,
    smartApiUrl: `${API_BASE_URL}/api/smart`,
    
    // Endpoints - Smart Fallback (NEVER 404)
    endpoints: {
        // Smart endpoints (use these - they never fail)
        smart: {
            market: `${API_BASE_URL}/api/smart/market`,
            news: `${API_BASE_URL}/api/smart/news`,
            sentiment: `${API_BASE_URL}/api/smart/sentiment`,
            whaleAlerts: `${API_BASE_URL}/api/smart/whale-alerts`,
            blockchain: `${API_BASE_URL}/api/smart/blockchain`,
            healthReport: `${API_BASE_URL}/api/smart/health-report`,
            stats: `${API_BASE_URL}/api/smart/stats`,
        },
        
        // Original endpoints (fallback to these if needed)
        market: `${API_BASE_URL}/api/market`,
        marketHistory: `${API_BASE_URL}/api/market/history`,
        sentiment: `${API_BASE_URL}/api/sentiment/analyze`,
        health: `${API_BASE_URL}/api/health`,
        
        // Alpha Vantage
        alphavantage: {
            health: `${API_BASE_URL}/api/alphavantage/health`,
            prices: `${API_BASE_URL}/api/alphavantage/prices`,
            ohlcv: `${API_BASE_URL}/api/alphavantage/ohlcv`,
            marketStatus: `${API_BASE_URL}/api/alphavantage/market-status`,
            cryptoRating: `${API_BASE_URL}/api/alphavantage/crypto-rating`,
            quote: `${API_BASE_URL}/api/alphavantage/quote`,
        },
        
        // Massive.com
        massive: {
            health: `${API_BASE_URL}/api/massive/health`,
            dividends: `${API_BASE_URL}/api/massive/dividends`,
            splits: `${API_BASE_URL}/api/massive/splits`,
            quotes: `${API_BASE_URL}/api/massive/quotes`,
            trades: `${API_BASE_URL}/api/massive/trades`,
            aggregates: `${API_BASE_URL}/api/massive/aggregates`,
            ticker: `${API_BASE_URL}/api/massive/ticker`,
            marketStatus: `${API_BASE_URL}/api/massive/market-status`,
        },
        
        // Documentation
        docs: `${API_BASE_URL}/docs`,
        redoc: `${API_BASE_URL}/redoc`,
    },
    
    // Feature flags
    features: {
        useSmartFallback: true,      // Always use smart fallback
        resourceRotation: true,       // Rotate through resources
        proxySupport: true,           // Use proxy for sanctioned exchanges
        backgroundCollection: true,   // 24/7 data collection
        healthMonitoring: true,       // Monitor resource health
        autoCleanup: true,            // Auto-remove dead resources
    },
    
    // Request configuration
    request: {
        timeout: 30000,               // 30 seconds
        retries: 3,                   // Retry 3 times
        retryDelay: 1000,            // Wait 1 second between retries
    },
    
    // Resource information
    resources: {
        total: '305+',
        categories: {
            marketData: 21,
            blockExplorers: 40,
            news: 15,
            sentiment: 12,
            whaleTracking: 9,
            onchainAnalytics: 13,
            rpcNodes: 24,
            localBackend: 106,
            corsProxies: 7,
        }
    }
};

/**

 * API Client with Smart Fallback

 */
class SmartAPIClient {
    constructor(config = window.API_CONFIG) {
        this.config = config;
        this.authToken = this.getAuthToken();
    }
    
    /**

     * Get auth token from localStorage or environment

     */
    getAuthToken() {
        // Try localStorage first
        let token = localStorage.getItem('hf_token');
        
        // Try sessionStorage
        if (!token) {
            token = sessionStorage.getItem('hf_token');
        }
        
        // Try from URL params (for testing)
        if (!token) {
            const params = new URLSearchParams(window.location.search);
            token = params.get('token');
        }
        
        return token;
    }
    
    /**

     * Set auth token

     */
    setAuthToken(token) {
        this.authToken = token;
        localStorage.setItem('hf_token', token);
    }
    
    /**

     * Get headers for API requests

     */
    getHeaders() {
        const headers = {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
        };
        
        if (this.authToken) {
            headers['Authorization'] = `Bearer ${this.authToken}`;
        }
        
        return headers;
    }
    
    /**

     * Fetch with retry logic

     */
    async fetchWithRetry(url, options = {}, retries = 3) {
        for (let i = 0; i < retries; i++) {
            try {
                const response = await fetch(url, {
                    ...options,
                    headers: {
                        ...this.getHeaders(),
                        ...options.headers,
                    },
                    timeout: this.config.request.timeout,
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                
                return await response.json();
            } catch (error) {
                console.warn(`Attempt ${i + 1} failed:`, error);
                
                if (i === retries - 1) {
                    throw error;
                }
                
                // Wait before retry
                await new Promise(resolve => 
                    setTimeout(resolve, this.config.request.retryDelay * (i + 1))
                );
            }
        }
    }
    
    /**

     * Get market data using smart fallback

     */
    async getMarketData(limit = 100) {
        try {
            // Try smart endpoint first (NEVER fails)
            return await this.fetchWithRetry(
                `${this.config.endpoints.smart.market}?limit=${limit}`
            );
        } catch (error) {
            console.error('Smart market data failed:', error);
            
            // Fallback to original endpoint
            try {
                return await this.fetchWithRetry(
                    `${this.config.endpoints.market}?limit=${limit}`
                );
            } catch (fallbackError) {
                console.error('All market data endpoints failed');
                throw fallbackError;
            }
        }
    }
    
    /**

     * Get news using smart fallback

     */
    async getNews(limit = 20) {
        try {
            return await this.fetchWithRetry(
                `${this.config.endpoints.smart.news}?limit=${limit}`
            );
        } catch (error) {
            console.error('Smart news failed:', error);
            throw error;
        }
    }
    
    /**

     * Get sentiment analysis

     */
    async getSentiment(symbol = null) {
        const url = symbol 
            ? `${this.config.endpoints.smart.sentiment}?symbol=${symbol}`
            : this.config.endpoints.smart.sentiment;
        
        try {
            return await this.fetchWithRetry(url);
        } catch (error) {
            console.error('Smart sentiment failed:', error);
            throw error;
        }
    }
    
    /**

     * Get whale alerts

     */
    async getWhaleAlerts(limit = 20) {
        try {
            return await this.fetchWithRetry(
                `${this.config.endpoints.smart.whaleAlerts}?limit=${limit}`
            );
        } catch (error) {
            console.error('Smart whale alerts failed:', error);
            throw error;
        }
    }
    
    /**

     * Get blockchain data

     */
    async getBlockchainData(chain = 'ethereum') {
        try {
            return await this.fetchWithRetry(
                `${this.config.endpoints.smart.blockchain}/${chain}`
            );
        } catch (error) {
            console.error('Smart blockchain data failed:', error);
            throw error;
        }
    }
    
    /**

     * Get health report

     */
    async getHealthReport() {
        try {
            return await this.fetchWithRetry(
                this.config.endpoints.smart.healthReport
            );
        } catch (error) {
            console.error('Health report failed:', error);
            throw error;
        }
    }
    
    /**

     * Get system statistics

     */
    async getStats() {
        try {
            return await this.fetchWithRetry(
                this.config.endpoints.smart.stats
            );
        } catch (error) {
            console.error('Stats failed:', error);
            throw error;
        }
    }
    
    /**

     * Get Alpha Vantage data

     */
    async getAlphaVantageData(endpoint, params = {}) {
        const url = new URL(endpoint);
        Object.keys(params).forEach(key => 
            url.searchParams.append(key, params[key])
        );
        
        try {
            return await this.fetchWithRetry(url.toString());
        } catch (error) {
            console.error('Alpha Vantage request failed:', error);
            throw error;
        }
    }
    
    /**

     * Get Massive.com data

     */
    async getMassiveData(endpoint, params = {}) {
        const url = new URL(endpoint);
        Object.keys(params).forEach(key => 
            url.searchParams.append(key, params[key])
        );
        
        try {
            return await this.fetchWithRetry(url.toString());
        } catch (error) {
            console.error('Massive.com request failed:', error);
            throw error;
        }
    }
}

// Create global API client instance
window.apiClient = new SmartAPIClient();

// Export for modules
if (typeof module !== 'undefined' && module.exports) {
    module.exports = { API_CONFIG, SmartAPIClient };
}

console.log('βœ… API Configuration loaded successfully');
console.log('πŸ“Š Smart Fallback System: 305+ resources available');
console.log('πŸ”„ Resource rotation: ENABLED');
console.log('πŸ”’ Proxy support: ENABLED');
console.log('✨ Features:', window.API_CONFIG.features);