rmi-backend/app/_archive/legacy_2026_07/alchemy_router.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

272 lines
10 KiB
Python

"""
Alchemy API Router - NFT API, Enhanced API, Transaction API.
Endpoints for NFT discovery, whale tracking, token metadata, and contract analysis.
"""
import logging
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/v1/alchemy", tags=["alchemy"])
# ── Models ───────────────────────────────────────────────────
class NftQuery(BaseModel):
owner: str
network: str = "eth"
page_size: int = 50
class NftMetadataQuery(BaseModel):
contract: str
token_id: str
network: str = "eth"
class CollectionOwnersQuery(BaseModel):
contract: str
network: str = "eth"
page_size: int = 50
class TokenBalanceQuery(BaseModel):
address: str
network: str = "eth"
class AssetTransferQuery(BaseModel):
from_address: str | None = None
to_address: str | None = None
network: str = "eth"
category: list[str] = ["external", "internal", "erc20", "erc721"]
max_count: int = 100
class ContractCallQuery(BaseModel):
contract: str
data: str
network: str = "eth"
from_address: str | None = None
# ── NFT API Endpoints ────────────────────────────────────────
@router.post("/nfts")
async def get_nfts(req: NftQuery):
"""Get all NFTs owned by an address."""
try:
from app.alchemy_connector import get_alchemy_connector
ac = get_alchemy_connector()
result = await ac.get_nfts(req.owner, req.network, req.page_size)
return {"owner": req.owner, "network": req.network, **result}
except ImportError:
raise HTTPException(status_code=503, detail="Alchemy connector not available") from None
except Exception as e:
raise HTTPException(status_code=500, detail=str(e)[:200]) from e
@router.get("/nft/metadata")
async def get_nft_metadata(contract: str, token_id: str, network: str = "eth"):
"""Get metadata for a specific NFT."""
try:
from app.alchemy_connector import get_alchemy_connector
ac = get_alchemy_connector()
result = await ac.get_nft_metadata(contract, token_id, network)
return {"contract": contract, "token_id": token_id, "metadata": result}
except ImportError:
raise HTTPException(status_code=503, detail="Alchemy connector not available") from None
except Exception as e:
raise HTTPException(status_code=500, detail=str(e)[:200]) from e
@router.get("/collection/owners")
async def get_collection_owners(contract: str, network: str = "eth", page_size: int = 50):
"""Get all owners of an NFT collection."""
try:
from app.alchemy_connector import get_alchemy_connector
ac = get_alchemy_connector()
result = await ac.get_owners_for_collection(contract, network, page_size)
return {"contract": contract, "network": network, **result}
except ImportError:
raise HTTPException(status_code=503, detail="Alchemy connector not available") from None
except Exception as e:
raise HTTPException(status_code=500, detail=str(e)[:200]) from e
@router.get("/contract/metadata")
async def get_contract_metadata(contract: str, network: str = "eth"):
"""Get NFT contract metadata (name, symbol, totalSupply)."""
try:
from app.alchemy_connector import get_alchemy_connector
ac = get_alchemy_connector()
result = await ac.get_contract_metadata(contract, network)
# Unwrap contractMetadata if present
if isinstance(result, dict) and "contractMetadata" in result:
result = result["contractMetadata"]
return {"contract": contract, "network": network, "metadata": result}
except ImportError:
raise HTTPException(status_code=503, detail="Alchemy connector not available") from None
except Exception as e:
raise HTTPException(status_code=500, detail=str(e)[:200]) from e
@router.get("/nft-sales")
async def get_nft_sales(contract: str | None = None, network: str = "eth", limit: int = 50):
"""Get recent NFT sales."""
try:
from app.alchemy_connector import get_alchemy_connector
ac = get_alchemy_connector()
result = await ac.get_nft_sales(contract, network, limit)
return {"contract": contract, "network": network, **result}
except ImportError:
raise HTTPException(status_code=503, detail="Alchemy connector not available") from None
except Exception as e:
raise HTTPException(status_code=500, detail=str(e)[:200]) from e
# ── Enhanced API Endpoints ───────────────────────────────────
@router.post("/token/balances")
async def get_token_balances(req: TokenBalanceQuery):
"""Get all ERC-20 token balances for an address."""
try:
from app.alchemy_connector import get_alchemy_connector
ac = get_alchemy_connector()
result = await ac.get_token_balances(req.address, req.network)
return {"address": req.address, "network": req.network, **result}
except ImportError:
raise HTTPException(status_code=503, detail="Alchemy connector not available") from None
except Exception as e:
raise HTTPException(status_code=500, detail=str(e)[:200]) from e
@router.get("/token/metadata")
async def get_token_metadata(contract: str, network: str = "eth"):
"""Get ERC-20 token metadata."""
try:
from app.alchemy_connector import get_alchemy_connector
ac = get_alchemy_connector()
result = await ac.get_token_metadata(contract, network)
return {"contract": contract, "network": network, "metadata": result}
except ImportError:
raise HTTPException(status_code=503, detail="Alchemy connector not available") from None
except Exception as e:
raise HTTPException(status_code=500, detail=str(e)[:200]) from e
@router.post("/transfers")
async def get_asset_transfers(req: AssetTransferQuery):
"""Get asset transfers (tokens, NFTs, internal)."""
try:
from app.alchemy_connector import get_alchemy_connector
ac = get_alchemy_connector()
result = await ac.get_asset_transfers(
from_address=req.from_address,
to_address=req.to_address,
network=req.network,
category=req.category,
max_count=req.max_count,
)
return {"network": req.network, **result}
except ImportError:
raise HTTPException(status_code=503, detail="Alchemy connector not available") from None
except Exception as e:
raise HTTPException(status_code=500, detail=str(e)[:200]) from e
# ── Transaction API Endpoints ────────────────────────────────
@router.get("/tx/{tx_hash}/receipt")
async def get_transaction_receipt(tx_hash: str, network: str = "eth"):
"""Get transaction receipt with enhanced data."""
try:
from app.alchemy_connector import get_alchemy_connector
ac = get_alchemy_connector()
result = await ac.get_transaction_receipt(tx_hash, network)
return {"tx_hash": tx_hash, "network": network, "receipt": result}
except ImportError:
raise HTTPException(status_code=503, detail="Alchemy connector not available") from None
except Exception as e:
raise HTTPException(status_code=500, detail=str(e)[:200]) from e
@router.get("/block/{block_number}")
async def get_block(block_number: int, network: str = "eth", include_txs: bool = False):
"""Get block data."""
try:
from app.alchemy_connector import get_alchemy_connector
ac = get_alchemy_connector()
result = await ac.get_block_by_number(block_number, network, include_txs)
return {"block_number": block_number, "network": network, "block": result}
except ImportError:
raise HTTPException(status_code=503, detail="Alchemy connector not available") from None
except Exception as e:
raise HTTPException(status_code=500, detail=str(e)[:200]) from e
@router.get("/balance/{address}")
async def get_balance(address: str, network: str = "eth", block: str = "latest"):
"""Get native token balance."""
try:
from app.alchemy_connector import get_alchemy_connector
ac = get_alchemy_connector()
result = await ac.get_balance(address, network, block)
# Convert hex wei to ETH
try:
eth = int(result, 16) / 1e18 if result.startswith("0x") else float(result)
except Exception:
eth = 0
return {"address": address, "network": network, "balance_wei": result, "balance_eth": eth}
except ImportError:
raise HTTPException(status_code=503, detail="Alchemy connector not available") from None
except Exception as e:
raise HTTPException(status_code=500, detail=str(e)[:200]) from e
@router.post("/contract/call")
async def contract_call(req: ContractCallQuery):
"""Call a contract read function."""
try:
from app.alchemy_connector import get_alchemy_connector
ac = get_alchemy_connector()
result = await ac.call_contract(req.contract, req.data, req.network, req.from_address)
return {"contract": req.contract, "network": req.network, "result": result}
except ImportError:
raise HTTPException(status_code=503, detail="Alchemy connector not available") from None
except Exception as e:
raise HTTPException(status_code=500, detail=str(e)[:200]) from e
# ── Health ────────────────────────────────────────────────────
@router.get("/health")
async def alchemy_health():
"""Alchemy connector status."""
try:
from app.alchemy_connector import get_alchemy_connector
ac = get_alchemy_connector()
return {"status": "ok", "service": "alchemy-connector", **ac.status()}
except ImportError:
return {"status": "ok", "service": "alchemy-connector", "api_key_set": False}