← Back to home

SafeSign PfalzAI

AI-powered Telegram bot predicting transaction risks before signing

Problem Statement

DescriptionSafeSign is a Telegram bot that analyzes blockchain transactionsbefore users sign them, implementing an EIP-3377-like approach to convert raw transaction calldata into human-readable JSON format with real-time risk assessment.Core Problem SolvedThe bot addresses the "blind signing" problem where users approve transactions without understanding what they're authorizing. When wallets show cryptic calldata like0x095ea7b3000000000000000000000000a0b86a33e6776c8b0c8b46c9e8b9e8b9e8b9e8b9ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff, users have no idea they're granting unlimited token spending rights.How SafeSign Works1. Preventive Calldata AnalysisUsers paste raw transaction calldata directly from MetaMask's "Advanced → Data field" before hitting "Confirm". SafeSign converts this hex data into structured EIP-3377-like JSON:{ "to": "0x6c3ea9036406852006290770BEdFcAbA0e23A0e8", "description": "Interact with PayPal USD (PYUSD)", "method": "approve", "args": { "spender": "0xa0b86a33e6776c8b0c8b46c9e8b9e8b9e8b9e8b9", "amount": "unlimited" } }2. Real-Time Risk AnalysisThe system runs comprehensive security checks including:Unlimited approval detection (amounts >= 2^255)Suspicious spender analysis through DeFi activity historyUSD impact calculation using live price feedsCross-chain operation identificationToken-specific risk assessment (PYUSD, stablecoins)3. Live Data IntegrationEach analysis incorporates real-time data from six sponsor APIs:Chainlink: Live ETH/USD price feeds ($4,408.85 in logs) for accurate dollar impactAlchemy: Blockchain data fetching and ERC-20 token metadataThe Graph: Spender address reputation through Uniswap V3 activity analysisGemini AI: Natural language explanations converting technical findings to plain EnglishPayPal USD: Direct PYUSD contract integration detecting 954.95M total supplyHedera: Immutable analysis storage in Hedera Consensus Service4. Clear Risk CommunicationResults are presented with intuitive risk levels:❌REJECT: "DO NOT SIGN" for dangerous transactions (unlimited approvals)⚠️CAUTION: "SIGN WITH CAUTION" for medium-risk operations✅APPROVE: Safe transactions with clear explanationsTechnical ImplementationEIP-3377-like DecoderCustom implementation that recognizes common ERC-20 function signatures:0x095ea7b3: approve(address,uint256)0xa9059cbb: transfer(address,uint256)0xd505accf: permit(address,address,uint256,uint256,uint8,bytes32,bytes32)Multi-Modal AnalysisPreventive Mode: Analyze calldata before signing (primary feature)Legacy Mode: Post-transaction analysis via transaction hashConstructor Mode: Build sample transactions for testingDemo Examples: Pre-built dangerous and safe transaction examplesReal Transaction Examples from LogsDangerous: Unlimited PYUSD approval with USD impact of $115,792,089,237,316,190+Safe: $10.00 PYUSD transfer with clear recipient verificationMedium Risk: Large transfers flagged for manual verificationUser InterfaceTelegram bot with clean menu system allowing users to:Paste raw calldata for immediate analysisView converted EIP-3377-like JSON with copy functionalityReceive comprehensive risk reports with live data sourcesAccess educational examples and explanationsSafeSign transforms the opaque world of blockchain transactions into transparent, actionable intelligence, enabling informed decision-making before any financial damage occurs.

Solution

