Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -20,7 +20,7 @@ for module_name, pip_name in REQUIRED_PACKAGES.items():
|
|
| 20 |
print(f"✅ {pip_name} установлен!")
|
| 21 |
|
| 22 |
# ============================================
|
| 23 |
-
# 👑 TOMIRIS SPACE 23 v2.
|
| 24 |
# ============================================
|
| 25 |
import os, time, json, logging, asyncio
|
| 26 |
from typing import Dict, Any, List, Optional
|
|
@@ -36,25 +36,23 @@ logger = logging.getLogger("Space23_AnomalySentinel")
|
|
| 36 |
# ================= КОНФИГУРАЦИЯ =================
|
| 37 |
TRACKED_SYMBOLS = ["ETH/USD", "SOL/USD"]
|
| 38 |
HUB_URL = os.getenv("SPACE17_URL", "https://tomiris-ai-name5-5.hf.space")
|
| 39 |
-
ARBITER_URL = os.getenv("SPACE18_URL", "https://tomiris-ai-name6-6.hf.space")
|
| 40 |
ETHERSCAN_KEY = os.getenv("ETHERSCAN_KEY", "TZGVD58I2HZ9G4BBD548KX11E4JFH4J5GX")
|
| 41 |
SOLSCAN_KEY = os.getenv("SOLSCAN_KEY", "") # опционально
|
| 42 |
|
| 43 |
-
# Известные кошельки бирж/китов (Ethereum)
|
| 44 |
ETH_WHALE_WALLETS = [
|
| 45 |
-
"0x28C6c06298d514089D2Bd15f6A8a38c5d8d3a6B2",
|
| 46 |
-
"0xA274C1e7D16E7e6F7C0e68b9f5A1a1BCc6E39509",
|
| 47 |
-
"0xBE0eB53F46cDf7F88F0E6F9D4D1D08B42DAbcD17"
|
| 48 |
]
|
| 49 |
SOL_WHALE_WALLETS = [
|
| 50 |
-
"9L4rU4mZJ2o8H6h2Xw3V3vJ2x9f7DqFtRt3y5j7",
|
| 51 |
-
"8k3WkRLGkR9mZ9z3X3a3o5v3h5p7u5j3n4b5v6c"
|
| 52 |
]
|
| 53 |
|
| 54 |
CACHE_TTL = {"gas": 60, "whales": 300, "stablecoin": 300, "active": 600}
|
| 55 |
HISTORY_FILE = "anomaly_history.json"
|
|
|
|
| 56 |
|
| 57 |
-
# Circuit breaker
|
| 58 |
CIRCUIT_BREAKER = {}
|
| 59 |
|
| 60 |
def breaker_open(name: str) -> bool:
|
|
@@ -85,15 +83,13 @@ if os.path.exists(HISTORY_FILE):
|
|
| 85 |
else:
|
| 86 |
ANOMALY_HISTORY = deque(maxlen=500)
|
| 87 |
|
| 88 |
-
# История активных адресов
|
| 89 |
-
ACTIVE_HISTORY_FILE = "active_history.json"
|
| 90 |
if os.path.exists(ACTIVE_HISTORY_FILE):
|
| 91 |
with open(ACTIVE_HISTORY_FILE) as f:
|
| 92 |
active_history = json.load(f)
|
| 93 |
else:
|
| 94 |
active_history = {}
|
| 95 |
|
| 96 |
-
# ================= ЗАГРУЗКА ДАННЫХ =================
|
| 97 |
async def fetch_gas_oracle() -> Dict[str, Any]:
|
| 98 |
if breaker_open("etherscan"):
|
| 99 |
return {'avg_gas': 45, 'gas_level': 'NORMAL', 'is_anomaly': False}
|
|
@@ -114,13 +110,12 @@ async def fetch_gas_oracle() -> Dict[str, Any]:
|
|
| 114 |
return {'avg_gas': 45, 'gas_level': 'NORMAL', 'is_anomaly': False}
|
| 115 |
|
| 116 |
async def fetch_large_transactions(network: str) -> Dict[str, Any]:
|
| 117 |
-
"""Крупные транзакции из отслеживаемых кошельков."""
|
| 118 |
if network == "ethereum":
|
| 119 |
wallets = ETH_WHALE_WALLETS
|
| 120 |
api_url = f"https://api.etherscan.io/api?module=account&action=txlist&apikey={ETHERSCAN_KEY}"
|
| 121 |
else:
|
| 122 |
wallets = SOL_WHALE_WALLETS
|
| 123 |
-
api_url = f"https://api.solscan.io/api?module=account&action=txlist"
|
| 124 |
if breaker_open(f"whale_{network}"):
|
| 125 |
return {'large_transactions': [], 'count': 0, 'is_anomaly': False, 'signal': 'NORMAL'}
|
| 126 |
|
|
@@ -132,7 +127,7 @@ async def fetch_large_transactions(network: str) -> Dict[str, Any]:
|
|
| 132 |
txs = r.json().get('result', [])
|
| 133 |
for tx in txs:
|
| 134 |
value = float(tx.get('value', 0))
|
| 135 |
-
if network == "ethereum" and value > 100e18:
|
| 136 |
large_txs.append({
|
| 137 |
'hash': tx.get('hash', '')[:10],
|
| 138 |
'value_eth': round(value / 1e18, 2),
|
|
@@ -151,21 +146,16 @@ async def fetch_large_transactions(network: str) -> Dict[str, Any]:
|
|
| 151 |
}
|
| 152 |
|
| 153 |
async def fetch_stablecoin_flows(network: str) -> Dict[str, Any]:
|
| 154 |
-
"""Отслеживаем крупные транзакции USDT/USDC (mint/burn) как прокси ликвидности."""
|
| 155 |
if breaker_open(f"stablecoin_{network}"):
|
| 156 |
return {'signal': 'BALANCED', 'is_anomaly': False}
|
| 157 |
-
# Для Ethereum используем Etherscan токен-трансферы
|
| 158 |
if network == "ethereum":
|
| 159 |
-
# USDT контракт: 0xdAC17F958D2ee523a2206206994597C13D831ec7
|
| 160 |
-
# USDC контракт: 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48
|
| 161 |
usdt_url = f"https://api.etherscan.io/api?module=account&action=tokentx&address=0xdAC17F958D2ee523a2206206994597C13D831ec7&page=1&offset=10&sort=desc&apikey={ETHERSCAN_KEY}"
|
| 162 |
try:
|
| 163 |
r = await http_client.get(usdt_url)
|
| 164 |
if r.status_code == 200 and r.json().get('status') == '1':
|
| 165 |
txs = r.json().get('result', [])
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
anomaly = total_value > 10_000_000 # > 10 млн USDT за 10 транзакций
|
| 169 |
breaker_record("stablecoin_ethereum", True)
|
| 170 |
return {
|
| 171 |
'token': 'USDT',
|
|
@@ -175,7 +165,6 @@ async def fetch_stablecoin_flows(network: str) -> Dict[str, Any]:
|
|
| 175 |
}
|
| 176 |
except:
|
| 177 |
breaker_record("stablecoin_ethereum", False)
|
| 178 |
-
# Для Solana используем Solscan (заглушка, можно расширить)
|
| 179 |
return {'signal': 'BALANCED', 'is_anomaly': False}
|
| 180 |
|
| 181 |
async def fetch_active_addresses(chain: str) -> Dict[str, Any]:
|
|
@@ -189,7 +178,6 @@ async def fetch_active_addresses(chain: str) -> Dict[str, Any]:
|
|
| 189 |
prev = active_history.get(chain, current)
|
| 190 |
change = ((current - prev) / prev * 100) if prev > 0 else 0
|
| 191 |
active_history[chain] = current
|
| 192 |
-
# Сохраняем в файл
|
| 193 |
with open(ACTIVE_HISTORY_FILE, 'w') as f:
|
| 194 |
json.dump(active_history, f)
|
| 195 |
is_anomaly = abs(change) > 20
|
|
@@ -208,7 +196,6 @@ async def fetch_active_addresses(chain: str) -> Dict[str, Any]:
|
|
| 208 |
# ================= ДЕТЕКТОР АНОМАЛИЙ =================
|
| 209 |
async def detect_anomalies(symbol: str) -> Dict[str, Any]:
|
| 210 |
chain = "ethereum" if "ETH" in symbol else "solana"
|
| 211 |
-
native = "ETH" if chain == "ethereum" else "SOL"
|
| 212 |
|
| 213 |
gas = await fetch_gas_oracle() if chain == "ethereum" else {'is_anomaly': False}
|
| 214 |
whales = await fetch_large_transactions(chain)
|
|
@@ -240,7 +227,6 @@ async def detect_anomalies(symbol: str) -> Dict[str, Any]:
|
|
| 240 |
else:
|
| 241 |
level, direction = "NORMAL", "NEUTRAL"
|
| 242 |
|
| 243 |
-
# Сохраняем в историю
|
| 244 |
record = {
|
| 245 |
"timestamp": datetime.now(timezone.utc).isoformat(),
|
| 246 |
"symbol": symbol,
|
|
@@ -271,39 +257,49 @@ async def detect_anomalies(symbol: str) -> Dict[str, Any]:
|
|
| 271 |
}
|
| 272 |
}
|
| 273 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 274 |
# ================= ГЛАВНЫЙ СИГНАЛ =================
|
| 275 |
async def get_anomaly_signal(symbol: str = "ETH/USD") -> Dict[str, Any]:
|
| 276 |
start = time.time()
|
| 277 |
analysis = await detect_anomalies(symbol)
|
| 278 |
latency = int((time.time() - start) * 1000)
|
| 279 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 280 |
result = {
|
| 281 |
"space": "space_23_anomaly",
|
| 282 |
"timestamp": int(time.time()),
|
| 283 |
"symbol": symbol,
|
| 284 |
"signal": {
|
| 285 |
-
"direction":
|
| 286 |
-
"confidence":
|
| 287 |
},
|
| 288 |
"anomaly_analysis": analysis,
|
| 289 |
"latency_ms": latency
|
| 290 |
}
|
| 291 |
|
| 292 |
-
# Отправка в Arbiter (сигнал WAIT/NEUTRAL)
|
| 293 |
-
try:
|
| 294 |
-
await http_client.post(f"{ARBITER_URL}/log_signal", json={
|
| 295 |
-
"space": "space_23_anomaly",
|
| 296 |
-
"symbol": symbol,
|
| 297 |
-
"signal": result["signal"]
|
| 298 |
-
})
|
| 299 |
-
except:
|
| 300 |
-
pass
|
| 301 |
-
|
| 302 |
logger.info(f"🔍 Anomaly {symbol}: {analysis['anomaly_level']} | Score={analysis['anomaly_score']}")
|
| 303 |
return result
|
| 304 |
|
| 305 |
# ================= FASTAPI =================
|
| 306 |
-
app = FastAPI(title="Tomiris Space 23 v2.
|
| 307 |
|
| 308 |
@app.on_event("startup")
|
| 309 |
async def startup():
|
|
@@ -317,10 +313,10 @@ async def shutdown():
|
|
| 317 |
async def health():
|
| 318 |
return {
|
| 319 |
"status": "operational",
|
| 320 |
-
"version": "2.
|
| 321 |
"symbols": TRACKED_SYMBOLS,
|
| 322 |
"anomaly_history": len(ANOMALY_HISTORY),
|
| 323 |
-
"
|
| 324 |
}
|
| 325 |
|
| 326 |
@app.get("/consilium")
|
|
@@ -361,4 +357,4 @@ if __name__ == "__main__":
|
|
| 361 |
import uvicorn
|
| 362 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|
| 363 |
|
| 364 |
-
print("🚀 SPACE 23 v2.
|
|
|
|
| 20 |
print(f"✅ {pip_name} установлен!")
|
| 21 |
|
| 22 |
# ============================================
|
| 23 |
+
# 👑 TOMIRIS SPACE 23 v2.1 — ON-CHAIN ANOMALY SENTINEL (Hub-Connected)
|
| 24 |
# ============================================
|
| 25 |
import os, time, json, logging, asyncio
|
| 26 |
from typing import Dict, Any, List, Optional
|
|
|
|
| 36 |
# ================= КОНФИГУРАЦИЯ =================
|
| 37 |
TRACKED_SYMBOLS = ["ETH/USD", "SOL/USD"]
|
| 38 |
HUB_URL = os.getenv("SPACE17_URL", "https://tomiris-ai-name5-5.hf.space")
|
|
|
|
| 39 |
ETHERSCAN_KEY = os.getenv("ETHERSCAN_KEY", "TZGVD58I2HZ9G4BBD548KX11E4JFH4J5GX")
|
| 40 |
SOLSCAN_KEY = os.getenv("SOLSCAN_KEY", "") # опционально
|
| 41 |
|
|
|
|
| 42 |
ETH_WHALE_WALLETS = [
|
| 43 |
+
"0x28C6c06298d514089D2Bd15f6A8a38c5d8d3a6B2",
|
| 44 |
+
"0xA274C1e7D16E7e6F7C0e68b9f5A1a1BCc6E39509",
|
| 45 |
+
"0xBE0eB53F46cDf7F88F0E6F9D4D1D08B42DAbcD17"
|
| 46 |
]
|
| 47 |
SOL_WHALE_WALLETS = [
|
| 48 |
+
"9L4rU4mZJ2o8H6h2Xw3V3vJ2x9f7DqFtRt3y5j7",
|
| 49 |
+
"8k3WkRLGkR9mZ9z3X3a3o5v3h5p7u5j3n4b5v6c"
|
| 50 |
]
|
| 51 |
|
| 52 |
CACHE_TTL = {"gas": 60, "whales": 300, "stablecoin": 300, "active": 600}
|
| 53 |
HISTORY_FILE = "anomaly_history.json"
|
| 54 |
+
ACTIVE_HISTORY_FILE = "active_history.json"
|
| 55 |
|
|
|
|
| 56 |
CIRCUIT_BREAKER = {}
|
| 57 |
|
| 58 |
def breaker_open(name: str) -> bool:
|
|
|
|
| 83 |
else:
|
| 84 |
ANOMALY_HISTORY = deque(maxlen=500)
|
| 85 |
|
|
|
|
|
|
|
| 86 |
if os.path.exists(ACTIVE_HISTORY_FILE):
|
| 87 |
with open(ACTIVE_HISTORY_FILE) as f:
|
| 88 |
active_history = json.load(f)
|
| 89 |
else:
|
| 90 |
active_history = {}
|
| 91 |
|
| 92 |
+
# ================= ЗАГРУЗКА ДАННЫХ (без изменений) =================
|
| 93 |
async def fetch_gas_oracle() -> Dict[str, Any]:
|
| 94 |
if breaker_open("etherscan"):
|
| 95 |
return {'avg_gas': 45, 'gas_level': 'NORMAL', 'is_anomaly': False}
|
|
|
|
| 110 |
return {'avg_gas': 45, 'gas_level': 'NORMAL', 'is_anomaly': False}
|
| 111 |
|
| 112 |
async def fetch_large_transactions(network: str) -> Dict[str, Any]:
|
|
|
|
| 113 |
if network == "ethereum":
|
| 114 |
wallets = ETH_WHALE_WALLETS
|
| 115 |
api_url = f"https://api.etherscan.io/api?module=account&action=txlist&apikey={ETHERSCAN_KEY}"
|
| 116 |
else:
|
| 117 |
wallets = SOL_WHALE_WALLETS
|
| 118 |
+
api_url = f"https://api.solscan.io/api?module=account&action=txlist"
|
| 119 |
if breaker_open(f"whale_{network}"):
|
| 120 |
return {'large_transactions': [], 'count': 0, 'is_anomaly': False, 'signal': 'NORMAL'}
|
| 121 |
|
|
|
|
| 127 |
txs = r.json().get('result', [])
|
| 128 |
for tx in txs:
|
| 129 |
value = float(tx.get('value', 0))
|
| 130 |
+
if network == "ethereum" and value > 100e18:
|
| 131 |
large_txs.append({
|
| 132 |
'hash': tx.get('hash', '')[:10],
|
| 133 |
'value_eth': round(value / 1e18, 2),
|
|
|
|
| 146 |
}
|
| 147 |
|
| 148 |
async def fetch_stablecoin_flows(network: str) -> Dict[str, Any]:
|
|
|
|
| 149 |
if breaker_open(f"stablecoin_{network}"):
|
| 150 |
return {'signal': 'BALANCED', 'is_anomaly': False}
|
|
|
|
| 151 |
if network == "ethereum":
|
|
|
|
|
|
|
| 152 |
usdt_url = f"https://api.etherscan.io/api?module=account&action=tokentx&address=0xdAC17F958D2ee523a2206206994597C13D831ec7&page=1&offset=10&sort=desc&apikey={ETHERSCAN_KEY}"
|
| 153 |
try:
|
| 154 |
r = await http_client.get(usdt_url)
|
| 155 |
if r.status_code == 200 and r.json().get('status') == '1':
|
| 156 |
txs = r.json().get('result', [])
|
| 157 |
+
total_value = sum(int(tx['value']) for tx in txs) / 1e6
|
| 158 |
+
anomaly = total_value > 10_000_000
|
|
|
|
| 159 |
breaker_record("stablecoin_ethereum", True)
|
| 160 |
return {
|
| 161 |
'token': 'USDT',
|
|
|
|
| 165 |
}
|
| 166 |
except:
|
| 167 |
breaker_record("stablecoin_ethereum", False)
|
|
|
|
| 168 |
return {'signal': 'BALANCED', 'is_anomaly': False}
|
| 169 |
|
| 170 |
async def fetch_active_addresses(chain: str) -> Dict[str, Any]:
|
|
|
|
| 178 |
prev = active_history.get(chain, current)
|
| 179 |
change = ((current - prev) / prev * 100) if prev > 0 else 0
|
| 180 |
active_history[chain] = current
|
|
|
|
| 181 |
with open(ACTIVE_HISTORY_FILE, 'w') as f:
|
| 182 |
json.dump(active_history, f)
|
| 183 |
is_anomaly = abs(change) > 20
|
|
|
|
| 196 |
# ================= ДЕТЕКТОР АНОМАЛИЙ =================
|
| 197 |
async def detect_anomalies(symbol: str) -> Dict[str, Any]:
|
| 198 |
chain = "ethereum" if "ETH" in symbol else "solana"
|
|
|
|
| 199 |
|
| 200 |
gas = await fetch_gas_oracle() if chain == "ethereum" else {'is_anomaly': False}
|
| 201 |
whales = await fetch_large_transactions(chain)
|
|
|
|
| 227 |
else:
|
| 228 |
level, direction = "NORMAL", "NEUTRAL"
|
| 229 |
|
|
|
|
| 230 |
record = {
|
| 231 |
"timestamp": datetime.now(timezone.utc).isoformat(),
|
| 232 |
"symbol": symbol,
|
|
|
|
| 257 |
}
|
| 258 |
}
|
| 259 |
|
| 260 |
+
# ================= ОТПРАВКА В HUB =================
|
| 261 |
+
async def send_signal_to_hub(symbol: str, direction: str, confidence: float):
|
| 262 |
+
try:
|
| 263 |
+
await http_client.post(f"{HUB_URL}/signal", json={
|
| 264 |
+
"space": "space_23_anomaly",
|
| 265 |
+
"symbol": symbol,
|
| 266 |
+
"direction": direction,
|
| 267 |
+
"confidence": confidence,
|
| 268 |
+
"raw": json.dumps({"source": "space_23_anomaly"})
|
| 269 |
+
})
|
| 270 |
+
logger.info(f"📤 {symbol}: {direction} conf={confidence:.3f} отправлен в Hub")
|
| 271 |
+
except Exception as e:
|
| 272 |
+
logger.error(f"Ошибка отправки в Hub: {e}")
|
| 273 |
+
|
| 274 |
# ================= ГЛАВНЫЙ СИГНАЛ =================
|
| 275 |
async def get_anomaly_signal(symbol: str = "ETH/USD") -> Dict[str, Any]:
|
| 276 |
start = time.time()
|
| 277 |
analysis = await detect_anomalies(symbol)
|
| 278 |
latency = int((time.time() - start) * 1000)
|
| 279 |
|
| 280 |
+
direction = analysis['signal']
|
| 281 |
+
confidence = round(analysis['anomaly_score'] / 100, 4) if analysis['anomaly_score'] > 0 else 0.0
|
| 282 |
+
|
| 283 |
+
# Отправка в Hub
|
| 284 |
+
await send_signal_to_hub(symbol, direction, confidence)
|
| 285 |
+
|
| 286 |
result = {
|
| 287 |
"space": "space_23_anomaly",
|
| 288 |
"timestamp": int(time.time()),
|
| 289 |
"symbol": symbol,
|
| 290 |
"signal": {
|
| 291 |
+
"direction": direction,
|
| 292 |
+
"confidence": confidence
|
| 293 |
},
|
| 294 |
"anomaly_analysis": analysis,
|
| 295 |
"latency_ms": latency
|
| 296 |
}
|
| 297 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 298 |
logger.info(f"🔍 Anomaly {symbol}: {analysis['anomaly_level']} | Score={analysis['anomaly_score']}")
|
| 299 |
return result
|
| 300 |
|
| 301 |
# ================= FASTAPI =================
|
| 302 |
+
app = FastAPI(title="Tomiris Space 23 v2.1 — On-Chain Anomaly Sentinel (Hub)")
|
| 303 |
|
| 304 |
@app.on_event("startup")
|
| 305 |
async def startup():
|
|
|
|
| 313 |
async def health():
|
| 314 |
return {
|
| 315 |
"status": "operational",
|
| 316 |
+
"version": "2.1",
|
| 317 |
"symbols": TRACKED_SYMBOLS,
|
| 318 |
"anomaly_history": len(ANOMALY_HISTORY),
|
| 319 |
+
"hub_connected": True
|
| 320 |
}
|
| 321 |
|
| 322 |
@app.get("/consilium")
|
|
|
|
| 357 |
import uvicorn
|
| 358 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|
| 359 |
|
| 360 |
+
print("🚀 SPACE 23 v2.1 — ON-CHAIN ANOMALY SENTINEL (Hub-Connected) ЗАПУЩЕН!")
|