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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
"""
Bitquery DataBus Provider β€” Blockchain Intelligence via GraphQL
=================================================================

Bitquery provides deep blockchain data across 40+ chains via GraphQL.
This provider integrates with DataBus for intelligent caching and
rate-limited access.

Status: API key valid, account needs active billing period.
When billing is activated (free tier or paid), all queries work.

Data types supported:
  - token_price: DEX trade prices across chains
  - holder_data: Token holder distribution and whale tracking
  - transaction_trace: Full transaction traces and fund flows
  - dex_volume: DEX trading volume and liquidity
  - smart_contract: Contract creation, calls, and events
  - address_balance: Address balances across chains
  - cross_chain_bridge: Bridge transaction tracking

Cache strategy:
  - Historical data: 24h TTL (immutable)
  - Price/volume: 5min TTL (volatile)
  - Holder data: 1h TTL (semi-volatile)
  - Transaction traces: 24h TTL (immutable)

Rate limits:
  - Free tier: 100k credits/month, ~1 query/sec
  - Developer: $99/mo, higher rate limits
  - Business: $499/mo, highest rate limits
"""

import hashlib
import logging
import time

import httpx

from app.databus.cache import CacheLayer, get_cache

logger = logging.getLogger("databus.bitquery")

# ── Configuration ──────────────────────────────────────────────
BITQUERY_STREAMING_URL = "https://streaming.bitquery.io/graphql"
BITQUERY_IDE_URL = "https://ide.bitquery.io/graphql"
BITQUERY_API_URL = "https://graphql.bitquery.io/"

# Cache TTLs
CACHE_TTL_PRICE = 300  # 5 min β€” prices are volatile
CACHE_TTL_VOLUME = 300  # 5 min
CACHE_TTL_HOLDERS = 3600  # 1 hour
CACHE_TTL_TRACE = 86400  # 24 hours β€” historical
CACHE_TTL_BALANCE = 600  # 10 min

# Rate limits (free tier)
FREE_CREDITS_PER_MONTH = 100_000
MAX_RPS = 1.0


