rmi-backend/app/_archive/legacy_2026_07/liquidity_watchdog.py
cryptorugmunch 628c1d2a10
Some checks failed
CI / build (push) Failing after 3s
refactor(rmi-backend,audit): mount Wave 3 + archive 136 dead-code files (P2.3)
PHASE 2.3 (AUDIT-2026-Q3.md):

Task 1 — Wire-in Wave 3 (1 router mounted, 2 deferred):
  - app.routers.unified_scanner_router mounted at /api/v2/scanner/* (2 routes:
    POST /api/v2/scanner/token/scan, POST /api/v2/scanner/wallet/scan).
    Refactored prefix from /api/v2 -> /api/v2/scanner to avoid future conflicts
    with the v1 /api/v1/scanner/ stub.
  - app.routers.unified_wallet_scanner DEFERRED (no router APIRouter attribute;
    library module consumed by unified_scanner_router via get_wallet_scanner()).
  - app.routers.admin_extensions DEFERRED (DORMANT per audit; 25 routes at
    /api/v1/admin/* would shadow /api/v1/admin/alerts_webhook).

Task 2 — Archive 136 dead-code files to app/_archive/legacy_2026_07/:
  - 73 routers in app/routers/ (reach graph showed zero reach into mount.py).
  - 63 flat app/*.py (domain modules never imported by live code).
  - 1 file RESTORED post-archive: app/routers/x402_bridge_health.py (caught by
    tests/unit/test_bridge_health.py which directly imports it; reach graph
    considered tests/ only as transitive reach — to be patched in next cycle).

Forced-LIVE (NOT archived per user directive):
  - app/ai_pipeline_v3.py  (3 importers in audit window, importers themselves DEAD)
  - app/splade_bm25.py       (LIVE via app.rag_service)
  - app/wallet_manager_v2.py (LIVE via x402_enforcement, x402_tools, sweep_all, sweep_now)
  - app/crypto_embeddings.py (NOT in audit ARCHIVE list; heavy import graph)

Verification (forward-import closure from mount.py + main.py + factory.py + lifespan.py):
  - imports = 348 app.* modules
  - reached = 194 files reachable from roots
  - archive set = audit_dead (186) - reached - forced_live (4) - test_live (1) = 136
  - Net delta: 136 files moved, 44,932 LOC reduction, 293->295 active routes (+2 from Wave 3)

pyproject.toml updates:
  - setuptools.packages.find: added exclude for app._archive*
  - ruff.extend-exclude: added "app/_archive/"
  - mypy.exclude: added "app/_archive/"

Smoke test: pytest tests/ — 817 passed, 3 pre-existing failures unchanged
(0 new failures; 0 routes lost; all 4 forced-LIVE files still importable).

Restoration: git mv app/_archive/legacy_2026_07/<name>.py <original-path>
and add the import to app/mount.py ROUTER_MODULES.

Refs: AUDIT-2026-Q3.md /home/dev/pry/rmi-final-deadcode-2026-07-06.md
2026-07-06 20:52:31 +02:00

176 lines
5.8 KiB
Python

"""
Liquidity Watchdog Router
=========================
FastAPI endpoints for monitoring liquidity lock expiries.
Endpoints:
GET /api/v1/alerts/liquidity-expiring → Upcoming lock expiries within 24h
POST /api/v1/alerts/liquidity-track → Register a token for monitoring
"""
import logging
from typing import Any
from fastapi import APIRouter, HTTPException, Query
from pydantic import BaseModel, Field
from app.liquidity_watchdog import (
check_all_locks_summary,
check_expiring_locks,
get_tracked_tokens,
track_token,
untrack_token,
)
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/v1/alerts", tags=["liquidity-watchdog"])
# ── Request/Response models ──────────────────────────────────────
class LiquidityTrackRequest(BaseModel):
token_address: str = Field(..., description="Token contract/mint address")
chain: str = Field(..., description="Blockchain name (e.g. solana, ethereum, bsc)")
lock_expiry_timestamp: int = Field(..., description="Unix timestamp (seconds) when lock expires")
liquidity_amount: float = Field(0.0, description="Locked liquidity amount in USD")
class LiquidityTrackResponse(BaseModel):
status: str = "ok"
message: str = "Token registered for liquidity expiry monitoring"
data: dict[str, Any]
class ExpiringLock(BaseModel):
token: str
chain: str
lock_expiry: int
hours_remaining: float
liquidity_amount: float
class LiquidityExpiringResponse(BaseModel):
status: str = "ok"
count: int = 0
expiring: list[ExpiringLock] = []
class LiquiditySummaryResponse(BaseModel):
status: str = "ok"
total_tracked: int = 0
already_expired: int = 0
expiring_soon: int = 0
safe: int = 0
expiring_tokens: list[ExpiringLock] = []
# ── Endpoints ────────────────────────────────────────────────────
@router.post("/liquidity-track", response_model=LiquidityTrackResponse)
async def post_liquidity_track(req: LiquidityTrackRequest):
"""Register a token for liquidity lock expiry monitoring.
This will be called by a cron job that pings Telegram/community channels
when locks are about to expire.
The token's lock expiry is checked against the current time to determine
if it's already expired (returns a warning but still registers it).
"""
if not req.token_address or not req.token_address.strip():
raise HTTPException(status_code=400, detail="token_address is required")
if not req.chain or not req.chain.strip():
raise HTTPException(status_code=400, detail="chain is required")
if req.lock_expiry_timestamp <= 0:
raise HTTPException(
status_code=400,
detail="lock_expiry_timestamp must be a positive unix timestamp",
)
data = track_token(
token_address=req.token_address,
chain=req.chain,
lock_expiry_timestamp=req.lock_expiry_timestamp,
liquidity_amount=req.liquidity_amount or 0.0,
)
return LiquidityTrackResponse(
status="ok",
message="Token registered for liquidity expiry monitoring",
data=data,
)
@router.get("/liquidity-expiring", response_model=LiquidityExpiringResponse)
async def get_liquidity_expiring(
hours: float | None = Query(
None,
description="Override the expiry window in hours (default: 24). "
"Only returns locks expiring within this many hours.",
),
):
"""Get all tracked tokens with liquidity locks expiring within the default
24-hour window (or a custom window via the `hours` query parameter).
Returns tokens sorted by urgency (most imminent first).
"""
if hours is not None and hours <= 0:
raise HTTPException(status_code=400, detail="hours must be > 0")
# If a custom hours window is given, we temporarily override the module's
# default and re-check. Since check_expiring_locks() uses a module constant,
# we just call it once and filter further if needed.
expiring = check_expiring_locks()
if hours is not None:
expiring = [e for e in expiring if e["hours_remaining"] <= hours]
expiring_models = [ExpiringLock(**e) for e in expiring]
return LiquidityExpiringResponse(
status="ok",
count=len(expiring_models),
expiring=expiring_models,
)
@router.get("/liquidity-tracked", response_model=dict)
async def get_liquidity_tracked():
"""List all tokens currently being monitored for liquidity expiry."""
tokens = get_tracked_tokens()
return {
"status": "ok",
"count": len(tokens),
"tokens": tokens,
}
@router.get("/liquidity-summary", response_model=LiquiditySummaryResponse)
async def get_liquidity_summary():
"""Get a summary of all tracked liquidity locks with counts."""
summary = check_all_locks_summary()
return LiquiditySummaryResponse(
status="ok",
total_tracked=summary["total_tracked"],
already_expired=summary["already_expired"],
expiring_soon=summary["expiring_soon"],
safe=summary["safe"],
expiring_tokens=[ExpiringLock(**e) for e in summary["expiring_tokens"]],
)
@router.delete("/liquidity-track/{chain}/{token_address}", response_model=dict)
async def delete_liquidity_track(chain: str, token_address: str):
"""Remove a token from liquidity expiry monitoring."""
removed = untrack_token(token_address, chain)
if not removed:
raise HTTPException(
status_code=404,
detail=f"Token {token_address} on {chain} is not being tracked",
)
return {
"status": "ok",
"message": f"Token {token_address} on {chain} removed from monitoring",
}