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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
#!/usr/bin/env python3
"""

On-Chain Data Aggregator - Uses ALL Free On-Chain Resources

Maximizes usage of all available free blockchain explorers and analytics

"""

import httpx
import logging
import asyncio
from typing import Dict, Any, List, Optional
from datetime import datetime
from fastapi import HTTPException

logger = logging.getLogger(__name__)


class OnChainAggregator:
    """

    Aggregates on-chain data from ALL free sources:

    Block Explorers:

    - Etherscan (with keys)

    - Blockchair (free tier)

    - Blockscout (free, open source)

    - BscScan (with key)

    - TronScan (with key)

    

    Public RPC Nodes:

    - Ankr (ETH, BSC, Polygon)

    - PublicNode (ETH, BSC, Polygon)

    - Cloudflare ETH

    - LlamaNodes

    - 1RPC

    - dRPC

    - BSC Official nodes

    - TronGrid

    - Polygon Official

    """
    
    def __init__(self):
        self.timeout = 15.0
        
        # Block Explorer APIs with keys
        self.explorers = {
            "ethereum": {
                "etherscan": {
                    "base_url": "https://api.etherscan.io/api",
                    "api_key": "SZHYFZK2RR8H9TIMJBVW54V4H81K2Z2KR2",
                    "priority": 1
                },
                "etherscan_backup": {
                    "base_url": "https://api.etherscan.io/api",
                    "api_key": "T6IR8VJHX2NE6ZJW2S3FDVN1TYG4PYYI45",
                    "priority": 2
                },
                "blockchair": {
                    "base_url": "https://api.blockchair.com/ethereum",
                    "api_key": None,  # Free tier, no key needed
                    "priority": 3
                },
                "blockscout": {
                    "base_url": "https://eth.blockscout.com/api",
                    "api_key": None,
                    "priority": 4
                }
            },
            "bsc": {
                "bscscan": {
                    "base_url": "https://api.bscscan.com/api",
                    "api_key": "K62RKHGXTDCG53RU4MCG6XABIMJKTN19IT",
                    "priority": 1
                },
                "blockchair": {
                    "base_url": "https://api.blockchair.com/binance-smart-chain",
                    "api_key": None,
                    "priority": 2
                }
            },
            "tron": {
                "tronscan": {
                    "base_url": "https://apilist.tronscanapi.com/api",
                    "api_key": "7ae72726-bffe-4e74-9c33-97b761eeea21",
                    "priority": 1
                },
                "blockchair": {
                    "base_url": "https://api.blockchair.com/tron",
                    "api_key": None,
                    "priority": 2
                }
            }
        }
        
        # Free Public RPC Nodes
        self.rpc_nodes = {
            "ethereum": [
                "https://rpc.ankr.com/eth",
                "https://ethereum.publicnode.com",
                "https://ethereum-rpc.publicnode.com",
                "https://cloudflare-eth.com",
                "https://eth.llamarpc.com",
                "https://1rpc.io/eth",
                "https://eth.drpc.org"
            ],
            "bsc": [
                "https://bsc-dataseed.binance.org",
                "https://bsc-dataseed1.defibit.io",
                "https://bsc-dataseed1.ninicoin.io",
                "https://rpc.ankr.com/bsc",
                "https://bsc-rpc.publicnode.com"
            ],
            "polygon": [
                "https://polygon-rpc.com",
                "https://rpc.ankr.com/polygon",
                "https://polygon-bor-rpc.publicnode.com"
            ],
            "tron": [
                "https://api.trongrid.io",
                "https://api.tronstack.io"
            ]
        }
    
    async def get_address_balance(

        self,

        address: str,

        chain: str = "ethereum"

    ) -> Dict[str, Any]:
        """

        Get address balance from ALL available explorers with fallback

        """
        chain = chain.lower()
        
        if chain not in self.explorers:
            raise HTTPException(
                status_code=400,
                detail=f"Unsupported chain: {chain}. Supported: {list(self.explorers.keys())}"
            )
        
        # Try all explorers for the chain
        explorers = sorted(
            self.explorers[chain].items(),
            key=lambda x: x[1]["priority"]
        )
        
        for explorer_name, explorer_config in explorers:
            try:
                if "etherscan" in explorer_name or "bscscan" in explorer_name:
                    balance_data = await self._get_balance_etherscan_like(
                        address, explorer_config
                    )
                elif "blockchair" in explorer_name:
                    balance_data = await self._get_balance_blockchair(
                        address, explorer_config
                    )
                elif "blockscout" in explorer_name:
                    balance_data = await self._get_balance_blockscout(
                        address, explorer_config
                    )
                elif "tronscan" in explorer_name:
                    balance_data = await self._get_balance_tronscan(
                        address, explorer_config
                    )
                else:
                    continue
                
                if balance_data:
                    logger.info(f"✅ {explorer_name.upper()} ({chain}): Successfully fetched balance")
                    return balance_data
                    
            except Exception as e:
                logger.warning(f"⚠️ {explorer_name.upper()} failed: {e}")
                continue
        
        raise HTTPException(
            status_code=503,
            detail=f"All {chain} explorers failed for address {address}"
        )
    
    async def get_gas_price(self, chain: str = "ethereum") -> Dict[str, Any]:
        """

        Get current gas price from explorers or RPC nodes

        """
        chain = chain.lower()
        
        # Try explorer APIs first (Etherscan-like)
        if chain in self.explorers:
            explorers = sorted(
                self.explorers[chain].items(),
                key=lambda x: x[1]["priority"]
            )
            
            for explorer_name, explorer_config in explorers:
                try:
                    if "etherscan" in explorer_name or "bscscan" in explorer_name:
                        gas_data = await self._get_gas_etherscan_like(explorer_config)
                        if gas_data:
                            logger.info(f"✅ {explorer_name.upper()}: Successfully fetched gas price")
                            return gas_data
                except Exception as e:
                    logger.warning(f"⚠️ {explorer_name} gas price failed: {e}")
                    continue
        
        # Try RPC nodes
        if chain in self.rpc_nodes:
            for rpc_url in self.rpc_nodes[chain]:
                try:
                    gas_data = await self._get_gas_rpc(rpc_url, chain)
                    if gas_data:
                        logger.info(f"✅ RPC ({rpc_url}): Successfully fetched gas price")
                        return gas_data
                except Exception as e:
                    logger.warning(f"⚠️ RPC {rpc_url} failed: {e}")
                    continue
        
        raise HTTPException(
            status_code=503,
            detail=f"Failed to fetch gas price for {chain}"
        )
    
    async def get_transactions(

        self,

        address: str,

        chain: str = "ethereum",

        limit: int = 20

    ) -> List[Dict[str, Any]]:
        """

        Get transaction history for an address

        """
        chain = chain.lower()
        
        if chain not in self.explorers:
            raise HTTPException(
                status_code=400,
                detail=f"Unsupported chain: {chain}"
            )
        
        # Try all explorers
        explorers = sorted(
            self.explorers[chain].items(),
            key=lambda x: x[1]["priority"]
        )
        
        for explorer_name, explorer_config in explorers:
            try:
                if "etherscan" in explorer_name or "bscscan" in explorer_name:
                    tx_data = await self._get_transactions_etherscan_like(
                        address, explorer_config, limit
                    )
                elif "tronscan" in explorer_name:
                    tx_data = await self._get_transactions_tronscan(
                        address, explorer_config, limit
                    )
                else:
                    continue
                
                if tx_data:
                    logger.info(f"✅ {explorer_name.upper()}: Fetched {len(tx_data)} transactions")
                    return tx_data
                    
            except Exception as e:
                logger.warning(f"⚠️ {explorer_name} transactions failed: {e}")
                continue
        
        raise HTTPException(
            status_code=503,
            detail=f"Failed to fetch transactions for {address} on {chain}"
        )
    
    # Etherscan-like API implementations
    async def _get_balance_etherscan_like(

        self,

        address: str,

        config: Dict[str, Any]

    ) -> Dict[str, Any]:
        """Get balance from Etherscan-like API"""
        async with httpx.AsyncClient(timeout=self.timeout) as client:
            params = {
                "module": "account",
                "action": "balance",
                "address": address,
                "tag": "latest"
            }
            
            if config["api_key"]:
                params["apikey"] = config["api_key"]
            
            response = await client.get(config["base_url"], params=params)
            response.raise_for_status()
            data = response.json()
            
            if data.get("status") == "1" and data.get("result"):
                # Convert wei to ether (for ETH/BNB)
                balance_wei = int(data["result"])
                balance_ether = balance_wei / 1e18
                
                return {
                    "address": address,
                    "balance": balance_ether,
                    "balance_wei": balance_wei,
                    "timestamp": int(datetime.utcnow().timestamp() * 1000)
                }
            
            raise Exception(f"API returned error: {data.get('message', 'Unknown error')}")
    
    async def _get_gas_etherscan_like(self, config: Dict[str, Any]) -> Dict[str, Any]:
        """Get gas price from Etherscan-like API"""
        async with httpx.AsyncClient(timeout=self.timeout) as client:
            params = {
                "module": "gastracker",
                "action": "gasoracle"
            }
            
            if config["api_key"]:
                params["apikey"] = config["api_key"]
            
            response = await client.get(config["base_url"], params=params)
            response.raise_for_status()
            data = response.json()
            
            if data.get("status") == "1" and data.get("result"):
                result = data["result"]
                return {
                    "safe_gas_price": float(result.get("SafeGasPrice", 0)),
                    "propose_gas_price": float(result.get("ProposeGasPrice", 0)),
                    "fast_gas_price": float(result.get("FastGasPrice", 0)),
                    "unit": "gwei",
                    "timestamp": int(datetime.utcnow().timestamp() * 1000)
                }
            
            raise Exception("Failed to fetch gas price")
    
    async def _get_transactions_etherscan_like(

        self,

        address: str,

        config: Dict[str, Any],

        limit: int

    ) -> List[Dict[str, Any]]:
        """Get transactions from Etherscan-like API"""
        async with httpx.AsyncClient(timeout=self.timeout) as client:
            params = {
                "module": "account",
                "action": "txlist",
                "address": address,
                "startblock": 0,
                "endblock": 99999999,
                "sort": "desc",
                "page": 1,
                "offset": limit
            }
            
            if config["api_key"]:
                params["apikey"] = config["api_key"]
            
            response = await client.get(config["base_url"], params=params)
            response.raise_for_status()
            data = response.json()
            
            if data.get("status") == "1" and data.get("result"):
                transactions = []
                for tx in data["result"]:
                    transactions.append({
                        "hash": tx.get("hash", ""),
                        "from": tx.get("from", ""),
                        "to": tx.get("to", ""),
                        "value": int(tx.get("value", 0)) / 1e18,
                        "gas_used": int(tx.get("gasUsed", 0)),
                        "gas_price": int(tx.get("gasPrice", 0)) / 1e9,
                        "timestamp": int(tx.get("timeStamp", 0)) * 1000,
                        "block_number": int(tx.get("blockNumber", 0)),
                        "status": "success" if tx.get("txreceipt_status") == "1" else "failed"
                    })
                
                return transactions
            
            return []
    
    # Blockchair implementation
    async def _get_balance_blockchair(

        self,

        address: str,

        config: Dict[str, Any]

    ) -> Dict[str, Any]:
        """Get balance from Blockchair"""
        async with httpx.AsyncClient(timeout=self.timeout) as client:
            url = f"{config['base_url']}/dashboards/address/{address}"
            
            response = await client.get(url)
            response.raise_for_status()
            data = response.json()
            
            if data.get("data") and address in data["data"]:
                addr_data = data["data"][address]["address"]
                
                return {
                    "address": address,
                    "balance": float(addr_data.get("balance", 0)) / 1e18,
                    "balance_wei": int(addr_data.get("balance", 0)),
                    "transaction_count": addr_data.get("transaction_count", 0),
                    "timestamp": int(datetime.utcnow().timestamp() * 1000)
                }
            
            raise Exception("Address not found in Blockchair")
    
    # Blockscout implementation
    async def _get_balance_blockscout(

        self,

        address: str,

        config: Dict[str, Any]

    ) -> Dict[str, Any]:
        """Get balance from Blockscout"""
        async with httpx.AsyncClient(timeout=self.timeout) as client:
            params = {
                "module": "account",
                "action": "balance",
                "address": address
            }
            
            response = await client.get(config["base_url"], params=params)
            response.raise_for_status()
            data = response.json()
            
            if data.get("result"):
                balance_wei = int(data["result"])
                
                return {
                    "address": address,
                    "balance": balance_wei / 1e18,
                    "balance_wei": balance_wei,
                    "timestamp": int(datetime.utcnow().timestamp() * 1000)
                }
            
            raise Exception("Failed to fetch balance from Blockscout")
    
    # TronScan implementation
    async def _get_balance_tronscan(

        self,

        address: str,

        config: Dict[str, Any]

    ) -> Dict[str, Any]:
        """Get balance from TronScan"""
        async with httpx.AsyncClient(timeout=self.timeout) as client:
            url = f"{config['base_url']}/account"
            params = {"address": address}
            
            if config["api_key"]:
                params["apiKey"] = config["api_key"]
            
            response = await client.get(url, params=params)
            response.raise_for_status()
            data = response.json()
            
            if data:
                balance_sun = data.get("balance", 0)
                
                return {
                    "address": address,
                    "balance": balance_sun / 1e6,  # Convert SUN to TRX
                    "balance_sun": balance_sun,
                    "timestamp": int(datetime.utcnow().timestamp() * 1000)
                }
            
            raise Exception("Failed to fetch balance from TronScan")
    
    async def _get_transactions_tronscan(

        self,

        address: str,

        config: Dict[str, Any],

        limit: int

    ) -> List[Dict[str, Any]]:
        """Get transactions from TronScan"""
        async with httpx.AsyncClient(timeout=self.timeout) as client:
            url = f"{config['base_url']}/transaction"
            params = {"address": address, "limit": limit}
            
            if config["api_key"]:
                params["apiKey"] = config["api_key"]
            
            response = await client.get(url, params=params)
            response.raise_for_status()
            data = response.json()
            
            transactions = []
            for tx in data.get("data", []):
                transactions.append({
                    "hash": tx.get("hash", ""),
                    "from": tx.get("ownerAddress", ""),
                    "to": tx.get("toAddress", ""),
                    "value": tx.get("amount", 0) / 1e6,
                    "timestamp": tx.get("timestamp", 0),
                    "status": "success" if tx.get("contractRet") == "SUCCESS" else "failed"
                })
            
            return transactions
    
    # RPC implementation
    async def _get_gas_rpc(self, rpc_url: str, chain: str) -> Dict[str, Any]:
        """Get gas price from RPC node"""
        async with httpx.AsyncClient(timeout=self.timeout) as client:
            payload = {
                "jsonrpc": "2.0",
                "method": "eth_gasPrice",
                "params": [],
                "id": 1
            }
            
            response = await client.post(rpc_url, json=payload)
            response.raise_for_status()
            data = response.json()
            
            if data.get("result"):
                gas_price_wei = int(data["result"], 16)
                gas_price_gwei = gas_price_wei / 1e9
                
                return {
                    "gas_price": gas_price_gwei,
                    "unit": "gwei",
                    "chain": chain,
                    "timestamp": int(datetime.utcnow().timestamp() * 1000)
                }
            
            raise Exception("Failed to fetch gas price from RPC")


# Global instance
onchain_aggregator = OnChainAggregator()

__all__ = ["OnChainAggregator", "onchain_aggregator"]