class BitqueryProvider:
    """
    Bitquery GraphQL API provider with intelligent caching.

    Handles:
    - GraphQL query construction for common blockchain data types
    - Rate limiting (credit-based)
    - Response caching with DataBus
    - Error handling for billing/auth issues
    """

    def __init__(self, cache: CacheLayer = None):
        self.cache = cache or get_cache()
        self._client: httpx.AsyncClient | None = None
        self._api_key: str | None = None
        self._oauth_token: str | None = None
        self._credits_used = 0
        self._monthly_reset = time.time()
        self._loaded = False

    async def _load_creds(self):
        """Load Bitquery credentials β€” env vars first, vault as fallback."""
        if self._loaded:
            return
        import os

        self._api_key = os.getenv("BITQUERY_API_KEY", "")
        self._oauth_token = os.getenv("BITQUERY_OAUTH_TOKEN", "")
        if self._api_key:
            self._loaded = True
            logger.info(
                f"Bitquery creds from env (key={'βœ“' if self._api_key else 'βœ—'}, oauth={'βœ“' if self._oauth_token else 'βœ—'})"
            )
            return
        # Fallback: vault
        try:
            import subprocess

            result = subprocess.run(
                ["python3", "/root/.secrets/vault.py", "get", "backend/bitquery_api_key"],
                capture_output=True,
                text=True,
                timeout=10,
            )
            key = result.stdout.strip()
            if key and len(key) > 10:
                self._api_key = key
            self._loaded = True
            logger.info(f"Bitquery creds from vault (key={'βœ“' if self._api_key else 'βœ—'})")
        except Exception as e:
            logger.error(f"Failed to load Bitquery credentials: {e}")

    async def _get_client(self) -> httpx.AsyncClient:
        if self._client is None or self._client.is_closed:
            self._client = httpx.AsyncClient(
                base_url=BITQUERY_STREAMING_URL,
                timeout=30.0,
                headers={"Content-Type": "application/json"},
            )
        return self._client

    def _check_billing(self) -> bool:
        """Check if credits are available. Returns False if billing period inactive."""
        now = time.time()
        if now - self._monthly_reset > 30 * 86400:  # ~30 days
            self._credits_used = 0
            self._monthly_reset = now
        return self._credits_used < FREE_CREDITS_PER_MONTH

    async def _query(self, graphql_query: str, variables: dict | None = None) -> dict | None:
        """
        Execute a Bitquery GraphQL query with caching and rate limiting.
        Returns None on billing error (402) or auth error.
        """
        await self._load_creds()

        if not self._check_billing():
            logger.warning("Bitquery monthly credit limit reached")
            return {"error": "Monthly credit limit reached", "code": 429}

        # Generate cache key from query hash
        query_hash = hashlib.sha256(graphql_query.encode()).hexdigest()[:16]

        cached = await self._get_cached(query_hash, graphql_query)
        if cached:
            return cached

        client = await self._get_client()

        payload = {"query": graphql_query}
        if variables:
            payload["variables"] = variables

        headers = {"X-API-KEY": self._api_key}
        if self._oauth_token:
            headers["Authorization"] = f"Bearer {self._oauth_token}"

        try:
            resp = await client.post("", json=payload, headers=headers)
            self._credits_used += 1

            if resp.status_code == 402:
                logger.error("Bitquery: No active billing period. Activate at bitquery.io")
                return {
                    "error": "No active billing period",
                    "code": 402,
                    "fix": "Log into bitquery.io and activate a plan (even free tier)",
                }

            if resp.status_code == 401:
                logger.error("Bitquery: Invalid API key or OAuth token")
                return {"error": "Authentication failed", "code": 401}

            resp.raise_for_status()
            data = resp.json()

            if "errors" in data:
                logger.warning(f"Bitquery GraphQL errors: {data['errors']}")
                return {"error": "GraphQL error", "details": data["errors"]}

            # Cache successful response
            await self._cache_response(query_hash, graphql_query, data)

            return data.get("data", {})

        except httpx.HTTPStatusError as e:
            logger.error(f"Bitquery HTTP error: {e.response.status_code}")
            return {"error": f"HTTP {e.response.status_code}", "code": e.response.status_code}
        except Exception as e:
            logger.error(f"Bitquery query failed: {e}")
            return {"error": str(e)}

    async def _get_cached(self, query_hash: str, query_text: str) -> dict | None:
        """Get cached response if available and not stale."""
        cache_key = f"bitquery:{query_hash}"

        # Determine TTL based on query type
        ttl = CACHE_TTL_TRACE  # default
        if any(k in query_text.lower() for k in ["price", "volume", "trade"]):
            ttl = CACHE_TTL_PRICE
        elif "holder" in query_text.lower() or "balance" in query_text.lower():
            ttl = CACHE_TTL_HOLDERS

        cached = await self.cache.get(cache_key)
        if cached:
            # Handle tuple (value, is_stale) from SWR cache
            if isinstance(cached, tuple):
                cached = cached[0]
            if cached is not None:
                # Check if cache is still fresh
                cached_time = cached.get("_cached_at", 0)
                if time.time() - cached_time < ttl:
                    return cached.get("data")

        return None

    async def _cache_response(self, query_hash: str, query_text: str, data: dict):
        """Cache successful response with metadata."""
        cache_key = f"bitquery:{query_hash}"

        ttl = CACHE_TTL_TRACE
        if any(k in query_text.lower() for k in ["price", "volume", "trade"]):
            ttl = CACHE_TTL_PRICE
        elif "holder" in query_text.lower() or "balance" in query_text.lower():
            ttl = CACHE_TTL_HOLDERS

        cache_data = {
            "data": data,
            "_cached_at": time.time(),
            "_query_hash": query_hash,
        }

        await self.cache.set(cache_key, cache_data, ttl=ttl)

    # ── Public Data Methods ──────────────────────────────────────

    async def get_token_price(self, network: str, token_address: str) -> dict | None:
        """
        Get latest DEX price for a token.

        Args:
            network: ethereum, bsc, solana, etc.
            token_address: Contract address or mint
        """
        query = f"""
        query {{
            {network}(network: {network}) {{
                dexTrades(
                    options: {{limit: 1, desc: "block.timestamp.time"}}
                    baseCurrency: {{is: "{token_address}"}}
                ) {{
                    transaction {{
                        hash
                    }}
                    tradeAmount(in: USD)
                    price
                    baseCurrency {{
                        symbol
                        name
                    }}
                    quoteCurrency {{
                        symbol
                    }}
                    block {{
                        timestamp {{
                            time(format: "%Y-%m-%d %H:%M:%S")
                        }}
                    }}
                }}
            }}
        }}
        """
        return await self._query(query)

    async def get_holder_distribution(self, network: str, token_address: str, limit: int = 100) -> dict | None:
        """
        Get top token holders and their balances.

        Args:
            network: blockchain network
            token_address: Token contract/mint
            limit: Number of holders to return
        """
        query = f"""
        query {{
            {network}(network: {network}) {{
                address(
                    address: {{is: "{token_address}"}}
                ) {{
                    balances {{
                        currency {{
                            symbol
                            tokenType
                        }}
                        value
                        history {{
                            block
                            timestamp
                            value
                        }}
                    }}
                }}
            }}
        }}
        """
        return await self._query(query)

    async def get_transaction_trace(self, network: str, tx_hash: str) -> dict | None:
        """
        Get full transaction trace including internal calls.

        Args:
            network: blockchain network
            tx_hash: Transaction hash
        """
        query = f"""
        query {{
            {network}(network: {network}) {{
                transactions(
                    txHash: {{is: "{tx_hash}"}}
                ) {{
                    hash
                    block {{
                        height
                        timestamp {{
                            time(format: "%Y-%m-%d %H:%M:%S")
                        }}
                    }}
                    sender {{
                        address
                    }}
                    receiver {{
                        address
                    }}
                    amount
                    gasValue
                    success
                    internalTransactions {{
                        sender {{
                            address
                        }}
                        receiver {{
                            address
                        }}
                        amount
                        gasValue
                        success
                    }}
                }}
            }}
        }}
        """
        return await self._query(query)

    async def get_dex_volume(
        self, network: str, pool_address: str | None = None, timeframe: str = "24h"
    ) -> dict | None:
        """
        Get DEX trading volume for a pool or network.

        Args:
            network: blockchain network
            pool_address: Optional specific pool
            timeframe: 1h, 6h, 24h, 7d
        """
        pool_filter = f'poolAddress: {{is: "{pool_address}"}}' if pool_address else ""

        query = f"""
        query {{
            {network}(network: {network}) {{
                dexTrades(
                    {pool_filter}
                    options: {{desc: "block.timestamp.time", limit: 100}}
                ) {{
                    count
                    tradeAmount(in: USD)
                    volume: tradeAmount(in: USD, calculate: sum)
                    block {{
                        timestamp {{
                            time(format: "%Y-%m-%d %H:%M:%S")
                        }}
                    }}
                }}
            }}
        }}
        """
        return await self._query(query)

    async def get_address_balance(self, network: str, address: str) -> dict | None:
        """
        Get all token balances for an address.

        Args:
            network: blockchain network
            address: Wallet address
        """
        query = f"""
        query {{
            {network}(network: {network}) {{
                address(
                    address: {{is: "{address}"}}
                ) {{
                    balances {{
                        currency {{
                            symbol
                            name
                            tokenType
                            address
                        }}
                        value
                    }}
                }}
            }}
        }}
        """
        return await self._query(query)

    async def get_cross_chain_transfers(self, address: str, networks: list[str] | None = None) -> dict | None:
        """
        Track token transfers across multiple chains for an address.

        Args:
            address: Wallet address
            networks: List of networks to check (default: ethereum, bsc, solana)
        """
        networks = networks or ["ethereum", "bsc", "solana"]

        # Build multi-network query
        queries = []
        for net in networks:
            queries.append(f"""
                {net}: {net}(network: {net}) {{
                    transfers(
                        sender: {{is: "{address}"}}
                        options: {{limit: 10, desc: "block.timestamp.time"}}
                    ) {{
                        transaction {{
                            hash
                        }}
                        amount
                        currency {{
                            symbol
                            name
                        }}
                        receiver {{
                            address
                        }}
                        block {{
                            timestamp {{
                                time(format: "%Y-%m-%d %H:%M:%S")
                            }}
                        }}
                    }}
                }}
            """)

        query = f"query {{ {' '.join(queries)} }}"
        return await self._query(query)

    async def get_smart_contract_events(
        self, network: str, contract: str, event_signature: str | None = None, limit: int = 50
    ) -> dict | None:
        """
        Get smart contract events/logs.

        Args:
            network: blockchain network
            contract: Contract address
            event_signature: Optional event signature hash
            limit: Number of events
        """
        event_filter = f'smartContractEvent: {{is: "{event_signature}"}}' if event_signature else ""

        query = f"""
        query {{
            {network}(network: {network}) {{
                smartContractEvents(
                    smartContractAddress: {{is: "{contract}"}}
                    {event_filter}
                    options: {{limit: {limit}, desc: "block.timestamp.time"}}
                ) {{
                    arguments {{
                        name
                        value
                        type
                    }}
                    smartContract {{
                        contractType
                        currency {{
                            symbol
                            name
                        }}
                    }}
                    block {{
                        timestamp {{
                            time(format: "%Y-%m-%d %H:%M:%S")
                        }}
                    }}
                }}
            }}
        }}
        """
        return await self._query(query)

    # ── Health & Status ─────────────────────────────────────────

    async def health(self) -> dict:
        """Provider health check."""
        await self._load_creds()

        # Try a minimal query to check status
        test_query = """
        query {
            ethereum(network: ethereum) {
                blocks(options: {limit: 1}) {
                    height
                }
            }
        }
        """

        result = await self._query(test_query)

        if result and "error" in result:
            error_code = result.get("code", 0)
            if error_code == 402:
                return {
                    "status": "billing_required",
                    "api_key_valid": True,
                    "billing_active": False,
                    "credits_used": self._credits_used,
                    "credits_remaining": FREE_CREDITS_PER_MONTH - self._credits_used,
                    "fix": "Activate billing at bitquery.io (free tier available)",
                    "message": "Account needs active billing period",
                }
            elif error_code == 401:
                return {
                    "status": "auth_error",
                    "api_key_valid": False,
                    "message": "Invalid API key or OAuth token",
                }
            else:
                return {"status": "error", "error": result.get("error"), "code": error_code}

        return {
            "status": "healthy",
            "api_key_valid": True,
            "billing_active": True,
            "credits_used": self._credits_used,
            "credits_remaining": FREE_CREDITS_PER_MONTH - self._credits_used,
            "networks_supported": 40,
            "data_types": [
                "token_price",
                "holder_data",
                "transaction_trace",
                "dex_volume",
                "smart_contract_events",
                "address_balance",
                "cross_chain_transfers",
            ],
        }