How it's MadeSafeSign is built with a clean hexagonal architecture integrating six sponsor technologies through live API calls and real-time blockchain interactions.Core ArchitectureDomain Layer: Custom EIP-3377-like decoder (src/domain/eip3377_decoder.py) that converts raw transaction calldata to structured JSON. The decoder recognizes ERC-20 function signatures through a lookup table:ERC20_SELECTORS = { "095ea7b3": {"name": "approve", "inputs": ["address", "uint256"]}, "a9059cbb": {"name": "transfer", "inputs": ["address", "uint256"]}, "d505accf": {"name": "permit", "inputs": ["address", "address", "uint256", "uint256", "uint8", "bytes32", "bytes32"]} }Application Layer: Risk analysis engine (src/application/rules.py) with 15+ detection rules including unlimited approval detection (checking values >= 2^255), suspicious spender analysis, and cross-chain operation identification.Infrastructure Layer: Six live sponsor integrations with real error handling and fallback mechanisms.Presentation Layer: Telegram bot (src/presentation/telegram/bot_real.py) with auto-detection of input types (calldata vs transaction hashes).Live Sponsor Integrations1. Alchemy (ETH RPC)# Real implementation from eth_rpc.py async def get_token_info(self, token: str) -> Optional[TokenInfo]: contract = self.w3.eth.contract(address=self.w3.to_checksum_address(token), abi=ERC20_ABI) symbol = await self._safe_contract_call(contract.functions.symbol()) decimals = await self._safe_contract_call(contract.functions.decimals())Powers automatic transaction fetching viaeth_getTransactionByHash, ERC-20 metadata retrieval, and balance verification. Logs show successful calls:INFO:httpx:HTTP Request: POST https://eth-mainnet.g.alchemy.com/v2/... "HTTP/1.1 200 OK"2. Chainlink# Real price feed integration from chainlink_real.py async def get_eth_usd_price(self) -> Optional[float]: round_data = self.eth_usd_feed.functions.latestRoundData().call() price_raw = round_data[1] decimals = self.eth_usd_feed.functions.decimals().call() price = float(price_raw) / (10 ** decimals)Direct smart contract calls to Chainlink's ETH/USD aggregator (0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419). Logs confirm real prices:INFO:src.infrastructure.chainlink_real:Chainlink ETH/USD: $4408.853. Gemini AI# Real AI integration from gemini_real.py async def explain_risk_report(self, report) -> Optional[str]: prompt = f"""Explain this blockchain transaction risk analysis in 2-3 simple sentences for a regular user: Transaction: {report.tx_summary} Risk Level: {report.recommendation.upper()}""" response = self.model.generate_content(prompt)Uses Gemini 1.5 Flash for natural language explanations. Logs show quota management:ERROR:src.infrastructure.gemini_real:Gemini API error: 429 You exceeded your current quota4. The Graph# Real Graph integration from graph_adapter.py async def _query_uniswap_activity(self, address: str) -> Optional[Dict[str, Any]]: query = """ query GetAddressActivity($address: String!) { account(id: $address) { swaps(first: 10, orderBy: timestamp, orderDirection: desc) { amountUSD token0 { symbol } token1 { symbol } } } }"""Queries Uniswap V3 subgraph for address reputation analysis. Includes fallback pattern analysis when Graph API returns 301 redirects.5. PayPal USD# Real PYUSD integration from paypalusd.py async def is_pyusd_token(self, token_address: str) -> bool: return token_address.lower() == self.pyusd_address.lower() async def get_pyusd_info(self, token_address: str) -> Optional[Dict[str, Any]]: name = self.pyusd_contract.functions.name().call() total_supply = self.pyusd_contract.functions.totalSupply().call()Direct integration with official PYUSD contracts on Ethereum (0x6c3ea9036406852006290770BEdFcAbA0e23A0e8). Logs show real data:INFO:src.infrastructure.paypalusd:💰 PYUSD detected: PYUSD, supply: 954952971.06M6. Hedera# Real Hedera integration from hedera_adapter.py async def store_analysis_result(self, report) -> Optional[str]: transaction = TopicMessageSubmitTransaction() transaction.setTopicId(self.topic) transaction.setMessage(message_bytes) response = transaction.execute(self.client)Stores analysis results in Hedera Consensus Service using Python SDK. Logs confirm successful storage:INFO:src.infrastructure.hedera_adapter:📝 ✅ Transaction submitted to Hedera HCSNotable Technical AchievementsEIP-3377-like JSON ConversionCustom decoder that transforms raw calldata like0x095ea7b3000000000000000000000000a0b86a33e6776c8b0c8b46c9e8b9e8b9e8b9e8b9ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffinto readable JSON showing it's an unlimited PYUSD approval.Robust Error HandlingAll integrations include fallback mechanisms. When The Graph API fails (301 redirects in logs), the system uses enhanced pattern analysis. When Gemini hits quota limits, analysis continues with technical details.Real-Time USD Impact CalculationCombines Chainlink price feeds with token decimals to show exact dollar impact. Example from logs: unlimited approval valued at $115,792,089,237,316,190+ for maximum uint256 values.Multi-Modal Input DetectionTelegram bot automatically distinguishes between:Calldata (starts with 0x, >66 chars): Routes to preventive analysisTransaction hashes (starts with 0x, exactly 66 chars): Routes to legacy analysisInvalid input: Shows appropriate error messagesProduction ArchitectureAsync/await throughout for non-blocking operationsComprehensive logging for debugging and monitoringClean separation of concerns enabling easy testingEnvironment variable configuration for all API keys and endpointsParticularly Hacky/Notable ElementsHedera Java SDK Integration: Used JPype to bridge Python with Java SDK, handling Java objects in Python code with proper error handling for timeout exceptions.Unlimited Value Detection: Checks for values >= 2^255 instead of exact 2^256-1 to catch various "unlimited" patterns used by different protocols.Graph API Fallback: When official Graph endpoints fail, implements pattern-based address analysis using entropy calculations and known protocol detection.EIP-3377 Standard Adaptation: While EIP-3377 isn't finalized, created a working implementation that transforms opaque calldata into standardized JSON format for transaction transparency.The entire system processes real transactions with live data from all six sponsors, as demonstrated in the logs and Telegram screenshots showing actual PYUSD transactions being analyzed with real USD impacts and risk assessments.

Hackathon

ETHGlobal New York 2025

2025

Contributors