|
| 1 | +import logging |
| 2 | +from datetime import datetime, timedelta, timezone |
| 3 | +from typing import Dict |
| 4 | + |
| 5 | +import aiohttp |
| 6 | + |
| 7 | +from config import get_chain_id |
| 8 | + |
| 9 | +logger = logging.getLogger(__name__) |
| 10 | + |
| 11 | + |
| 12 | +class BitQueryService: |
| 13 | + def __init__(self, oauth_token: str): |
| 14 | + if not oauth_token: |
| 15 | + raise ValueError("BitQuery OAuth token is required") |
| 16 | + |
| 17 | + logger.debug("Initializing BitQueryService") |
| 18 | + self.oauth_token = oauth_token |
| 19 | + self.url = "https://streaming.bitquery.io/graphql" |
| 20 | + self.headers = { |
| 21 | + "Content-Type": "application/json", |
| 22 | + "Authorization": f"Bearer {oauth_token}", |
| 23 | + } |
| 24 | + |
| 25 | + def _get_base_trade_fields(self, address_field: str = "SmartContract") -> str: |
| 26 | + """Get common trade fields structure for all chains""" |
| 27 | + return f""" |
| 28 | + Block {{ |
| 29 | + Number |
| 30 | + Time |
| 31 | + }} |
| 32 | + Transaction {{ |
| 33 | + Hash |
| 34 | + }} |
| 35 | + Trade {{ |
| 36 | + Buy {{ |
| 37 | + Amount |
| 38 | + Currency {{ |
| 39 | + Name |
| 40 | + Symbol |
| 41 | + {address_field} |
| 42 | + }} |
| 43 | + Price |
| 44 | + }} |
| 45 | + Sell {{ |
| 46 | + Amount |
| 47 | + Currency {{ |
| 48 | + Name |
| 49 | + Symbol |
| 50 | + {address_field} |
| 51 | + }} |
| 52 | + Price |
| 53 | + }} |
| 54 | + Dex {{ |
| 55 | + ProtocolName |
| 56 | + }} |
| 57 | + }} |
| 58 | + """ |
| 59 | + |
| 60 | + def _get_chain_query(self, chain: str) -> tuple[str, str]: |
| 61 | + """Get chain-specific query structure and namespace""" |
| 62 | + if chain == "solana": |
| 63 | + return "Solana", "MintAddress" |
| 64 | + elif chain == "tron": |
| 65 | + return "Tron", "Address" |
| 66 | + elif chain == "ton": |
| 67 | + return "TON", "Address" |
| 68 | + else: # EVM chains |
| 69 | + return "EVM", "SmartContract" |
| 70 | + |
| 71 | + async def get_chain_activity(self, chain: str, time_window: int = 60) -> Dict: |
| 72 | + """ |
| 73 | + Fetch trading activity for specified chain |
| 74 | + time_window: minutes to look back |
| 75 | + """ |
| 76 | + try: |
| 77 | + logger.debug(f"Fetching chain activity for {chain}, time window: {time_window}min") |
| 78 | + now = datetime.now(timezone.utc) |
| 79 | + time_ago = now - timedelta(minutes=time_window) |
| 80 | + |
| 81 | + # Normalize chain name |
| 82 | + chain = get_chain_id(chain) |
| 83 | + namespace, address_field = self._get_chain_query(chain) |
| 84 | + trade_fields = self._get_base_trade_fields(address_field) |
| 85 | + |
| 86 | + # Build query based on chain type |
| 87 | + if namespace == "EVM": |
| 88 | + # Query for EVM chains |
| 89 | + query = f""" |
| 90 | + query ($network: evm_network!, $since: DateTime) {{ |
| 91 | + {namespace}(network: $network) {{ |
| 92 | + DEXTrades( |
| 93 | + orderBy: {{descending: Block_Time}} |
| 94 | + where: {{Block: {{Time: {{since: $since}}}}}} |
| 95 | + ) {{ |
| 96 | + {trade_fields} |
| 97 | + }} |
| 98 | + }} |
| 99 | + }} |
| 100 | + """ |
| 101 | + variables = {"network": chain.lower(), "since": time_ago.isoformat()} |
| 102 | + else: |
| 103 | + # Query for non-EVM chains (Solana, Tron, TON) |
| 104 | + query = f""" |
| 105 | + query ($since: DateTime) {{ |
| 106 | + {namespace} {{ |
| 107 | + DEXTrades( |
| 108 | + orderBy: {{descending: Block_Time}} |
| 109 | + where: {{Block: {{Time: {{since: $since}}}}}} |
| 110 | + ) {{ |
| 111 | + {trade_fields} |
| 112 | + }} |
| 113 | + }} |
| 114 | + }} |
| 115 | + """ |
| 116 | + variables = {"since": time_ago.isoformat()} |
| 117 | + |
| 118 | + # Log the query and variables |
| 119 | + logger.debug(f"BitQuery request for {chain}:") |
| 120 | + logger.debug(f"Query: {query}") |
| 121 | + logger.debug(f"Variables: {variables}") |
| 122 | + |
| 123 | + async with aiohttp.ClientSession() as session: |
| 124 | + async with session.post( |
| 125 | + self.url, |
| 126 | + headers=self.headers, |
| 127 | + json={"query": query, "variables": variables}, |
| 128 | + ) as response: |
| 129 | + if response.status != 200: |
| 130 | + error_text = await response.text() |
| 131 | + logger.error(f"BitQuery API error: Status {response.status}, Response: {error_text}") |
| 132 | + raise aiohttp.ClientError(f"BitQuery API returned status {response.status}") |
| 133 | + |
| 134 | + data = await response.json() |
| 135 | + |
| 136 | + if "errors" in data: |
| 137 | + logger.error(f"GraphQL errors: {data['errors']}") |
| 138 | + raise ValueError(f"GraphQL query failed: {data['errors']}") |
| 139 | + |
| 140 | + # Log the response data |
| 141 | + trades = data.get("data", {}).get(namespace, {}).get("DEXTrades", []) |
| 142 | + logger.info(f"Received {len(trades)} trades from BitQuery for {chain}") |
| 143 | + |
| 144 | + # Log sample of trades for debugging |
| 145 | + if trades: |
| 146 | + logger.debug("Sample trade data (first trade):") |
| 147 | + logger.debug(f"Block: {trades[0].get('Block', {})}") |
| 148 | + logger.debug(f"Transaction: {trades[0].get('Transaction', {})}") |
| 149 | + logger.debug(f"Trade details: {trades[0].get('Trade', {})}") |
| 150 | + |
| 151 | + logger.debug(f"Successfully fetched data for {chain}") |
| 152 | + return data |
| 153 | + |
| 154 | + except aiohttp.ClientError as e: |
| 155 | + logger.error(f"Network error while fetching chain activity: {str(e)}") |
| 156 | + raise |
| 157 | + except Exception as e: |
| 158 | + logger.error(f"Error fetching chain activity for {chain}: {str(e)}") |
| 159 | + raise |
0 commit comments