AI-powered Telegram bot predicting transaction risks before signing
SafeSign is a Telegram bot that analyzes blockchain transactions before 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 Solved
The bot addresses the "blind signing" problem where users approve transactions without understanding what they're authorizing. When wallets show cryptic calldata like 0x095ea7b3000000000000000000000000a0b86a33e6776c8b0c8b46c9e8b9e8b9e8b9e8b9ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff, users have no idea they're granting unlimited token spending rights.
How SafeSign Works
1. Preventive Calldata Analysis Users 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 Analysis The system runs comprehensive security checks including:
3. Live Data Integration Each analysis incorporates real-time data from six sponsor APIs:
4. Clear Risk Communication Results are presented with intuitive risk levels:
Technical Implementation
EIP-3377-like Decoder Custom 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 Analysis
Real Transaction Examples from Logs
User Interface Telegram bot with clean menu system allowing users to:
SafeSign transforms the opaque world of blockchain transactions into transparent, actionable intelligence, enabling informed decision-making before any financial damage occurs.
SafeSign is built with a clean hexagonal architecture integrating six sponsor technologies through live API calls and real-time blockchain interactions.
Core Architecture
Domain 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 Integrations
1. 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 via eth_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.85
3. 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 quota
4. 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.06M
6. 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 HCS
Notable Technical Achievements
EIP-3377-like JSON Conversion
Custom decoder that transforms raw calldata like 0x095ea7b3000000000000000000000000a0b86a33e6776c8b0c8b46c9e8b9e8b9e8b9e8b9ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff into readable JSON showing it's an unlimited PYUSD approval.
Robust Error Handling All 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 Calculation Combines 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 Detection Telegram bot automatically distinguishes between:
Production Architecture
Particularly Hacky/Notable Elements
Hedera 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.

