Fix type annotation gaps in coordinator-api routers

- Add return type annotations to all async functions
- Add argument type annotations to functions missing them
- Add missing imports for typing (Any, Annotated, etc.)
- Add missing imports for FastAPI components (Query, Body, HTTPException)
- Fix validator functions in bounty.py and staking.py
- Fix dependency injection functions in agent_identity.py
- All 236 Ruff ANN001/ANN201 errors resolved across 26 files
This commit is contained in:
aitbc
2026-04-30 10:24:17 +02:00
parent ed128014c6
commit 09b0edc212
27 changed files with 267 additions and 240 deletions

View File

@@ -17,6 +17,7 @@ from aitbc import get_logger
logger = get_logger(__name__) logger = get_logger(__name__)
from ..domain.agent_performance import CreativeCapability from ..domain.agent_performance import CreativeCapability
from sqlmodel import select
from ..services.creative_capabilities_service import ( from ..services.creative_capabilities_service import (
CreativityEnhancementEngine, CreativityEnhancementEngine,
CrossDomainCreativeIntegrator, CrossDomainCreativeIntegrator,
@@ -82,7 +83,7 @@ class SynthesisRequest(BaseModel):
@router.post("/capabilities", response_model=CreativeCapabilityResponse) @router.post("/capabilities", response_model=CreativeCapabilityResponse)
async def create_creative_capability(request: CreativeCapabilityCreate, session: Annotated[Session, Depends(get_session)]): async def create_creative_capability(request: CreativeCapabilityCreate, session: Annotated[Session, Depends(get_session)]) -> CreativeCapabilityResponse:
"""Initialize a new creative capability for an agent""" """Initialize a new creative capability for an agent"""
engine = CreativityEnhancementEngine() engine = CreativityEnhancementEngine()
@@ -105,7 +106,7 @@ async def create_creative_capability(request: CreativeCapabilityCreate, session:
@router.post("/capabilities/{capability_id}/enhance") @router.post("/capabilities/{capability_id}/enhance")
async def enhance_creativity( async def enhance_creativity(
capability_id: str, request: EnhanceCreativityRequest, session: Annotated[Session, Depends(get_session)] capability_id: str, request: EnhanceCreativityRequest, session: Annotated[Session, Depends(get_session)]
): ) -> dict[str, Any]:
"""Enhance a specific creative capability using specified algorithm""" """Enhance a specific creative capability using specified algorithm"""
engine = CreativityEnhancementEngine() engine = CreativityEnhancementEngine()
@@ -124,7 +125,7 @@ async def enhance_creativity(
@router.post("/capabilities/{capability_id}/evaluate") @router.post("/capabilities/{capability_id}/evaluate")
async def evaluate_creation( async def evaluate_creation(
capability_id: str, request: EvaluateCreationRequest, session: Annotated[Session, Depends(get_session)] capability_id: str, request: EvaluateCreationRequest, session: Annotated[Session, Depends(get_session)]
): ) -> dict[str, Any]:
"""Evaluate a creative output and update agent capability metrics""" """Evaluate a creative output and update agent capability metrics"""
engine = CreativityEnhancementEngine() engine = CreativityEnhancementEngine()
@@ -144,7 +145,7 @@ async def evaluate_creation(
@router.post("/ideation/generate") @router.post("/ideation/generate")
async def generate_ideas(request: IdeationRequest): async def generate_ideas(request: IdeationRequest) -> dict[str, Any]:
"""Generate innovative ideas using specialized ideation algorithms""" """Generate innovative ideas using specialized ideation algorithms"""
ideation_engine = IdeationAlgorithm() ideation_engine = IdeationAlgorithm()
@@ -163,7 +164,7 @@ async def generate_ideas(request: IdeationRequest):
@router.post("/synthesis/cross-domain") @router.post("/synthesis/cross-domain")
async def synthesize_cross_domain(request: SynthesisRequest, session: Annotated[Session, Depends(get_session)]): async def synthesize_cross_domain(request: SynthesisRequest, session: Annotated[Session, Depends(get_session)]) -> dict[str, Any]:
"""Synthesize concepts from multiple domains to create novel outputs""" """Synthesize concepts from multiple domains to create novel outputs"""
integrator = CrossDomainCreativeIntegrator() integrator = CrossDomainCreativeIntegrator()
@@ -184,7 +185,7 @@ async def synthesize_cross_domain(request: SynthesisRequest, session: Annotated[
@router.get("/capabilities/{agent_id}") @router.get("/capabilities/{agent_id}")
async def list_agent_creative_capabilities(agent_id: str, session: Annotated[Session, Depends(get_session)]): async def list_agent_creative_capabilities(agent_id: str, session: Annotated[Session, Depends(get_session)]) -> list[CreativeCapability]:
"""List all creative capabilities for a specific agent""" """List all creative capabilities for a specific agent"""
try: try:
capabilities = session.execute(select(CreativeCapability).where(CreativeCapability.agent_id == agent_id)).all() capabilities = session.execute(select(CreativeCapability).where(CreativeCapability.agent_id == agent_id)).all()

View File

@@ -20,7 +20,7 @@ from ..storage.db import get_session
router = APIRouter(prefix="/agent-identity", tags=["Agent Identity"]) router = APIRouter(prefix="/agent-identity", tags=["Agent Identity"])
def get_identity_manager(session=Depends(get_session)) -> AgentIdentityManager: def get_identity_manager(session: Session = Depends(get_session)) -> AgentIdentityManager:
"""Dependency injection for AgentIdentityManager""" """Dependency injection for AgentIdentityManager"""
return AgentIdentityManager(session) return AgentIdentityManager(session)
@@ -29,7 +29,7 @@ def get_identity_manager(session=Depends(get_session)) -> AgentIdentityManager:
@router.post("/identities", response_model=dict[str, Any]) @router.post("/identities", response_model=dict[str, Any])
async def create_agent_identity(request: dict[str, Any], manager: AgentIdentityManager = Depends(get_identity_manager)): async def create_agent_identity(request: dict[str, Any], manager: AgentIdentityManager = Depends(get_identity_manager)) -> JSONResponse:
"""Create a new agent identity with cross-chain mappings""" """Create a new agent identity with cross-chain mappings"""
try: try:
result = await manager.create_agent_identity( result = await manager.create_agent_identity(
@@ -46,7 +46,7 @@ async def create_agent_identity(request: dict[str, Any], manager: AgentIdentityM
@router.get("/identities/{agent_id}", response_model=dict[str, Any]) @router.get("/identities/{agent_id}", response_model=dict[str, Any])
async def get_agent_identity(agent_id: str, manager: AgentIdentityManager = Depends(get_identity_manager)): async def get_agent_identity(agent_id: str, manager: AgentIdentityManager = Depends(get_identity_manager)) -> dict[str, Any]:
"""Get comprehensive agent identity summary""" """Get comprehensive agent identity summary"""
try: try:
result = await manager.get_agent_identity_summary(agent_id) result = await manager.get_agent_identity_summary(agent_id)
@@ -62,7 +62,7 @@ async def get_agent_identity(agent_id: str, manager: AgentIdentityManager = Depe
@router.put("/identities/{agent_id}", response_model=dict[str, Any]) @router.put("/identities/{agent_id}", response_model=dict[str, Any])
async def update_agent_identity( async def update_agent_identity(
agent_id: str, request: dict[str, Any], manager: AgentIdentityManager = Depends(get_identity_manager) agent_id: str, request: dict[str, Any], manager: AgentIdentityManager = Depends(get_identity_manager)
): ) -> dict[str, Any]:
"""Update agent identity and related components""" """Update agent identity and related components"""
try: try:
result = await manager.update_agent_identity(agent_id, request) result = await manager.update_agent_identity(agent_id, request)
@@ -78,7 +78,7 @@ async def update_agent_identity(
@router.post("/identities/{agent_id}/deactivate", response_model=dict[str, Any]) @router.post("/identities/{agent_id}/deactivate", response_model=dict[str, Any])
async def deactivate_agent_identity( async def deactivate_agent_identity(
agent_id: str, request: dict[str, Any], manager: AgentIdentityManager = Depends(get_identity_manager) agent_id: str, request: dict[str, Any], manager: AgentIdentityManager = Depends(get_identity_manager)
): ) -> dict[str, Any]:
"""Deactivate an agent identity across all chains""" """Deactivate an agent identity across all chains"""
try: try:
reason = request.get("reason", "") reason = request.get("reason", "")
@@ -98,7 +98,7 @@ async def deactivate_agent_identity(
@router.post("/identities/{agent_id}/cross-chain/register", response_model=dict[str, Any]) @router.post("/identities/{agent_id}/cross-chain/register", response_model=dict[str, Any])
async def register_cross_chain_identity( async def register_cross_chain_identity(
agent_id: str, request: dict[str, Any], manager: AgentIdentityManager = Depends(get_identity_manager) agent_id: str, request: dict[str, Any], manager: AgentIdentityManager = Depends(get_identity_manager)
): ) -> dict[str, Any]:
"""Register cross-chain identity mappings""" """Register cross-chain identity mappings"""
try: try:
chain_mappings = request["chain_mappings"] chain_mappings = request["chain_mappings"]
@@ -115,7 +115,7 @@ async def register_cross_chain_identity(
@router.get("/identities/{agent_id}/cross-chain/mapping", response_model=list[CrossChainMappingResponse]) @router.get("/identities/{agent_id}/cross-chain/mapping", response_model=list[CrossChainMappingResponse])
async def get_cross_chain_mapping(agent_id: str, manager: AgentIdentityManager = Depends(get_identity_manager)): async def get_cross_chain_mapping(agent_id: str, manager: AgentIdentityManager = Depends(get_identity_manager)) -> list[CrossChainMappingResponse]:
"""Get all cross-chain mappings for an agent""" """Get all cross-chain mappings for an agent"""
try: try:
mappings = await manager.registry.get_all_cross_chain_mappings(agent_id) mappings = await manager.registry.get_all_cross_chain_mappings(agent_id)
@@ -145,7 +145,7 @@ async def get_cross_chain_mapping(agent_id: str, manager: AgentIdentityManager =
@router.put("/identities/{agent_id}/cross-chain/{chain_id}", response_model=dict[str, Any]) @router.put("/identities/{agent_id}/cross-chain/{chain_id}", response_model=dict[str, Any])
async def update_cross_chain_mapping( async def update_cross_chain_mapping(
agent_id: str, chain_id: int, request: dict[str, Any], manager: AgentIdentityManager = Depends(get_identity_manager) agent_id: str, chain_id: int, request: dict[str, Any], manager: AgentIdentityManager = Depends(get_identity_manager)
): ) -> dict[str, Any]:
"""Update cross-chain mapping for a specific chain""" """Update cross-chain mapping for a specific chain"""
try: try:
new_address = request.get("new_address") new_address = request.get("new_address")
@@ -175,7 +175,7 @@ async def update_cross_chain_mapping(
@router.post("/identities/{agent_id}/cross-chain/{chain_id}/verify", response_model=dict[str, Any]) @router.post("/identities/{agent_id}/cross-chain/{chain_id}/verify", response_model=dict[str, Any])
async def verify_cross_chain_identity( async def verify_cross_chain_identity(
agent_id: str, chain_id: int, request: dict[str, Any], manager: AgentIdentityManager = Depends(get_identity_manager) agent_id: str, chain_id: int, request: dict[str, Any], manager: AgentIdentityManager = Depends(get_identity_manager)
): ) -> dict[str, Any]:
"""Verify identity on a specific blockchain""" """Verify identity on a specific blockchain"""
try: try:
# Get identity ID # Get identity ID
@@ -209,7 +209,7 @@ async def verify_cross_chain_identity(
@router.post("/identities/{agent_id}/migrate", response_model=dict[str, Any]) @router.post("/identities/{agent_id}/migrate", response_model=dict[str, Any])
async def migrate_agent_identity( async def migrate_agent_identity(
agent_id: str, request: dict[str, Any], manager: AgentIdentityManager = Depends(get_identity_manager) agent_id: str, request: dict[str, Any], manager: AgentIdentityManager = Depends(get_identity_manager)
): ) -> dict[str, Any]:
"""Migrate agent identity from one chain to another""" """Migrate agent identity from one chain to another"""
try: try:
result = await manager.migrate_agent_identity( result = await manager.migrate_agent_identity(
@@ -226,7 +226,7 @@ async def migrate_agent_identity(
@router.post("/identities/{agent_id}/wallets", response_model=dict[str, Any]) @router.post("/identities/{agent_id}/wallets", response_model=dict[str, Any])
async def create_agent_wallet( async def create_agent_wallet(
agent_id: str, request: dict[str, Any], manager: AgentIdentityManager = Depends(get_identity_manager) agent_id: str, request: dict[str, Any], manager: AgentIdentityManager = Depends(get_identity_manager)
): ) -> dict[str, Any]:
"""Create an agent wallet on a specific blockchain""" """Create an agent wallet on a specific blockchain"""
try: try:
wallet = await manager.wallet_adapter.create_agent_wallet( wallet = await manager.wallet_adapter.create_agent_wallet(
@@ -247,7 +247,7 @@ async def create_agent_wallet(
@router.get("/identities/{agent_id}/wallets/{chain_id}/balance", response_model=dict[str, Any]) @router.get("/identities/{agent_id}/wallets/{chain_id}/balance", response_model=dict[str, Any])
async def get_wallet_balance(agent_id: str, chain_id: int, manager: AgentIdentityManager = Depends(get_identity_manager)): async def get_wallet_balance(agent_id: str, chain_id: int, manager: AgentIdentityManager = Depends(get_identity_manager)) -> dict[str, Any]:
"""Get wallet balance for an agent on a specific chain""" """Get wallet balance for an agent on a specific chain"""
try: try:
balance = await manager.wallet_adapter.get_wallet_balance(agent_id, chain_id) balance = await manager.wallet_adapter.get_wallet_balance(agent_id, chain_id)
@@ -264,7 +264,7 @@ async def get_wallet_balance(agent_id: str, chain_id: int, manager: AgentIdentit
@router.post("/identities/{agent_id}/wallets/{chain_id}/transactions", response_model=dict[str, Any]) @router.post("/identities/{agent_id}/wallets/{chain_id}/transactions", response_model=dict[str, Any])
async def execute_wallet_transaction( async def execute_wallet_transaction(
agent_id: str, chain_id: int, request: dict[str, Any], manager: AgentIdentityManager = Depends(get_identity_manager) agent_id: str, chain_id: int, request: dict[str, Any], manager: AgentIdentityManager = Depends(get_identity_manager)
): ) -> dict[str, Any]:
"""Execute a transaction from agent wallet""" """Execute a transaction from agent wallet"""
try: try:
from decimal import Decimal from decimal import Decimal
@@ -284,7 +284,7 @@ async def get_wallet_transaction_history(
limit: int = Query(default=50, ge=1, le=1000), limit: int = Query(default=50, ge=1, le=1000),
offset: int = Query(default=0, ge=0), offset: int = Query(default=0, ge=0),
manager: AgentIdentityManager = Depends(get_identity_manager), manager: AgentIdentityManager = Depends(get_identity_manager),
): ) -> list[dict[str, Any]]:
"""Get transaction history for agent wallet""" """Get transaction history for agent wallet"""
try: try:
history = await manager.wallet_adapter.get_wallet_transaction_history(agent_id, chain_id, limit, offset) history = await manager.wallet_adapter.get_wallet_transaction_history(agent_id, chain_id, limit, offset)
@@ -294,7 +294,7 @@ async def get_wallet_transaction_history(
@router.get("/identities/{agent_id}/wallets", response_model=dict[str, Any]) @router.get("/identities/{agent_id}/wallets", response_model=dict[str, Any])
async def get_all_agent_wallets(agent_id: str, manager: AgentIdentityManager = Depends(get_identity_manager)): async def get_all_agent_wallets(agent_id: str, manager: AgentIdentityManager = Depends(get_identity_manager)) -> dict[str, Any]:
"""Get all wallets for an agent across all chains""" """Get all wallets for an agent across all chains"""
try: try:
wallets = await manager.wallet_adapter.get_all_agent_wallets(agent_id) wallets = await manager.wallet_adapter.get_all_agent_wallets(agent_id)
@@ -339,7 +339,7 @@ async def search_agent_identities(
limit: int = Query(default=50, ge=1, le=100), limit: int = Query(default=50, ge=1, le=100),
offset: int = Query(default=0, ge=0), offset: int = Query(default=0, ge=0),
manager: AgentIdentityManager = Depends(get_identity_manager), manager: AgentIdentityManager = Depends(get_identity_manager),
): ) -> dict[str, Any]:
"""Search agent identities with advanced filters""" """Search agent identities with advanced filters"""
try: try:
result = await manager.search_agent_identities( result = await manager.search_agent_identities(
@@ -357,7 +357,7 @@ async def search_agent_identities(
@router.post("/identities/{agent_id}/sync-reputation", response_model=dict[str, Any]) @router.post("/identities/{agent_id}/sync-reputation", response_model=dict[str, Any])
async def sync_agent_reputation(agent_id: str, manager: AgentIdentityManager = Depends(get_identity_manager)): async def sync_agent_reputation(agent_id: str, manager: AgentIdentityManager = Depends(get_identity_manager)) -> dict[str, Any]:
"""Sync agent reputation across all chains""" """Sync agent reputation across all chains"""
try: try:
result = await manager.sync_agent_reputation(agent_id) result = await manager.sync_agent_reputation(agent_id)
@@ -370,7 +370,7 @@ async def sync_agent_reputation(agent_id: str, manager: AgentIdentityManager = D
@router.get("/registry/health", response_model=dict[str, Any]) @router.get("/registry/health", response_model=dict[str, Any])
async def get_registry_health(manager: AgentIdentityManager = Depends(get_identity_manager)): async def get_registry_health(manager: AgentIdentityManager = Depends(get_identity_manager)) -> dict[str, Any]:
"""Get health status of the identity registry""" """Get health status of the identity registry"""
try: try:
result = await manager.get_registry_health() result = await manager.get_registry_health()
@@ -380,7 +380,7 @@ async def get_registry_health(manager: AgentIdentityManager = Depends(get_identi
@router.get("/registry/statistics", response_model=dict[str, Any]) @router.get("/registry/statistics", response_model=dict[str, Any])
async def get_registry_statistics(manager: AgentIdentityManager = Depends(get_identity_manager)): async def get_registry_statistics(manager: AgentIdentityManager = Depends(get_identity_manager)) -> dict[str, Any]:
"""Get comprehensive registry statistics""" """Get comprehensive registry statistics"""
try: try:
result = await manager.registry.get_registry_statistics() result = await manager.registry.get_registry_statistics()
@@ -390,7 +390,7 @@ async def get_registry_statistics(manager: AgentIdentityManager = Depends(get_id
@router.get("/chains/supported", response_model=list[dict[str, Any]]) @router.get("/chains/supported", response_model=list[dict[str, Any]])
async def get_supported_chains(manager: AgentIdentityManager = Depends(get_identity_manager)): async def get_supported_chains(manager: AgentIdentityManager = Depends(get_identity_manager)) -> list[dict[str, Any]]:
"""Get list of supported blockchains""" """Get list of supported blockchains"""
try: try:
chains = manager.wallet_adapter.get_supported_chains() chains = manager.wallet_adapter.get_supported_chains()
@@ -402,7 +402,7 @@ async def get_supported_chains(manager: AgentIdentityManager = Depends(get_ident
@router.post("/identities/{agent_id}/export", response_model=dict[str, Any]) @router.post("/identities/{agent_id}/export", response_model=dict[str, Any])
async def export_agent_identity( async def export_agent_identity(
agent_id: str, request: dict[str, Any] = None, manager: AgentIdentityManager = Depends(get_identity_manager) agent_id: str, request: dict[str, Any] = None, manager: AgentIdentityManager = Depends(get_identity_manager)
): ) -> dict[str, Any]:
"""Export agent identity data for backup or migration""" """Export agent identity data for backup or migration"""
try: try:
format_type = (request or {}).get("format", "json") format_type = (request or {}).get("format", "json")
@@ -413,7 +413,7 @@ async def export_agent_identity(
@router.post("/identities/import", response_model=dict[str, Any]) @router.post("/identities/import", response_model=dict[str, Any])
async def import_agent_identity(export_data: dict[str, Any], manager: AgentIdentityManager = Depends(get_identity_manager)): async def import_agent_identity(export_data: dict[str, Any], manager: AgentIdentityManager = Depends(get_identity_manager)) -> dict[str, Any]:
"""Import agent identity data from backup or migration""" """Import agent identity data from backup or migration"""
try: try:
result = await manager.import_agent_identity(export_data) result = await manager.import_agent_identity(export_data)
@@ -423,7 +423,7 @@ async def import_agent_identity(export_data: dict[str, Any], manager: AgentIdent
@router.post("/registry/cleanup-expired", response_model=dict[str, Any]) @router.post("/registry/cleanup-expired", response_model=dict[str, Any])
async def cleanup_expired_verifications(manager: AgentIdentityManager = Depends(get_identity_manager)): async def cleanup_expired_verifications(manager: AgentIdentityManager = Depends(get_identity_manager)) -> dict[str, Any]:
"""Clean up expired verification records""" """Clean up expired verification records"""
try: try:
cleaned_count = await manager.registry.cleanup_expired_verifications() cleaned_count = await manager.registry.cleanup_expired_verifications()
@@ -435,7 +435,7 @@ async def cleanup_expired_verifications(manager: AgentIdentityManager = Depends(
@router.post("/identities/batch-verify", response_model=list[dict[str, Any]]) @router.post("/identities/batch-verify", response_model=list[dict[str, Any]])
async def batch_verify_identities( async def batch_verify_identities(
verifications: list[dict[str, Any]], manager: AgentIdentityManager = Depends(get_identity_manager) verifications: list[dict[str, Any]], manager: AgentIdentityManager = Depends(get_identity_manager)
): ) -> list[dict[str, Any]]:
"""Batch verify multiple identities""" """Batch verify multiple identities"""
try: try:
results = await manager.registry.batch_verify_identities(verifications) results = await manager.registry.batch_verify_identities(verifications)
@@ -445,7 +445,7 @@ async def batch_verify_identities(
@router.get("/identities/{agent_id}/resolve/{chain_id}", response_model=dict[str, Any]) @router.get("/identities/{agent_id}/resolve/{chain_id}", response_model=dict[str, Any])
async def resolve_agent_identity(agent_id: str, chain_id: int, manager: AgentIdentityManager = Depends(get_identity_manager)): async def resolve_agent_identity(agent_id: str, chain_id: int, manager: AgentIdentityManager = Depends(get_identity_manager)) -> dict[str, Any]:
"""Resolve agent identity to chain-specific address""" """Resolve agent identity to chain-specific address"""
try: try:
address = await manager.registry.resolve_agent_identity(agent_id, chain_id) address = await manager.registry.resolve_agent_identity(agent_id, chain_id)
@@ -462,7 +462,7 @@ async def resolve_agent_identity(agent_id: str, chain_id: int, manager: AgentIde
@router.get("/address/{chain_address}/resolve/{chain_id}", response_model=dict[str, Any]) @router.get("/address/{chain_address}/resolve/{chain_id}", response_model=dict[str, Any])
async def resolve_address_to_agent( async def resolve_address_to_agent(
chain_address: str, chain_id: int, manager: AgentIdentityManager = Depends(get_identity_manager) chain_address: str, chain_id: int, manager: AgentIdentityManager = Depends(get_identity_manager)
): ) -> dict[str, Any]:
"""Resolve chain address back to agent ID""" """Resolve chain address back to agent ID"""
try: try:
agent_id = await manager.registry.resolve_agent_identity_by_address(chain_address, chain_id) agent_id = await manager.registry.resolve_agent_identity_by_address(chain_address, chain_id)

View File

@@ -37,7 +37,7 @@ async def create_deployment_config(
deployment_config: dict, deployment_config: dict,
session: Session = Depends(Annotated[Session, Depends(get_session)]), session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()), current_user: str = Depends(require_admin_key()),
): ) -> AgentDeploymentConfig:
"""Create deployment configuration for agent workflow""" """Create deployment configuration for agent workflow"""
try: try:
@@ -70,7 +70,7 @@ async def list_deployment_configs(
status: DeploymentStatus | None = None, status: DeploymentStatus | None = None,
session: Session = Depends(Annotated[Session, Depends(get_session)]), session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()), current_user: str = Depends(require_admin_key()),
): ) -> list[AgentDeploymentConfig]:
"""List deployment configurations with filtering""" """List deployment configurations with filtering"""
try: try:
@@ -103,7 +103,7 @@ async def get_deployment_config(
config_id: str, config_id: str,
session: Session = Depends(Annotated[Session, Depends(get_session)]), session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()), current_user: str = Depends(require_admin_key()),
): ) -> AgentDeploymentConfig:
"""Get specific deployment configuration""" """Get specific deployment configuration"""
try: try:
@@ -131,7 +131,7 @@ async def deploy_workflow(
target_environment: str = "production", target_environment: str = "production",
session: Session = Depends(Annotated[Session, Depends(get_session)]), session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()), current_user: str = Depends(require_admin_key()),
): ) -> dict[str, Any]:
"""Deploy agent workflow to target environment""" """Deploy agent workflow to target environment"""
try: try:
@@ -164,7 +164,7 @@ async def get_deployment_health(
config_id: str, config_id: str,
session: Session = Depends(Annotated[Session, Depends(get_session)]), session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()), current_user: str = Depends(require_admin_key()),
): ) -> dict[str, Any]:
"""Get health status of deployment""" """Get health status of deployment"""
try: try:
@@ -195,7 +195,7 @@ async def scale_deployment(
target_instances: int, target_instances: int,
session: Session = Depends(Annotated[Session, Depends(get_session)]), session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()), current_user: str = Depends(require_admin_key()),
): ) -> dict[str, Any]:
"""Scale deployment to target number of instances""" """Scale deployment to target number of instances"""
try: try:
@@ -228,7 +228,7 @@ async def rollback_deployment(
config_id: str, config_id: str,
session: Session = Depends(Annotated[Session, Depends(get_session)]), session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()), current_user: str = Depends(require_admin_key()),
): ) -> dict[str, Any]:
"""Rollback deployment to previous version""" """Rollback deployment to previous version"""
try: try:
@@ -261,7 +261,7 @@ async def list_deployment_instances(
status: DeploymentStatus | None = None, status: DeploymentStatus | None = None,
session: Session = Depends(Annotated[Session, Depends(get_session)]), session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()), current_user: str = Depends(require_admin_key()),
): ) -> list[AgentDeploymentInstance]:
"""List deployment instances with filtering""" """List deployment instances with filtering"""
try: try:
@@ -299,7 +299,7 @@ async def get_deployment_instance(
instance_id: str, instance_id: str,
session: Session = Depends(Annotated[Session, Depends(get_session)]), session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()), current_user: str = Depends(require_admin_key()),
): ) -> AgentDeploymentInstance:
"""Get specific deployment instance""" """Get specific deployment instance"""
try: try:
@@ -331,7 +331,7 @@ async def integrate_with_zk_system(
verification_level: VerificationLevel = VerificationLevel.BASIC, verification_level: VerificationLevel = VerificationLevel.BASIC,
session: Session = Depends(Annotated[Session, Depends(get_session)]), session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()), current_user: str = Depends(require_admin_key()),
): ) -> dict[str, Any]:
"""Integrate agent execution with ZK proof system""" """Integrate agent execution with ZK proof system"""
try: try:
@@ -365,7 +365,7 @@ async def get_deployment_metrics(
time_range: str = "1h", time_range: str = "1h",
session: Session = Depends(Annotated[Session, Depends(get_session)]), session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()), current_user: str = Depends(require_admin_key()),
): ) -> dict[str, Any]:
"""Get metrics for deployment over time range""" """Get metrics for deployment over time range"""
try: try:
@@ -397,7 +397,7 @@ async def deploy_to_production(
integration_config: dict | None = None, integration_config: dict | None = None,
session: Session = Depends(Annotated[Session, Depends(get_session)]), session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()), current_user: str = Depends(require_admin_key()),
): ) -> dict[str, Any]:
"""Deploy agent workflow to production with full integration""" """Deploy agent workflow to production with full integration"""
try: try:
@@ -427,7 +427,7 @@ async def deploy_to_production(
@router.get("/production/dashboard") @router.get("/production/dashboard")
async def get_production_dashboard( async def get_production_dashboard(
session: Session = Depends(Annotated[Session, Depends(get_session)]), current_user: str = Depends(require_admin_key()) session: Session = Depends(Annotated[Session, Depends(get_session)]), current_user: str = Depends(require_admin_key())
): ) -> dict[str, Any]:
"""Get comprehensive production dashboard data""" """Get comprehensive production dashboard data"""
try: try:
@@ -481,7 +481,7 @@ async def get_production_dashboard(
@router.get("/production/health") @router.get("/production/health")
async def get_production_health( async def get_production_health(
session: Session = Depends(Annotated[Session, Depends(get_session)]), current_user: str = Depends(require_admin_key()) session: Session = Depends(Annotated[Session, Depends(get_session)]), current_user: str = Depends(require_admin_key())
): ) -> dict[str, Any]:
"""Get overall production health status""" """Get overall production health status"""
try: try:
@@ -553,7 +553,7 @@ async def get_production_alerts(
severity: str | None = None, severity: str | None = None,
limit: int = 50, limit: int = 50,
current_user: str = Depends(require_admin_key()), current_user: str = Depends(require_admin_key()),
): ) -> dict[str, Any]:
"""Get production alerts and notifications""" """Get production alerts and notifications"""
try: try:

View File

@@ -8,6 +8,7 @@ Provides REST API endpoints for agent workflow management and execution
""" """
from datetime import datetime, UTC from datetime import datetime, UTC
from typing import Any
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException
@@ -38,7 +39,7 @@ async def create_workflow(
workflow_data: AgentWorkflowCreate, workflow_data: AgentWorkflowCreate,
session: Session = Depends(Annotated[Session, Depends(get_session)]), session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()), current_user: str = Depends(require_admin_key()),
): ) -> AIAgentWorkflow:
"""Create a new AI agent workflow""" """Create a new AI agent workflow"""
try: try:
@@ -63,7 +64,7 @@ async def list_workflows(
tags: list[str] | None = None, tags: list[str] | None = None,
session: Session = Depends(Annotated[Session, Depends(get_session)]), session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()), current_user: str = Depends(require_admin_key()),
): ) -> list[AIAgentWorkflow]:
"""List agent workflows with filtering""" """List agent workflows with filtering"""
try: try:
@@ -97,7 +98,7 @@ async def get_workflow(
workflow_id: str, workflow_id: str,
session: Session = Depends(Annotated[Session, Depends(get_session)]), session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()), current_user: str = Depends(require_admin_key()),
): ) -> AIAgentWorkflow:
"""Get a specific agent workflow""" """Get a specific agent workflow"""
try: try:
@@ -124,7 +125,7 @@ async def update_workflow(
workflow_data: AgentWorkflowUpdate, workflow_data: AgentWorkflowUpdate,
session: Session = Depends(Annotated[Session, Depends(get_session)]), session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()), current_user: str = Depends(require_admin_key()),
): ) -> AIAgentWorkflow:
"""Update an agent workflow""" """Update an agent workflow"""
try: try:
@@ -160,7 +161,7 @@ async def delete_workflow(
workflow_id: str, workflow_id: str,
session: Session = Depends(Annotated[Session, Depends(get_session)]), session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()), current_user: str = Depends(require_admin_key()),
): ) -> dict[str, str]:
"""Delete an agent workflow""" """Delete an agent workflow"""
try: try:
@@ -192,7 +193,7 @@ async def execute_workflow(
background_tasks: BackgroundTasks, background_tasks: BackgroundTasks,
session: Session = Depends(Annotated[Session, Depends(get_session)]), session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()), current_user: str = Depends(require_admin_key()),
): ) -> AgentExecutionResponse:
"""Execute an AI agent workflow""" """Execute an AI agent workflow"""
try: try:
@@ -236,7 +237,7 @@ async def get_execution_status(
execution_id: str, execution_id: str,
session: Session = Depends(Annotated[Session, Depends(get_session)]), session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()), current_user: str = Depends(require_admin_key()),
): ) -> AgentExecutionStatus:
"""Get execution status""" """Get execution status"""
try: try:
@@ -270,7 +271,7 @@ async def list_executions(
offset: int = 0, offset: int = 0,
session: Session = Depends(Annotated[Session, Depends(get_session)]), session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()), current_user: str = Depends(require_admin_key()),
): ) -> list[AgentExecutionStatus]:
"""List agent executions with filtering""" """List agent executions with filtering"""
try: try:
@@ -328,7 +329,7 @@ async def cancel_execution(
execution_id: str, execution_id: str,
session: Session = Depends(Annotated[Session, Depends(get_session)]), session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()), current_user: str = Depends(require_admin_key()),
): ) -> dict[str, str]:
"""Cancel an ongoing execution""" """Cancel an ongoing execution"""
try: try:
@@ -368,7 +369,7 @@ async def get_execution_logs(
execution_id: str, execution_id: str,
session: Session = Depends(Annotated[Session, Depends(get_session)]), session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()), current_user: str = Depends(require_admin_key()),
): ) -> dict[str, Any]:
"""Get execution logs""" """Get execution logs"""
try: try:
@@ -422,7 +423,7 @@ async def get_execution_logs(
@router.get("/test") @router.get("/test")
async def test_endpoint(): async def test_endpoint() -> dict[str, str]:
"""Test endpoint to verify router is working""" """Test endpoint to verify router is working"""
return {"message": "Agent router is working", "timestamp": datetime.now(datetime.UTC).isoformat()} return {"message": "Agent router is working", "timestamp": datetime.now(datetime.UTC).isoformat()}
@@ -432,7 +433,7 @@ async def create_agent_network(
network_data: dict, network_data: dict,
session: Session = Depends(Annotated[Session, Depends(get_session)]), session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()), current_user: str = Depends(require_admin_key()),
): ) -> dict[str, Any]:
"""Create a new agent network for collaborative processing""" """Create a new agent network for collaborative processing"""
try: try:
@@ -472,7 +473,7 @@ async def get_execution_receipt(
execution_id: str, execution_id: str,
session: Session = Depends(Annotated[Session, Depends(get_session)]), session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()), current_user: str = Depends(require_admin_key()),
): ) -> dict[str, Any]:
"""Get verifiable receipt for completed execution""" """Get verifiable receipt for completed execution"""
try: try:

View File

@@ -41,7 +41,7 @@ async def create_security_policy(
policy_rules: dict, policy_rules: dict,
session: Session = Depends(Annotated[Session, Depends(get_session)]), session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()), current_user: str = Depends(require_admin_key()),
): ) -> AgentSecurityPolicy:
"""Create a new security policy""" """Create a new security policy"""
try: try:
@@ -64,7 +64,7 @@ async def list_security_policies(
is_active: bool | None = None, is_active: bool | None = None,
session: Session = Depends(Annotated[Session, Depends(get_session)]), session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()), current_user: str = Depends(require_admin_key()),
): ) -> list[AgentSecurityPolicy]:
"""List security policies with filtering""" """List security policies with filtering"""
try: try:
@@ -89,7 +89,7 @@ async def get_security_policy(
policy_id: str, policy_id: str,
session: Session = Depends(Annotated[Session, Depends(get_session)]), session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()), current_user: str = Depends(require_admin_key()),
): ) -> AgentSecurityPolicy:
"""Get a specific security policy""" """Get a specific security policy"""
try: try:
@@ -112,7 +112,7 @@ async def update_security_policy(
policy_updates: dict, policy_updates: dict,
session: Session = Depends(Annotated[Session, Depends(get_session)]), session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()), current_user: str = Depends(require_admin_key()),
): ) -> AgentSecurityPolicy:
"""Update a security policy""" """Update a security policy"""
try: try:
@@ -154,7 +154,7 @@ async def delete_security_policy(
policy_id: str, policy_id: str,
session: Session = Depends(Annotated[Session, Depends(get_session)]), session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()), current_user: str = Depends(require_admin_key()),
): ) -> dict[str, str]:
"""Delete a security policy""" """Delete a security policy"""
try: try:
@@ -190,7 +190,7 @@ async def validate_workflow_security(
workflow_id: str, workflow_id: str,
session: Session = Depends(Annotated[Session, Depends(get_session)]), session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()), current_user: str = Depends(require_admin_key()),
): ) -> dict[str, Any]:
"""Validate workflow security requirements""" """Validate workflow security requirements"""
try: try:
@@ -228,7 +228,7 @@ async def list_audit_logs(
offset: int = 0, offset: int = 0,
session: Session = Depends(Annotated[Session, Depends(get_session)]), session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()), current_user: str = Depends(require_admin_key()),
): ) -> list[AgentAuditLog]:
"""List audit logs with filtering""" """List audit logs with filtering"""
try: try:
@@ -271,7 +271,7 @@ async def get_audit_log(
audit_id: str, audit_id: str,
session: Session = Depends(Annotated[Session, Depends(get_session)]), session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()), current_user: str = Depends(require_admin_key()),
): ) -> AgentAuditLog:
"""Get a specific audit log entry""" """Get a specific audit log entry"""
try: try:
@@ -299,7 +299,7 @@ async def list_trust_scores(
offset: int = 0, offset: int = 0,
session: Session = Depends(Annotated[Session, Depends(get_session)]), session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()), current_user: str = Depends(require_admin_key()),
): ) -> list[AgentTrustScore]:
"""List trust scores with filtering""" """List trust scores with filtering"""
try: try:
@@ -335,7 +335,7 @@ async def get_trust_score(
entity_id: str, entity_id: str,
session: Session = Depends(Annotated[Session, Depends(get_session)]), session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()), current_user: str = Depends(require_admin_key()),
): ) -> AgentTrustScore:
"""Get trust score for specific entity""" """Get trust score for specific entity"""
try: try:
@@ -369,7 +369,7 @@ async def update_trust_score(
policy_violation: bool = False, policy_violation: bool = False,
session: Session = Depends(Annotated[Session, Depends(get_session)]), session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()), current_user: str = Depends(require_admin_key()),
): ) -> AgentTrustScore:
"""Update trust score based on execution results""" """Update trust score based on execution results"""
try: try:
@@ -415,7 +415,7 @@ async def create_sandbox(
workflow_requirements: dict | None = None, workflow_requirements: dict | None = None,
session: Session = Depends(Annotated[Session, Depends(get_session)]), session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()), current_user: str = Depends(require_admin_key()),
): ) -> dict[str, Any]:
"""Create sandbox environment for agent execution""" """Create sandbox environment for agent execution"""
try: try:
@@ -451,7 +451,7 @@ async def monitor_sandbox(
execution_id: str, execution_id: str,
session: Session = Depends(Annotated[Session, Depends(get_session)]), session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()), current_user: str = Depends(require_admin_key()),
): ) -> dict[str, Any]:
"""Monitor sandbox execution for security violations""" """Monitor sandbox execution for security violations"""
try: try:
@@ -470,7 +470,7 @@ async def cleanup_sandbox(
execution_id: str, execution_id: str,
session: Session = Depends(Annotated[Session, Depends(get_session)]), session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()), current_user: str = Depends(require_admin_key()),
): ) -> dict[str, Any]:
"""Clean up sandbox environment after execution""" """Clean up sandbox environment after execution"""
try: try:
@@ -500,7 +500,7 @@ async def monitor_execution_security(
workflow_id: str, workflow_id: str,
session: Session = Depends(Annotated[Session, Depends(get_session)]), session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()), current_user: str = Depends(require_admin_key()),
): ) -> dict[str, Any]:
"""Monitor execution for security violations""" """Monitor execution for security violations"""
try: try:
@@ -517,7 +517,7 @@ async def monitor_execution_security(
@router.get("/security-dashboard") @router.get("/security-dashboard")
async def get_security_dashboard( async def get_security_dashboard(
session: Session = Depends(Annotated[Session, Depends(get_session)]), current_user: str = Depends(require_admin_key()) session: Session = Depends(Annotated[Session, Depends(get_session)]), current_user: str = Depends(require_admin_key())
): ) -> dict[str, Any]:
"""Get comprehensive security dashboard data""" """Get comprehensive security dashboard data"""
try: try:
@@ -572,7 +572,7 @@ async def get_security_dashboard(
@router.get("/security-stats") @router.get("/security-stats")
async def get_security_statistics( async def get_security_statistics(
session: Session = Depends(Annotated[Session, Depends(get_session)]), current_user: str = Depends(require_admin_key()) session: Session = Depends(Annotated[Session, Depends(get_session)]), current_user: str = Depends(require_admin_key())
): ) -> dict[str, Any]:
"""Get security statistics and metrics""" """Get security statistics and metrics"""
try: try:

View File

@@ -1,5 +1,7 @@
from __future__ import annotations from __future__ import annotations
from typing import Any
from fastapi import APIRouter from fastapi import APIRouter
from aitbc import get_logger, AITBCHTTPClient, NetworkError from aitbc import get_logger, AITBCHTTPClient, NetworkError
@@ -11,7 +13,7 @@ router = APIRouter(tags=["blockchain"])
@router.get("/status") @router.get("/status")
async def blockchain_status(): async def blockchain_status() -> dict[str, Any]:
"""Get blockchain status.""" """Get blockchain status."""
try: try:
from ..config import settings from ..config import settings
@@ -32,7 +34,7 @@ async def blockchain_status():
@router.get("/sync-status") @router.get("/sync-status")
async def blockchain_sync_status(): async def blockchain_sync_status() -> dict[str, Any]:
"""Get blockchain synchronization status.""" """Get blockchain synchronization status."""
try: try:
from ..config import settings from ..config import settings

View File

@@ -47,7 +47,7 @@ class BountyCreateRequest(BaseModel):
difficulty: Optional[str] = Field(default=None) difficulty: Optional[str] = Field(default=None)
@validator('deadline') @validator('deadline')
def validate_deadline(cls, v): def validate_deadline(cls, v: datetime) -> datetime:
if v <= datetime.now(datetime.UTC): if v <= datetime.now(datetime.UTC):
raise ValueError('Deadline must be in the future') raise ValueError('Deadline must be in the future')
if v > datetime.now(datetime.UTC) + timedelta(days=365): if v > datetime.now(datetime.UTC) + timedelta(days=365):
@@ -55,7 +55,7 @@ class BountyCreateRequest(BaseModel):
return v return v
@validator('reward_amount') @validator('reward_amount')
def validate_reward_amount(cls, v, values): def validate_reward_amount(cls, v: float, values: dict[str, Any]) -> float:
tier = values.get('tier', BountyTier.BRONZE) tier = values.get('tier', BountyTier.BRONZE)
tier_minimums = { tier_minimums = {
BountyTier.BRONZE: 100.0, BountyTier.BRONZE: 100.0,
@@ -184,7 +184,7 @@ async def create_bounty(
bounty_service: BountyService = Depends(get_bounty_service), bounty_service: BountyService = Depends(get_bounty_service),
blockchain_service: BlockchainService = Depends(get_blockchain_service), blockchain_service: BlockchainService = Depends(get_blockchain_service),
current_user: dict = Depends(get_current_user) current_user: dict = Depends(get_current_user)
): ) -> BountyResponse:
"""Create a new bounty""" """Create a new bounty"""
try: try:
logger.info(f"Creating bounty: {request.title} by user {current_user['address']}") logger.info(f"Creating bounty: {request.title} by user {current_user['address']}")
@@ -215,7 +215,7 @@ async def get_bounties(
session: Session = Depends(get_session), session: Session = Depends(get_session),
filters: BountyFilterRequest = Depends(), filters: BountyFilterRequest = Depends(),
bounty_service: BountyService = Depends(get_bounty_service) bounty_service: BountyService = Depends(get_bounty_service)
): ) -> List[BountyResponse]:
"""Get filtered list of bounties""" """Get filtered list of bounties"""
try: try:
bounties = await bounty_service.get_bounties( bounties = await bounty_service.get_bounties(
@@ -244,7 +244,7 @@ async def get_bounty(
bounty_id: str, bounty_id: str,
session: Session = Depends(get_session), session: Session = Depends(get_session),
bounty_service: BountyService = Depends(get_bounty_service) bounty_service: BountyService = Depends(get_bounty_service)
): ) -> BountyResponse:
"""Get bounty details""" """Get bounty details"""
try: try:
bounty = await bounty_service.get_bounty(bounty_id) bounty = await bounty_service.get_bounty(bounty_id)
@@ -268,7 +268,7 @@ async def submit_bounty_solution(
bounty_service: BountyService = Depends(get_bounty_service), bounty_service: BountyService = Depends(get_bounty_service),
blockchain_service: BlockchainService = Depends(get_blockchain_service), blockchain_service: BlockchainService = Depends(get_blockchain_service),
current_user: dict = Depends(get_current_user) current_user: dict = Depends(get_current_user)
): ) -> BountySubmissionResponse:
"""Submit a solution to a bounty""" """Submit a solution to a bounty"""
try: try:
logger.info(f"Submitting solution for bounty {bounty_id} by {current_user['address']}") logger.info(f"Submitting solution for bounty {bounty_id} by {current_user['address']}")
@@ -316,7 +316,7 @@ async def get_bounty_submissions(
session: Session = Depends(get_session), session: Session = Depends(get_session),
bounty_service: BountyService = Depends(get_bounty_service), bounty_service: BountyService = Depends(get_bounty_service),
current_user: dict = Depends(get_current_user) current_user: dict = Depends(get_current_user)
): ) -> List[BountySubmissionResponse]:
"""Get all submissions for a bounty""" """Get all submissions for a bounty"""
try: try:
# Check if user is bounty creator or has permission # Check if user is bounty creator or has permission
@@ -347,7 +347,7 @@ async def verify_bounty_submission(
bounty_service: BountyService = Depends(get_bounty_service), bounty_service: BountyService = Depends(get_bounty_service),
blockchain_service: BlockchainService = Depends(get_blockchain_service), blockchain_service: BlockchainService = Depends(get_blockchain_service),
current_user: dict = Depends(get_current_user) current_user: dict = Depends(get_current_user)
): ) -> Dict[str, str]:
"""Verify a bounty submission (oracle/admin only)""" """Verify a bounty submission (oracle/admin only)"""
try: try:
# Check permissions # Check permissions
@@ -387,7 +387,7 @@ async def dispute_bounty_submission(
bounty_service: BountyService = Depends(get_bounty_service), bounty_service: BountyService = Depends(get_bounty_service),
blockchain_service: BlockchainService = Depends(get_blockchain_service), blockchain_service: BlockchainService = Depends(get_blockchain_service),
current_user: dict = Depends(get_current_user) current_user: dict = Depends(get_current_user)
): ) -> Dict[str, str]:
"""Dispute a bounty submission""" """Dispute a bounty submission"""
try: try:
# Create dispute # Create dispute
@@ -421,7 +421,7 @@ async def get_my_created_bounties(
session: Session = Depends(get_session), session: Session = Depends(get_session),
bounty_service: BountyService = Depends(get_bounty_service), bounty_service: BountyService = Depends(get_bounty_service),
current_user: dict = Depends(get_current_user) current_user: dict = Depends(get_current_user)
): ) -> List[BountyResponse]:
"""Get bounties created by the current user""" """Get bounties created by the current user"""
try: try:
bounties = await bounty_service.get_user_created_bounties( bounties = await bounty_service.get_user_created_bounties(
@@ -445,7 +445,7 @@ async def get_my_submissions(
session: Session = Depends(get_session), session: Session = Depends(get_session),
bounty_service: BountyService = Depends(get_bounty_service), bounty_service: BountyService = Depends(get_bounty_service),
current_user: dict = Depends(get_current_user) current_user: dict = Depends(get_current_user)
): ) -> List[BountySubmissionResponse]:
"""Get submissions made by the current user""" """Get submissions made by the current user"""
try: try:
submissions = await bounty_service.get_user_submissions( submissions = await bounty_service.get_user_submissions(
@@ -467,7 +467,7 @@ async def get_bounty_leaderboard(
limit: int = Field(default=50, ge=1, le=100), limit: int = Field(default=50, ge=1, le=100),
session: Session = Depends(get_session), session: Session = Depends(get_session),
bounty_service: BountyService = Depends(get_bounty_service) bounty_service: BountyService = Depends(get_bounty_service)
): ) -> Dict[str, Any]:
"""Get bounty leaderboard""" """Get bounty leaderboard"""
try: try:
leaderboard = await bounty_service.get_leaderboard( leaderboard = await bounty_service.get_leaderboard(
@@ -486,7 +486,7 @@ async def get_bounty_stats(
period: str = Field(default="monthly", regex="^(daily|weekly|monthly)$"), period: str = Field(default="monthly", regex="^(daily|weekly|monthly)$"),
session: Session = Depends(get_session), session: Session = Depends(get_session),
bounty_service: BountyService = Depends(get_bounty_service) bounty_service: BountyService = Depends(get_bounty_service)
): ) -> BountyStatsResponse:
"""Get bounty statistics""" """Get bounty statistics"""
try: try:
stats = await bounty_service.get_bounty_stats(period=period) stats = await bounty_service.get_bounty_stats(period=period)
@@ -505,7 +505,7 @@ async def expire_bounty(
bounty_service: BountyService = Depends(get_bounty_service), bounty_service: BountyService = Depends(get_bounty_service),
blockchain_service: BlockchainService = Depends(get_blockchain_service), blockchain_service: BlockchainService = Depends(get_blockchain_service),
current_user: dict = Depends(get_current_user) current_user: dict = Depends(get_current_user)
): ) -> Dict[str, str]:
"""Expire a bounty (creator only)""" """Expire a bounty (creator only)"""
try: try:
# Check if user is bounty creator # Check if user is bounty creator
@@ -543,7 +543,7 @@ async def expire_bounty(
async def get_bounty_categories( async def get_bounty_categories(
session: Session = Depends(get_session), session: Session = Depends(get_session),
bounty_service: BountyService = Depends(get_bounty_service) bounty_service: BountyService = Depends(get_bounty_service)
): ) -> Dict[str, Any]:
"""Get all bounty categories""" """Get all bounty categories"""
try: try:
categories = await bounty_service.get_categories() categories = await bounty_service.get_categories()
@@ -558,7 +558,7 @@ async def get_bounty_tags(
limit: int = Field(default=100, ge=1, le=500), limit: int = Field(default=100, ge=1, le=500),
session: Session = Depends(get_session), session: Session = Depends(get_session),
bounty_service: BountyService = Depends(get_bounty_service) bounty_service: BountyService = Depends(get_bounty_service)
): ) -> Dict[str, Any]:
"""Get popular bounty tags""" """Get popular bounty tags"""
try: try:
tags = await bounty_service.get_popular_tags(limit=limit) tags = await bounty_service.get_popular_tags(limit=limit)
@@ -575,7 +575,7 @@ async def search_bounties(
limit: int = Field(default=20, ge=1, le=100), limit: int = Field(default=20, ge=1, le=100),
session: Session = Depends(get_session), session: Session = Depends(get_session),
bounty_service: BountyService = Depends(get_bounty_service) bounty_service: BountyService = Depends(get_bounty_service)
): ) -> List[BountyResponse]:
"""Search bounties by text""" """Search bounties by text"""
try: try:
bounties = await bounty_service.search_bounties( bounties = await bounty_service.search_bounties(

View File

@@ -2,6 +2,8 @@
Cache monitoring and management endpoints Cache monitoring and management endpoints
""" """
from typing import Any
from fastapi import APIRouter, Depends, HTTPException, Request from fastapi import APIRouter, Depends, HTTPException, Request
from slowapi import Limiter from slowapi import Limiter
from slowapi.util import get_remote_address from slowapi.util import get_remote_address
@@ -20,7 +22,7 @@ router = APIRouter(prefix="/cache", tags=["cache-management"])
@router.get("/stats", summary="Get cache statistics") @router.get("/stats", summary="Get cache statistics")
@limiter.limit(lambda: settings.rate_limit_admin_stats) @limiter.limit(lambda: settings.rate_limit_admin_stats)
async def get_cache_statistics(request: Request, admin_key: str = Depends(require_admin_key())): async def get_cache_statistics(request: Request, admin_key: str = Depends(require_admin_key())) -> dict[str, Any]:
"""Get cache performance statistics""" """Get cache performance statistics"""
try: try:
stats = get_cache_stats() stats = get_cache_stats()
@@ -32,7 +34,7 @@ async def get_cache_statistics(request: Request, admin_key: str = Depends(requir
@router.post("/clear", summary="Clear cache entries") @router.post("/clear", summary="Clear cache entries")
@limiter.limit(lambda: settings.rate_limit_admin_stats) @limiter.limit(lambda: settings.rate_limit_admin_stats)
async def clear_cache_entries(request: Request, pattern: str = None, admin_key: str = Depends(require_admin_key())): async def clear_cache_entries(request: Request, pattern: str = None, admin_key: str = Depends(require_admin_key())) -> dict[str, Any]:
"""Clear cache entries (all or matching pattern)""" """Clear cache entries (all or matching pattern)"""
try: try:
result = clear_cache(pattern) result = clear_cache(pattern)
@@ -45,7 +47,7 @@ async def clear_cache_entries(request: Request, pattern: str = None, admin_key:
@router.post("/warm", summary="Warm up cache") @router.post("/warm", summary="Warm up cache")
@limiter.limit(lambda: settings.rate_limit_admin_stats) @limiter.limit(lambda: settings.rate_limit_admin_stats)
async def warm_up_cache(request: Request, admin_key: str = Depends(require_admin_key())): async def warm_up_cache(request: Request, admin_key: str = Depends(require_admin_key())) -> dict[str, Any]:
"""Trigger cache warming for common queries""" """Trigger cache warming for common queries"""
try: try:
result = warm_cache() result = warm_cache()
@@ -58,7 +60,7 @@ async def warm_up_cache(request: Request, admin_key: str = Depends(require_admin
@router.get("/health", summary="Get cache health status") @router.get("/health", summary="Get cache health status")
@limiter.limit(lambda: settings.rate_limit_admin_stats) @limiter.limit(lambda: settings.rate_limit_admin_stats)
async def cache_health_check(request: Request, admin_key: str = Depends(require_admin_key())): async def cache_health_check(request: Request, admin_key: str = Depends(require_admin_key())) -> dict[str, Any]:
"""Get detailed cache health information""" """Get detailed cache health information"""
try: try:
from ..utils.cache import cache_manager from ..utils.cache import cache_manager

View File

@@ -84,7 +84,7 @@ class HackathonCreateRequest(BaseModel):
# Endpoints - Developer Ecosystem # Endpoints - Developer Ecosystem
@router.post("/developers", response_model=DeveloperProfile) @router.post("/developers", response_model=DeveloperProfile)
async def create_developer_profile(request: DeveloperProfileCreate, session: Annotated[Session, Depends(get_session)]): async def create_developer_profile(request: DeveloperProfileCreate, session: Annotated[Session, Depends(get_session)]) -> DeveloperProfile:
"""Register a new developer in the OpenClaw ecosystem""" """Register a new developer in the OpenClaw ecosystem"""
service = DeveloperEcosystemService(session) service = DeveloperEcosystemService(session)
try: try:
@@ -98,7 +98,7 @@ async def create_developer_profile(request: DeveloperProfileCreate, session: Ann
@router.get("/developers/{developer_id}", response_model=DeveloperProfile) @router.get("/developers/{developer_id}", response_model=DeveloperProfile)
async def get_developer_profile(developer_id: str, session: Annotated[Session, Depends(get_session)]): async def get_developer_profile(developer_id: str, session: Annotated[Session, Depends(get_session)]) -> DeveloperProfile:
"""Get a developer's profile and reputation""" """Get a developer's profile and reputation"""
service = DeveloperEcosystemService(session) service = DeveloperEcosystemService(session)
profile = await service.get_developer_profile(developer_id) profile = await service.get_developer_profile(developer_id)
@@ -108,7 +108,7 @@ async def get_developer_profile(developer_id: str, session: Annotated[Session, D
@router.get("/sdk/latest") @router.get("/sdk/latest")
async def get_latest_sdk(session: Annotated[Session, Depends(get_session)]): async def get_latest_sdk(session: Annotated[Session, Depends(get_session)]) -> dict[str, Any]:
"""Get information about the latest OpenClaw SDK releases""" """Get information about the latest OpenClaw SDK releases"""
service = DeveloperEcosystemService(session) service = DeveloperEcosystemService(session)
return await service.get_sdk_release_info() return await service.get_sdk_release_info()
@@ -116,7 +116,7 @@ async def get_latest_sdk(session: Annotated[Session, Depends(get_session)]):
# Endpoints - Marketplace Solutions # Endpoints - Marketplace Solutions
@router.post("/solutions/publish", response_model=AgentSolution) @router.post("/solutions/publish", response_model=AgentSolution)
async def publish_solution(request: SolutionPublishRequest, session: Annotated[Session, Depends(get_session)]): async def publish_solution(request: SolutionPublishRequest, session: Annotated[Session, Depends(get_session)]) -> AgentSolution:
"""Publish a new third-party agent solution to the marketplace""" """Publish a new third-party agent solution to the marketplace"""
service = ThirdPartySolutionService(session) service = ThirdPartySolutionService(session)
try: try:
@@ -131,7 +131,8 @@ async def publish_solution(request: SolutionPublishRequest, session: Annotated[S
async def list_solutions( async def list_solutions(
category: str | None = None, category: str | None = None,
limit: int = 50, limit: int = 50,
): session: Annotated[Session, Depends(get_session)] = Depends(get_session),
) -> list[AgentSolution]:
"""List available third-party agent solutions""" """List available third-party agent solutions"""
service = ThirdPartySolutionService(session) service = ThirdPartySolutionService(session)
return await service.list_published_solutions(category, limit) return await service.list_published_solutions(category, limit)
@@ -140,7 +141,7 @@ async def list_solutions(
@router.post("/solutions/{solution_id}/purchase") @router.post("/solutions/{solution_id}/purchase")
async def purchase_solution( async def purchase_solution(
solution_id: str, session: Annotated[Session, Depends(get_session)], buyer_id: str = Body(embed=True) solution_id: str, session: Annotated[Session, Depends(get_session)], buyer_id: str = Body(embed=True)
): ) -> dict[str, Any]:
"""Purchase or install a third-party solution""" """Purchase or install a third-party solution"""
service = ThirdPartySolutionService(session) service = ThirdPartySolutionService(session)
try: try:
@@ -157,7 +158,8 @@ async def purchase_solution(
async def propose_innovation_lab( async def propose_innovation_lab(
researcher_id: str = Query(...), researcher_id: str = Query(...),
request: LabProposalRequest = Body(...), request: LabProposalRequest = Body(...),
): session: Annotated[Session, Depends(get_session)] = Depends(get_session),
) -> InnovationLab:
"""Propose a new agent innovation lab or research program""" """Propose a new agent innovation lab or research program"""
service = InnovationLabService(session) service = InnovationLabService(session)
try: try:
@@ -170,7 +172,7 @@ async def propose_innovation_lab(
@router.post("/labs/{lab_id}/join") @router.post("/labs/{lab_id}/join")
async def join_innovation_lab( async def join_innovation_lab(
lab_id: str, session: Annotated[Session, Depends(get_session)], developer_id: str = Body(embed=True) lab_id: str, session: Annotated[Session, Depends(get_session)], developer_id: str = Body(embed=True)
): ) -> InnovationLab:
"""Join an active innovation lab""" """Join an active innovation lab"""
service = InnovationLabService(session) service = InnovationLabService(session)
try: try:
@@ -183,7 +185,7 @@ async def join_innovation_lab(
@router.post("/labs/{lab_id}/fund") @router.post("/labs/{lab_id}/fund")
async def fund_innovation_lab( async def fund_innovation_lab(
lab_id: str, session: Annotated[Session, Depends(get_session)], amount: float = Body(embed=True) lab_id: str, session: Annotated[Session, Depends(get_session)], amount: float = Body(embed=True)
): ) -> InnovationLab:
"""Provide funding to a proposed innovation lab""" """Provide funding to a proposed innovation lab"""
service = InnovationLabService(session) service = InnovationLabService(session)
try: try:
@@ -198,7 +200,8 @@ async def fund_innovation_lab(
async def create_community_post( async def create_community_post(
author_id: str = Query(...), author_id: str = Query(...),
request: PostCreateRequest = Body(...), request: PostCreateRequest = Body(...),
): session: Annotated[Session, Depends(get_session)] = Depends(get_session),
) -> CommunityPost:
"""Create a new post in the community forum""" """Create a new post in the community forum"""
service = CommunityPlatformService(session) service = CommunityPlatformService(session)
try: try:
@@ -212,14 +215,15 @@ async def create_community_post(
async def get_community_feed( async def get_community_feed(
category: str | None = None, category: str | None = None,
limit: int = 20, limit: int = 20,
): session: Annotated[Session, Depends(get_session)] = Depends(get_session),
) -> list[CommunityPost]:
"""Get the latest community posts and discussions""" """Get the latest community posts and discussions"""
service = CommunityPlatformService(session) service = CommunityPlatformService(session)
return await service.get_feed(category, limit) return await service.get_feed(category, limit)
@router.post("/platform/posts/{post_id}/upvote") @router.post("/platform/posts/{post_id}/upvote")
async def upvote_community_post(post_id: str, session: Annotated[Session, Depends(get_session)]): async def upvote_community_post(post_id: str, session: Annotated[Session, Depends(get_session)]) -> CommunityPost:
"""Upvote a community post (rewards author reputation)""" """Upvote a community post (rewards author reputation)"""
service = CommunityPlatformService(session) service = CommunityPlatformService(session)
try: try:
@@ -234,7 +238,8 @@ async def upvote_community_post(post_id: str, session: Annotated[Session, Depend
async def create_hackathon( async def create_hackathon(
organizer_id: str = Query(...), organizer_id: str = Query(...),
request: HackathonCreateRequest = Body(...), request: HackathonCreateRequest = Body(...),
): session: Annotated[Session, Depends(get_session)] = Depends(get_session),
) -> Hackathon:
"""Create a new agent innovation hackathon (requires high reputation)""" """Create a new agent innovation hackathon (requires high reputation)"""
service = CommunityPlatformService(session) service = CommunityPlatformService(session)
try: try:
@@ -249,7 +254,7 @@ async def create_hackathon(
@router.post("/hackathons/{hackathon_id}/register") @router.post("/hackathons/{hackathon_id}/register")
async def register_for_hackathon( async def register_for_hackathon(
hackathon_id: str, session: Annotated[Session, Depends(get_session)], developer_id: str = Body(embed=True) hackathon_id: str, session: Annotated[Session, Depends(get_session)], developer_id: str = Body(embed=True)
): ) -> Hackathon:
"""Register for an upcoming or ongoing hackathon""" """Register for an upcoming or ongoing hackathon"""
service = CommunityPlatformService(session) service = CommunityPlatformService(session)
try: try:

View File

@@ -3,6 +3,11 @@ API endpoints for confidential transactions
""" """
from datetime import datetime, UTC from datetime import datetime, UTC
from typing import Any
from aitbc import get_logger
logger = get_logger(__name__)
from fastapi import APIRouter, Depends, HTTPException from fastapi import APIRouter, Depends, HTTPException
from fastapi.security import HTTPBearer from fastapi.security import HTTPBearer
@@ -74,7 +79,7 @@ def get_access_controller() -> AccessController:
@router.post("/transactions", response_model=ConfidentialTransactionView) @router.post("/transactions", response_model=ConfidentialTransactionView)
async def create_confidential_transaction(request: ConfidentialTransactionCreate, api_key: str = Depends(get_api_key)): async def create_confidential_transaction(request: ConfidentialTransactionCreate, api_key: str = Depends(get_api_key)) -> ConfidentialTransactionView:
"""Create a new confidential transaction with optional encryption""" """Create a new confidential transaction with optional encryption"""
try: try:
# Generate transaction ID # Generate transaction ID
@@ -144,7 +149,7 @@ async def create_confidential_transaction(request: ConfidentialTransactionCreate
@router.get("/transactions/{transaction_id}", response_model=ConfidentialTransactionView) @router.get("/transactions/{transaction_id}", response_model=ConfidentialTransactionView)
async def get_confidential_transaction(transaction_id: str, api_key: str = Depends(get_api_key)): async def get_confidential_transaction(transaction_id: str, api_key: str = Depends(get_api_key)) -> ConfidentialTransactionView:
"""Get confidential transaction metadata (without decrypting sensitive data)""" """Get confidential transaction metadata (without decrypting sensitive data)"""
try: try:
# Retrieve transaction (in production, query from database) # Retrieve transaction (in production, query from database)
@@ -161,7 +166,7 @@ async def get_confidential_transaction(transaction_id: str, api_key: str = Depen
@router.post("/transactions/{transaction_id}/access", response_model=ConfidentialAccessResponse) @router.post("/transactions/{transaction_id}/access", response_model=ConfidentialAccessResponse)
async def access_confidential_data( async def access_confidential_data(
request: ConfidentialAccessRequest, transaction_id: str, api_key: str = Depends(get_api_key) request: ConfidentialAccessRequest, transaction_id: str, api_key: str = Depends(get_api_key)
): ) -> ConfidentialAccessResponse:
"""Request access to decrypt confidential transaction data""" """Request access to decrypt confidential transaction data"""
try: try:
# Validate request # Validate request
@@ -242,7 +247,7 @@ async def access_confidential_data(
@router.post("/transactions/{transaction_id}/audit", response_model=ConfidentialAccessResponse) @router.post("/transactions/{transaction_id}/audit", response_model=ConfidentialAccessResponse)
async def audit_access_confidential_data( async def audit_access_confidential_data(
transaction_id: str, authorization: str, purpose: str = "compliance", api_key: str = Depends(get_api_key) transaction_id: str, authorization: str, purpose: str = "compliance", api_key: str = Depends(get_api_key)
): ) -> ConfidentialAccessResponse:
"""Audit access to confidential transaction data""" """Audit access to confidential transaction data"""
try: try:
# Get transaction # Get transaction
@@ -293,7 +298,7 @@ async def audit_access_confidential_data(
@router.post("/keys/register", response_model=KeyRegistrationResponse) @router.post("/keys/register", response_model=KeyRegistrationResponse)
async def register_encryption_key(request: KeyRegistrationRequest, api_key: str = Depends(get_api_key)): async def register_encryption_key(request: KeyRegistrationRequest, api_key: str = Depends(get_api_key)) -> KeyRegistrationResponse:
"""Register public key for confidential transactions""" """Register public key for confidential transactions"""
try: try:
# Get key manager # Get key manager
@@ -336,7 +341,7 @@ async def register_encryption_key(request: KeyRegistrationRequest, api_key: str
@router.post("/keys/rotate") @router.post("/keys/rotate")
async def rotate_encryption_key(participant_id: str, api_key: str = Depends(get_api_key)): async def rotate_encryption_key(participant_id: str, api_key: str = Depends(get_api_key)) -> dict[str, Any]:
"""Rotate encryption keys for participant""" """Rotate encryption keys for participant"""
try: try:
km = get_key_manager() km = get_key_manager()
@@ -360,7 +365,7 @@ async def rotate_encryption_key(participant_id: str, api_key: str = Depends(get_
@router.get("/access/logs", response_model=AccessLogResponse) @router.get("/access/logs", response_model=AccessLogResponse)
async def get_access_logs(query: AccessLogQuery = Depends(), api_key: str = Depends(get_api_key)): async def get_access_logs(query: AccessLogQuery = Depends(), api_key: str = Depends(get_api_key)) -> AccessLogResponse:
"""Get access logs for confidential transactions""" """Get access logs for confidential transactions"""
try: try:
# Query logs (in production, query from database) # Query logs (in production, query from database)
@@ -373,7 +378,7 @@ async def get_access_logs(query: AccessLogQuery = Depends(), api_key: str = Depe
@router.get("/status") @router.get("/status")
async def get_confidential_status(api_key: str = Depends(get_api_key)): async def get_confidential_status(api_key: str = Depends(get_api_key)) -> dict[str, Any]:
"""Get status of confidential transaction system""" """Get status of confidential transaction system"""
try: try:
km = get_key_manager() km = get_key_manager()

View File

@@ -93,7 +93,7 @@ async def get_developer_earnings(
session: Session = Depends(get_session), session: Session = Depends(get_session),
ecosystem_service: EcosystemService = Depends(get_ecosystem_service), ecosystem_service: EcosystemService = Depends(get_ecosystem_service),
current_user: dict = Depends(get_current_user) current_user: dict = Depends(get_current_user)
): ) -> DeveloperEarningsResponse:
"""Get developer earnings metrics""" """Get developer earnings metrics"""
try: try:
earnings_data = await ecosystem_service.get_developer_earnings(period=period) earnings_data = await ecosystem_service.get_developer_earnings(period=period)
@@ -112,7 +112,7 @@ async def get_agent_utilization(
period: str = Field(default="monthly", regex="^(daily|weekly|monthly)$"), period: str = Field(default="monthly", regex="^(daily|weekly|monthly)$"),
session: Session = Depends(get_session), session: Session = Depends(get_session),
ecosystem_service: EcosystemService = Depends(get_ecosystem_service) ecosystem_service: EcosystemService = Depends(get_ecosystem_service)
): ) -> AgentUtilizationResponse:
"""Get agent utilization metrics""" """Get agent utilization metrics"""
try: try:
utilization_data = await ecosystem_service.get_agent_utilization(period=period) utilization_data = await ecosystem_service.get_agent_utilization(period=period)
@@ -131,7 +131,7 @@ async def get_treasury_allocation(
period: str = Field(default="monthly", regex="^(daily|weekly|monthly)$"), period: str = Field(default="monthly", regex="^(daily|weekly|monthly)$"),
session: Session = Depends(get_session), session: Session = Depends(get_session),
ecosystem_service: EcosystemService = Depends(get_ecosystem_service) ecosystem_service: EcosystemService = Depends(get_ecosystem_service)
): ) -> TreasuryAllocationResponse:
"""Get DAO treasury allocation metrics""" """Get DAO treasury allocation metrics"""
try: try:
treasury_data = await ecosystem_service.get_treasury_allocation(period=period) treasury_data = await ecosystem_service.get_treasury_allocation(period=period)
@@ -150,7 +150,7 @@ async def get_staking_metrics(
period: str = Field(default="monthly", regex="^(daily|weekly|monthly)$"), period: str = Field(default="monthly", regex="^(daily|weekly|monthly)$"),
session: Session = Depends(get_session), session: Session = Depends(get_session),
ecosystem_service: EcosystemService = Depends(get_ecosystem_service) ecosystem_service: EcosystemService = Depends(get_ecosystem_service)
): ) -> StakingMetricsResponse:
"""Get staking system metrics""" """Get staking system metrics"""
try: try:
staking_data = await ecosystem_service.get_staking_metrics(period=period) staking_data = await ecosystem_service.get_staking_metrics(period=period)
@@ -169,7 +169,7 @@ async def get_bounty_analytics(
period: str = Field(default="monthly", regex="^(daily|weekly|monthly)$"), period: str = Field(default="monthly", regex="^(daily|weekly|monthly)$"),
session: Session = Depends(get_session), session: Session = Depends(get_session),
ecosystem_service: EcosystemService = Depends(get_ecosystem_service) ecosystem_service: EcosystemService = Depends(get_ecosystem_service)
): ) -> BountyAnalyticsResponse:
"""Get bounty system analytics""" """Get bounty system analytics"""
try: try:
bounty_data = await ecosystem_service.get_bounty_analytics(period=period) bounty_data = await ecosystem_service.get_bounty_analytics(period=period)
@@ -188,7 +188,7 @@ async def get_ecosystem_overview(
period_type: str = Field(default="daily", regex="^(hourly|daily|weekly|monthly)$"), period_type: str = Field(default="daily", regex="^(hourly|daily|weekly|monthly)$"),
session: Session = Depends(get_session), session: Session = Depends(get_session),
ecosystem_service: EcosystemService = Depends(get_ecosystem_service) ecosystem_service: EcosystemService = Depends(get_ecosystem_service)
): ) -> EcosystemOverviewResponse:
"""Get comprehensive ecosystem overview""" """Get comprehensive ecosystem overview"""
try: try:
overview_data = await ecosystem_service.get_ecosystem_overview(period_type=period_type) overview_data = await ecosystem_service.get_ecosystem_overview(period_type=period_type)
@@ -217,7 +217,7 @@ async def get_ecosystem_metrics(
limit: int = Field(default=100, ge=1, le=1000), limit: int = Field(default=100, ge=1, le=1000),
session: Session = Depends(get_session), session: Session = Depends(get_session),
ecosystem_service: EcosystemService = Depends(get_ecosystem_service) ecosystem_service: EcosystemService = Depends(get_ecosystem_service)
): ) -> Dict[str, Any]:
"""Get time-series ecosystem metrics""" """Get time-series ecosystem metrics"""
try: try:
metrics = await ecosystem_service.get_time_series_metrics( metrics = await ecosystem_service.get_time_series_metrics(
@@ -241,7 +241,7 @@ async def get_ecosystem_metrics(
async def get_ecosystem_health_score( async def get_ecosystem_health_score(
session: Session = Depends(get_session), session: Session = Depends(get_session),
ecosystem_service: EcosystemService = Depends(get_ecosystem_service) ecosystem_service: EcosystemService = Depends(get_ecosystem_service)
): ) -> Dict[str, Any]:
"""Get overall ecosystem health score""" """Get overall ecosystem health score"""
try: try:
health_score = await ecosystem_service.calculate_health_score() health_score = await ecosystem_service.calculate_health_score()
@@ -262,7 +262,7 @@ async def get_growth_indicators(
period: str = Field(default="monthly", regex="^(daily|weekly|monthly)$"), period: str = Field(default="monthly", regex="^(daily|weekly|monthly)$"),
session: Session = Depends(get_session), session: Session = Depends(get_session),
ecosystem_service: EcosystemService = Depends(get_ecosystem_service) ecosystem_service: EcosystemService = Depends(get_ecosystem_service)
): ) -> Dict[str, Any]:
"""Get ecosystem growth indicators""" """Get ecosystem growth indicators"""
try: try:
growth_data = await ecosystem_service.get_growth_indicators(period=period) growth_data = await ecosystem_service.get_growth_indicators(period=period)
@@ -285,7 +285,7 @@ async def get_top_performers(
limit: int = Field(default=50, ge=1, le=100), limit: int = Field(default=50, ge=1, le=100),
session: Session = Depends(get_session), session: Session = Depends(get_session),
ecosystem_service: EcosystemService = Depends(get_ecosystem_service) ecosystem_service: EcosystemService = Depends(get_ecosystem_service)
): ) -> Dict[str, Any]:
"""Get top performers in different categories""" """Get top performers in different categories"""
try: try:
performers = await ecosystem_service.get_top_performers( performers = await ecosystem_service.get_top_performers(
@@ -311,7 +311,7 @@ async def get_ecosystem_predictions(
horizon: int = Field(default=30, ge=1, le=365), # days horizon: int = Field(default=30, ge=1, le=365), # days
session: Session = Depends(get_session), session: Session = Depends(get_session),
ecosystem_service: EcosystemService = Depends(get_ecosystem_service) ecosystem_service: EcosystemService = Depends(get_ecosystem_service)
): ) -> Dict[str, Any]:
"""Get ecosystem predictions based on historical data""" """Get ecosystem predictions based on historical data"""
try: try:
predictions = await ecosystem_service.get_predictions( predictions = await ecosystem_service.get_predictions(
@@ -336,7 +336,7 @@ async def get_ecosystem_alerts(
severity: str = Field(default="all", regex="^(low|medium|high|critical|all)$"), severity: str = Field(default="all", regex="^(low|medium|high|critical|all)$"),
session: Session = Depends(get_session), session: Session = Depends(get_session),
ecosystem_service: EcosystemService = Depends(get_ecosystem_service) ecosystem_service: EcosystemService = Depends(get_ecosystem_service)
): ) -> Dict[str, Any]:
"""Get ecosystem alerts and anomalies""" """Get ecosystem alerts and anomalies"""
try: try:
alerts = await ecosystem_service.get_alerts(severity=severity) alerts = await ecosystem_service.get_alerts(severity=severity)
@@ -360,7 +360,7 @@ async def get_ecosystem_comparison(
custom_end_date: Optional[datetime] = None, custom_end_date: Optional[datetime] = None,
session: Session = Depends(get_session), session: Session = Depends(get_session),
ecosystem_service: EcosystemService = Depends(get_ecosystem_service) ecosystem_service: EcosystemService = Depends(get_ecosystem_service)
): ) -> Dict[str, Any]:
"""Compare ecosystem metrics between periods""" """Compare ecosystem metrics between periods"""
try: try:
comparison = await ecosystem_service.get_period_comparison( comparison = await ecosystem_service.get_period_comparison(
@@ -389,7 +389,7 @@ async def export_ecosystem_data(
end_date: Optional[datetime] = None, end_date: Optional[datetime] = None,
session: Session = Depends(get_session), session: Session = Depends(get_session),
ecosystem_service: EcosystemService = Depends(get_ecosystem_service) ecosystem_service: EcosystemService = Depends(get_ecosystem_service)
): ) -> Dict[str, Any]:
"""Export ecosystem data in various formats""" """Export ecosystem data in various formats"""
try: try:
export_data = await ecosystem_service.export_data( export_data = await ecosystem_service.export_data(
@@ -416,7 +416,7 @@ async def export_ecosystem_data(
async def get_real_time_metrics( async def get_real_time_metrics(
session: Session = Depends(get_session), session: Session = Depends(get_session),
ecosystem_service: EcosystemService = Depends(get_ecosystem_service) ecosystem_service: EcosystemService = Depends(get_ecosystem_service)
): ) -> Dict[str, Any]:
"""Get real-time ecosystem metrics""" """Get real-time ecosystem metrics"""
try: try:
real_time_data = await ecosystem_service.get_real_time_metrics() real_time_data = await ecosystem_service.get_real_time_metrics()
@@ -435,7 +435,7 @@ async def get_real_time_metrics(
async def get_kpi_dashboard( async def get_kpi_dashboard(
session: Session = Depends(get_session), session: Session = Depends(get_session),
ecosystem_service: EcosystemService = Depends(get_ecosystem_service) ecosystem_service: EcosystemService = Depends(get_ecosystem_service)
): ) -> Dict[str, Any]:
"""Get KPI dashboard with key performance indicators""" """Get KPI dashboard with key performance indicators"""
try: try:
kpi_data = await ecosystem_service.get_kpi_dashboard() kpi_data = await ecosystem_service.get_kpi_dashboard()

View File

@@ -1,6 +1,6 @@
from typing import Annotated from typing import Annotated, Any
from fastapi import APIRouter, Depends, Query from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from ..domain.gpu_marketplace import ConsumerGPUProfile, EdgeGPUMetrics, GPUArchitecture from ..domain.gpu_marketplace import ConsumerGPUProfile, EdgeGPUMetrics, GPUArchitecture
@@ -20,7 +20,7 @@ async def get_consumer_gpu_profiles(
edge_optimized: bool | None = Query(default=None), edge_optimized: bool | None = Query(default=None),
min_memory_gb: int | None = Query(default=None), min_memory_gb: int | None = Query(default=None),
svc: EdgeGPUService = Depends(get_edge_service), svc: EdgeGPUService = Depends(get_edge_service),
): ) -> list[ConsumerGPUProfile]:
return svc.list_profiles(architecture=architecture, edge_optimized=edge_optimized, min_memory_gb=min_memory_gb) return svc.list_profiles(architecture=architecture, edge_optimized=edge_optimized, min_memory_gb=min_memory_gb)
@@ -29,12 +29,12 @@ async def get_edge_gpu_metrics(
gpu_id: str, gpu_id: str,
limit: int = Query(default=100, ge=1, le=500), limit: int = Query(default=100, ge=1, le=500),
svc: EdgeGPUService = Depends(get_edge_service), svc: EdgeGPUService = Depends(get_edge_service),
): ) -> list[EdgeGPUMetrics]:
return svc.list_metrics(gpu_id=gpu_id, limit=limit) return svc.list_metrics(gpu_id=gpu_id, limit=limit)
@router.post("/scan/{miner_id}") @router.post("/scan/{miner_id}")
async def scan_edge_gpus(miner_id: str, svc: EdgeGPUService = Depends(get_edge_service)): async def scan_edge_gpus(miner_id: str, svc: EdgeGPUService = Depends(get_edge_service)) -> dict[str, Any]:
"""Scan and register edge GPUs for a miner""" """Scan and register edge GPUs for a miner"""
try: try:
result = await svc.discover_and_register_edge_gpus(miner_id) result = await svc.discover_and_register_edge_gpus(miner_id)
@@ -51,7 +51,7 @@ async def scan_edge_gpus(miner_id: str, svc: EdgeGPUService = Depends(get_edge_s
@router.post("/optimize/inference/{gpu_id}") @router.post("/optimize/inference/{gpu_id}")
async def optimize_inference( async def optimize_inference(
gpu_id: str, model_name: str, request_data: dict, svc: EdgeGPUService = Depends(get_edge_service) gpu_id: str, model_name: str, request_data: dict, svc: EdgeGPUService = Depends(get_edge_service)
): ) -> dict[str, Any]:
"""Optimize ML inference request for edge GPU""" """Optimize ML inference request for edge GPU"""
try: try:
optimized = await svc.optimize_inference_for_edge(gpu_id, model_name, request_data) optimized = await svc.optimize_inference_for_edge(gpu_id, model_name, request_data)

View File

@@ -191,7 +191,7 @@ async def get_wallet_info_api() -> WalletInfoResponse:
raise HTTPException(status_code=500, detail=str(e)) raise HTTPException(status_code=500, detail=str(e))
async def monitor_payment(payment_id: str): async def monitor_payment(payment_id: str) -> None:
"""Monitor payment for confirmation (background task)""" """Monitor payment for confirmation (background task)"""
import asyncio import asyncio
@@ -212,13 +212,13 @@ async def monitor_payment(payment_id: str):
# Agent endpoints temporarily added to exchange router # Agent endpoints temporarily added to exchange router
@router.get("/agents/test") @router.get("/agents/test")
async def test_agent_endpoint(): async def test_agent_endpoint() -> dict[str, str]:
"""Test endpoint to verify agent routes are working""" """Test endpoint to verify agent routes are working"""
return {"message": "Agent routes are working", "timestamp": datetime.now(datetime.UTC).isoformat()} return {"message": "Agent routes are working", "timestamp": datetime.now(datetime.UTC).isoformat()}
@router.post("/agents/networks", response_model=dict, status_code=201) @router.post("/agents/networks", response_model=dict, status_code=201)
async def create_agent_network(network_data: dict): async def create_agent_network(network_data: dict) -> dict[str, Any]:
"""Create a new agent network for collaborative processing""" """Create a new agent network for collaborative processing"""
try: try:
@@ -254,7 +254,7 @@ async def create_agent_network(network_data: dict):
@router.get("/agents/executions/{execution_id}/receipt") @router.get("/agents/executions/{execution_id}/receipt")
async def get_execution_receipt(execution_id: str): async def get_execution_receipt(execution_id: str) -> dict[str, Any]:
"""Get verifiable receipt for completed execution""" """Get verifiable receipt for completed execution"""
try: try:

View File

@@ -9,7 +9,7 @@ REST API for OpenClaw DAO voting, proposals, and governance analytics
from __future__ import annotations from __future__ import annotations
from fastapi import APIRouter, Depends, HTTPException from fastapi import APIRouter, Body, Depends, HTTPException, Query
from aitbc import get_logger from aitbc import get_logger
@@ -59,7 +59,7 @@ class VoteRequest(BaseModel):
# Endpoints - Profile & Delegation # Endpoints - Profile & Delegation
@router.post("/profiles", response_model=GovernanceProfile) @router.post("/profiles", response_model=GovernanceProfile)
async def init_governance_profile(request: ProfileInitRequest, session: Annotated[Session, Depends(get_session)]): async def init_governance_profile(request: ProfileInitRequest, session: Annotated[Session, Depends(get_session)]) -> GovernanceProfile:
"""Initialize a governance profile for a user""" """Initialize a governance profile for a user"""
service = GovernanceService(session) service = GovernanceService(session)
try: try:
@@ -73,7 +73,7 @@ async def init_governance_profile(request: ProfileInitRequest, session: Annotate
@router.post("/profiles/{profile_id}/delegate", response_model=GovernanceProfile) @router.post("/profiles/{profile_id}/delegate", response_model=GovernanceProfile)
async def delegate_voting_power( async def delegate_voting_power(
profile_id: str, request: DelegationRequest, session: Annotated[Session, Depends(get_session)] profile_id: str, request: DelegationRequest, session: Annotated[Session, Depends(get_session)]
): ) -> GovernanceProfile:
"""Delegate your voting power to another DAO member""" """Delegate your voting power to another DAO member"""
service = GovernanceService(session) service = GovernanceService(session)
try: try:
@@ -91,7 +91,7 @@ async def create_proposal(
session: Annotated[Session, Depends(get_session)], session: Annotated[Session, Depends(get_session)],
proposer_id: str = Query(...), proposer_id: str = Query(...),
request: ProposalCreateRequest = Body(...), request: ProposalCreateRequest = Body(...),
): ) -> Proposal:
"""Submit a new governance proposal to the DAO""" """Submit a new governance proposal to the DAO"""
service = GovernanceService(session) service = GovernanceService(session)
try: try:
@@ -109,7 +109,7 @@ async def cast_vote(
session: Annotated[Session, Depends(get_session)], session: Annotated[Session, Depends(get_session)],
voter_id: str = Query(...), voter_id: str = Query(...),
request: VoteRequest = Body(...), request: VoteRequest = Body(...),
): ) -> Vote:
"""Cast a vote on an active proposal""" """Cast a vote on an active proposal"""
service = GovernanceService(session) service = GovernanceService(session)
try: try:
@@ -124,7 +124,7 @@ async def cast_vote(
@router.post("/proposals/{proposal_id}/process", response_model=Proposal) @router.post("/proposals/{proposal_id}/process", response_model=Proposal)
async def process_proposal(proposal_id: str, session: Annotated[Session, Depends(get_session)]): async def process_proposal(proposal_id: str, session: Annotated[Session, Depends(get_session)]) -> Proposal:
"""Manually trigger the lifecycle check of a proposal (e.g., tally votes when time ends)""" """Manually trigger the lifecycle check of a proposal (e.g., tally votes when time ends)"""
service = GovernanceService(session) service = GovernanceService(session)
try: try:
@@ -137,7 +137,7 @@ async def process_proposal(proposal_id: str, session: Annotated[Session, Depends
@router.post("/proposals/{proposal_id}/execute", response_model=Proposal) @router.post("/proposals/{proposal_id}/execute", response_model=Proposal)
async def execute_proposal(proposal_id: str, session: Annotated[Session, Depends(get_session)], executor_id: str = Query(...)): async def execute_proposal(proposal_id: str, session: Annotated[Session, Depends(get_session)], executor_id: str = Query(...)) -> Proposal:
"""Execute the payload of a succeeded proposal""" """Execute the payload of a succeeded proposal"""
service = GovernanceService(session) service = GovernanceService(session)
try: try:
@@ -153,7 +153,7 @@ async def execute_proposal(proposal_id: str, session: Annotated[Session, Depends
@router.post("/analytics/reports", response_model=TransparencyReport) @router.post("/analytics/reports", response_model=TransparencyReport)
async def generate_transparency_report( async def generate_transparency_report(
session: Annotated[Session, Depends(get_session)], period: str = Query(..., description="e.g., 2026-Q1") session: Annotated[Session, Depends(get_session)], period: str = Query(..., description="e.g., 2026-Q1")
): ) -> TransparencyReport:
"""Generate a governance analytics and transparency report""" """Generate a governance analytics and transparency report"""
service = GovernanceService(session) service = GovernanceService(session)
try: try:

View File

@@ -36,7 +36,7 @@ async def create_royalty_distribution(
royalty_tiers: RoyaltyDistributionRequest, royalty_tiers: RoyaltyDistributionRequest,
session: Session = Depends(Annotated[Session, Depends(get_session)]), session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()), current_user: str = Depends(require_admin_key()),
): ) -> RoyaltyDistributionResponse:
"""Create sophisticated royalty distribution for marketplace offer""" """Create sophisticated royalty distribution for marketplace offer"""
try: try:
@@ -72,7 +72,7 @@ async def calculate_royalties(
transaction_id: str | None = None, transaction_id: str | None = None,
session: Session = Depends(Annotated[Session, Depends(get_session)]), session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()), current_user: str = Depends(require_admin_key()),
): ) -> dict:
"""Calculate and distribute royalties for a sale""" """Calculate and distribute royalties for a sale"""
try: try:
@@ -102,7 +102,7 @@ async def create_model_license(
license_request: ModelLicenseRequest, license_request: ModelLicenseRequest,
session: Session = Depends(Annotated[Session, Depends(get_session)]), session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()), current_user: str = Depends(require_admin_key()),
): ) -> ModelLicenseResponse:
"""Create model license and IP protection""" """Create model license and IP protection"""
try: try:
@@ -143,7 +143,7 @@ async def verify_model(
verification_request: ModelVerificationRequest, verification_request: ModelVerificationRequest,
session: Session = Depends(Annotated[Session, Depends(get_session)]), session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()), current_user: str = Depends(require_admin_key()),
): ) -> ModelVerificationResponse:
"""Perform advanced model verification""" """Perform advanced model verification"""
try: try:
@@ -179,7 +179,7 @@ async def get_marketplace_analytics(
metrics: list[str] | None = None, metrics: list[str] | None = None,
session: Session = Depends(Annotated[Session, Depends(get_session)]), session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()), current_user: str = Depends(require_admin_key()),
): ) -> MarketplaceAnalyticsResponse:
"""Get comprehensive marketplace analytics""" """Get comprehensive marketplace analytics"""
try: try:

View File

@@ -32,7 +32,7 @@ app.include_router(health_router, tags=["health"])
@app.get("/health") @app.get("/health")
async def health(): async def health() -> dict[str, str]:
return {"status": "ok", "service": "marketplace-enhanced"} return {"status": "ok", "service": "marketplace-enhanced"}

View File

@@ -6,7 +6,7 @@ Enhanced Marketplace API Router - Simplified Version
REST API endpoints for enhanced marketplace features REST API endpoints for enhanced marketplace features
""" """
from typing import Any from typing import Annotated, Any
from aitbc import get_logger from aitbc import get_logger
@@ -56,9 +56,9 @@ class MarketplaceAnalyticsRequest(BaseModel):
async def create_royalty_distribution( async def create_royalty_distribution(
request: RoyaltyDistributionRequest, request: RoyaltyDistributionRequest,
offer_id: str, offer_id: str,
session: Session = Depends(get_session), session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()), current_user: str = Depends(require_admin_key()),
): ) -> dict[str, Any]:
"""Create royalty distribution for marketplace offer""" """Create royalty distribution for marketplace offer"""
try: try:
@@ -78,9 +78,9 @@ async def create_royalty_distribution(
async def calculate_royalties( async def calculate_royalties(
offer_id: str, offer_id: str,
sale_amount: float, sale_amount: float,
session: Session = Depends(get_session), session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()), current_user: str = Depends(require_admin_key()),
): ) -> dict[str, Any]:
"""Calculate royalties for a sale""" """Calculate royalties for a sale"""
try: try:
@@ -98,9 +98,9 @@ async def calculate_royalties(
async def create_model_license( async def create_model_license(
request: ModelLicenseRequest, request: ModelLicenseRequest,
offer_id: str, offer_id: str,
session: Session = Depends(get_session), session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()), current_user: str = Depends(require_admin_key()),
): ) -> dict[str, Any]:
"""Create model license for marketplace offer""" """Create model license for marketplace offer"""
try: try:
@@ -124,9 +124,9 @@ async def create_model_license(
async def verify_model( async def verify_model(
request: ModelVerificationRequest, request: ModelVerificationRequest,
offer_id: str, offer_id: str,
session: Session = Depends(get_session), session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()), current_user: str = Depends(require_admin_key()),
): ) -> dict[str, Any]:
"""Verify model quality and performance""" """Verify model quality and performance"""
try: try:
@@ -143,9 +143,9 @@ async def verify_model(
@router.post("/analytics") @router.post("/analytics")
async def get_marketplace_analytics( async def get_marketplace_analytics(
request: MarketplaceAnalyticsRequest, request: MarketplaceAnalyticsRequest,
session: Session = Depends(get_session), session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()), current_user: str = Depends(require_admin_key()),
): ) -> dict[str, Any]:
"""Get marketplace analytics and insights""" """Get marketplace analytics and insights"""
try: try:

View File

@@ -135,7 +135,7 @@ def _gpu_to_dict(gpu: GPURegistry) -> dict[str, Any]:
} }
def _get_gpu_or_404(session, gpu_id: str) -> GPURegistry: def _get_gpu_or_404(session: Session, gpu_id: str) -> GPURegistry:
gpu = session.get(GPURegistry, gpu_id) gpu = session.get(GPURegistry, gpu_id)
if not gpu: if not gpu:
raise HTTPException( raise HTTPException(

View File

@@ -3,15 +3,18 @@ Marketplace Performance Optimization API Endpoints
REST API for managing distributed processing, GPU optimization, caching, and scaling REST API for managing distributed processing, GPU optimization, caching, and scaling
""" """
import time
import os
import sys
from typing import Any from typing import Any
from fastapi import APIRouter, BackgroundTasks, HTTPException
from pydantic import BaseModel, Field
from aitbc import get_logger from aitbc import get_logger
logger = get_logger(__name__) logger = get_logger(__name__)
import os
import sys
from app.services.marketplace_gpu_optimizer import MarketplaceGPUOptimizer from app.services.marketplace_gpu_optimizer import MarketplaceGPUOptimizer
from app.services.distributed_framework import ( from app.services.distributed_framework import (
DistributedProcessingCoordinator, DistributedProcessingCoordinator,
@@ -32,7 +35,7 @@ resource_scaler = ResourceScaler()
# Startup event handler for background tasks # Startup event handler for background tasks
@router.on_event("startup") @router.on_event("startup")
async def startup_event(): async def startup_event() -> None:
await marketplace_monitor.start() await marketplace_monitor.start()
await distributed_coordinator.start() await distributed_coordinator.start()
await resource_scaler.start() await resource_scaler.start()
@@ -40,7 +43,7 @@ async def startup_event():
@router.on_event("shutdown") @router.on_event("shutdown")
async def shutdown_event(): async def shutdown_event() -> None:
await marketplace_monitor.stop() await marketplace_monitor.stop()
await distributed_coordinator.stop() await distributed_coordinator.stop()
await resource_scaler.stop() await resource_scaler.stop()
@@ -85,7 +88,7 @@ class ScalingPolicyUpdate(BaseModel):
# Endpoints: GPU Optimization # Endpoints: GPU Optimization
@router.post("/gpu/allocate") @router.post("/gpu/allocate")
async def allocate_gpu_resources(request: GPUAllocationRequest): async def allocate_gpu_resources(request: GPUAllocationRequest) -> dict[str, Any]:
"""Request optimal GPU resource allocation for a marketplace task""" """Request optimal GPU resource allocation for a marketplace task"""
try: try:
start_time = time.time() start_time = time.time()
@@ -105,7 +108,7 @@ async def allocate_gpu_resources(request: GPUAllocationRequest):
@router.post("/gpu/release") @router.post("/gpu/release")
async def release_gpu_resources(request: GPUReleaseRequest): async def release_gpu_resources(request: GPUReleaseRequest) -> dict[str, str]:
"""Release previously allocated GPU resources""" """Release previously allocated GPU resources"""
success = gpu_optimizer.release_resources(request.job_id) success = gpu_optimizer.release_resources(request.job_id)
if not success: if not success:
@@ -114,14 +117,14 @@ async def release_gpu_resources(request: GPUReleaseRequest):
@router.get("/gpu/status") @router.get("/gpu/status")
async def get_gpu_status(): async def get_gpu_status() -> dict[str, Any]:
"""Get overall GPU fleet status and optimization metrics""" """Get overall GPU fleet status and optimization metrics"""
return gpu_optimizer.get_system_status() return gpu_optimizer.get_system_status()
# Endpoints: Distributed Processing # Endpoints: Distributed Processing
@router.post("/distributed/task") @router.post("/distributed/task")
async def submit_distributed_task(request: DistributedTaskRequest): async def submit_distributed_task(request: DistributedTaskRequest) -> dict[str, str]:
"""Submit a task to the distributed processing framework""" """Submit a task to the distributed processing framework"""
task = DistributedTask( task = DistributedTask(
task_id=None, task_id=None,
@@ -137,7 +140,7 @@ async def submit_distributed_task(request: DistributedTaskRequest):
@router.get("/distributed/task/{task_id}") @router.get("/distributed/task/{task_id}")
async def get_distributed_task_status(task_id: str): async def get_distributed_task_status(task_id: str) -> dict[str, Any]:
"""Check the status and get results of a distributed task""" """Check the status and get results of a distributed task"""
status = await distributed_coordinator.get_task_status(task_id) status = await distributed_coordinator.get_task_status(task_id)
if not status: if not status:
@@ -146,7 +149,7 @@ async def get_distributed_task_status(task_id: str):
@router.post("/distributed/worker/register") @router.post("/distributed/worker/register")
async def register_worker(request: WorkerRegistrationRequest): async def register_worker(request: WorkerRegistrationRequest) -> dict[str, str]:
"""Register a new worker node in the cluster""" """Register a new worker node in the cluster"""
distributed_coordinator.register_worker( distributed_coordinator.register_worker(
worker_id=request.worker_id, worker_id=request.worker_id,
@@ -158,14 +161,14 @@ async def register_worker(request: WorkerRegistrationRequest):
@router.get("/distributed/status") @router.get("/distributed/status")
async def get_cluster_status(): async def get_cluster_status() -> dict[str, Any]:
"""Get overall distributed cluster health and load""" """Get overall distributed cluster health and load"""
return distributed_coordinator.get_cluster_status() return distributed_coordinator.get_cluster_status()
# Endpoints: Caching # Endpoints: Caching
@router.get("/cache/stats") @router.get("/cache/stats")
async def get_cache_stats(): async def get_cache_stats() -> dict[str, Any]:
"""Get current caching performance statistics""" """Get current caching performance statistics"""
return { return {
"status": "connected" if cache_optimizer.is_connected else "local_only", "status": "connected" if cache_optimizer.is_connected else "local_only",
@@ -175,7 +178,7 @@ async def get_cache_stats():
@router.post("/cache/invalidate/{namespace}") @router.post("/cache/invalidate/{namespace}")
async def invalidate_cache_namespace(namespace: str, background_tasks: BackgroundTasks): async def invalidate_cache_namespace(namespace: str, background_tasks: BackgroundTasks) -> dict[str, str]:
"""Invalidate a specific cache namespace (e.g., 'order_book')""" """Invalidate a specific cache namespace (e.g., 'order_book')"""
background_tasks.add_task(cache_optimizer.invalidate_namespace, namespace) background_tasks.add_task(cache_optimizer.invalidate_namespace, namespace)
return {"success": True, "message": f"Invalidation for {namespace} queued"} return {"success": True, "message": f"Invalidation for {namespace} queued"}
@@ -183,20 +186,20 @@ async def invalidate_cache_namespace(namespace: str, background_tasks: Backgroun
# Endpoints: Monitoring # Endpoints: Monitoring
@router.get("/monitor/dashboard") @router.get("/monitor/dashboard")
async def get_monitoring_dashboard(): async def get_monitoring_dashboard() -> dict[str, Any]:
"""Get real-time performance dashboard data""" """Get real-time performance dashboard data"""
return marketplace_monitor.get_realtime_dashboard_data() return marketplace_monitor.get_realtime_dashboard_data()
# Endpoints: Auto-scaling # Endpoints: Auto-scaling
@router.get("/scaler/status") @router.get("/scaler/status")
async def get_scaler_status(): async def get_scaler_status() -> dict[str, Any]:
"""Get current auto-scaler status and active rules""" """Get current auto-scaler status and active rules"""
return resource_scaler.get_status() return resource_scaler.get_status()
@router.post("/scaler/policy") @router.post("/scaler/policy")
async def update_scaling_policy(policy_update: ScalingPolicyUpdate): async def update_scaling_policy(policy_update: ScalingPolicyUpdate) -> dict[str, str]:
"""Update auto-scaling thresholds and parameters dynamically""" """Update auto-scaling thresholds and parameters dynamically"""
current_policy = resource_scaler.policy current_policy = resource_scaler.policy

View File

@@ -1,4 +1,6 @@
from typing import Any
from fastapi import APIRouter, HTTPException from fastapi import APIRouter, HTTPException
from ..services.fhe_service import FHEService from ..services.fhe_service import FHEService
@@ -11,7 +13,7 @@ fhe_service = FHEService()
@router.post("/prove/training") @router.post("/prove/training")
async def prove_ml_training(proof_request: dict): async def prove_ml_training(proof_request: dict) -> dict[str, Any]:
"""Generate ZK proof for ML training verification""" """Generate ZK proof for ML training verification"""
try: try:
circuit_name = "ml_training_verification" circuit_name = "ml_training_verification"
@@ -33,7 +35,7 @@ async def prove_ml_training(proof_request: dict):
@router.post("/verify/training") @router.post("/verify/training")
async def verify_ml_training(verification_request: dict): async def verify_ml_training(verification_request: dict) -> dict[str, Any]:
"""Verify ZK proof for ML training""" """Verify ZK proof for ML training"""
try: try:
verification_result = await zk_service.verify_proof( verification_result = await zk_service.verify_proof(
@@ -52,7 +54,7 @@ async def verify_ml_training(verification_request: dict):
@router.post("/prove/modular") @router.post("/prove/modular")
async def prove_modular_ml(proof_request: dict): async def prove_modular_ml(proof_request: dict) -> dict[str, Any]:
"""Generate ZK proof using optimized modular circuits""" """Generate ZK proof using optimized modular circuits"""
try: try:
circuit_name = "modular_ml_components" circuit_name = "modular_ml_components"
@@ -75,7 +77,7 @@ async def prove_modular_ml(proof_request: dict):
@router.post("/verify/inference") @router.post("/verify/inference")
async def verify_ml_inference(verification_request: dict): async def verify_ml_inference(verification_request: dict) -> dict[str, Any]:
"""Verify ZK proof for ML inference""" """Verify ZK proof for ML inference"""
try: try:
verification_result = await zk_service.verify_proof( verification_result = await zk_service.verify_proof(
@@ -94,7 +96,7 @@ async def verify_ml_inference(verification_request: dict):
@router.post("/fhe/inference") @router.post("/fhe/inference")
async def fhe_ml_inference(fhe_request: dict): async def fhe_ml_inference(fhe_request: dict) -> dict[str, Any]:
"""Perform ML inference on encrypted data""" """Perform ML inference on encrypted data"""
try: try:
# Setup FHE context # Setup FHE context
@@ -123,7 +125,7 @@ async def fhe_ml_inference(fhe_request: dict):
@router.get("/circuits") @router.get("/circuits")
async def list_ml_circuits(): async def list_ml_circuits() -> dict[str, Any]:
"""List available ML ZK circuits""" """List available ML ZK circuits"""
circuits = [ circuits = [
{ {

View File

@@ -41,7 +41,7 @@ async def route_agent_skill(
routing_request: SkillRoutingRequest, routing_request: SkillRoutingRequest,
session: Session = Depends(Annotated[Session, Depends(get_session)]), session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()), current_user: str = Depends(require_admin_key()),
): ) -> SkillRoutingResponse:
"""Sophisticated agent skill routing""" """Sophisticated agent skill routing"""
try: try:
@@ -69,7 +69,7 @@ async def intelligent_job_offloading(
offloading_request: JobOffloadingRequest, offloading_request: JobOffloadingRequest,
session: Session = Depends(Annotated[Session, Depends(get_session)]), session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()), current_user: str = Depends(require_admin_key()),
): ) -> JobOffloadingResponse:
"""Intelligent job offloading strategies""" """Intelligent job offloading strategies"""
try: try:
@@ -98,7 +98,7 @@ async def coordinate_agent_collaboration(
collaboration_request: AgentCollaborationRequest, collaboration_request: AgentCollaborationRequest,
session: Session = Depends(Annotated[Session, Depends(get_session)]), session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()), current_user: str = Depends(require_admin_key()),
): ) -> AgentCollaborationResponse:
"""Agent collaboration and coordination""" """Agent collaboration and coordination"""
try: try:
@@ -127,7 +127,7 @@ async def optimize_hybrid_execution(
execution_request: HybridExecutionRequest, execution_request: HybridExecutionRequest,
session: Session = Depends(Annotated[Session, Depends(get_session)]), session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()), current_user: str = Depends(require_admin_key()),
): ) -> HybridExecutionResponse:
"""Hybrid execution optimization""" """Hybrid execution optimization"""
try: try:
@@ -155,7 +155,7 @@ async def deploy_to_edge(
deployment_request: EdgeDeploymentRequest, deployment_request: EdgeDeploymentRequest,
session: Session = Depends(Annotated[Session, Depends(get_session)]), session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()), current_user: str = Depends(require_admin_key()),
): ) -> EdgeDeploymentResponse:
"""Deploy agent to edge computing infrastructure""" """Deploy agent to edge computing infrastructure"""
try: try:
@@ -184,7 +184,7 @@ async def coordinate_edge_to_cloud(
coordination_request: EdgeCoordinationRequest, coordination_request: EdgeCoordinationRequest,
session: Session = Depends(Annotated[Session, Depends(get_session)]), session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()), current_user: str = Depends(require_admin_key()),
): ) -> EdgeCoordinationResponse:
"""Coordinate edge-to-cloud agent operations""" """Coordinate edge-to-cloud agent operations"""
try: try:
@@ -213,7 +213,7 @@ async def develop_openclaw_ecosystem(
ecosystem_request: EcosystemDevelopmentRequest, ecosystem_request: EcosystemDevelopmentRequest,
session: Session = Depends(Annotated[Session, Depends(get_session)]), session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()), current_user: str = Depends(require_admin_key()),
): ) -> EcosystemDevelopmentResponse:
"""Build comprehensive OpenClaw ecosystem""" """Build comprehensive OpenClaw ecosystem"""
try: try:

View File

@@ -4,6 +4,8 @@
OpenClaw Enhanced Service - FastAPI Entry Point OpenClaw Enhanced Service - FastAPI Entry Point
""" """
from typing import Any
from fastapi import FastAPI from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware from fastapi.middleware.cors import CORSMiddleware
@@ -32,12 +34,12 @@ app.include_router(health_router, tags=["health"])
@app.get("/health") @app.get("/health")
async def health(): async def health() -> dict[str, str]:
return {"status": "ok", "service": "openclaw-enhanced"} return {"status": "ok", "service": "openclaw-enhanced"}
@app.get("/health/detailed") @app.get("/health/detailed")
async def detailed_health(): async def detailed_health() -> dict[str, Any]:
"""Simple health check without database dependency""" """Simple health check without database dependency"""
try: try:
import psutil import psutil

View File

@@ -81,7 +81,7 @@ async def route_agent_skill(
request: SkillRoutingRequest, request: SkillRoutingRequest,
session: Session = Depends(Annotated[Session, Depends(get_session)]), session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()), current_user: str = Depends(require_admin_key()),
): ) -> dict[str, Any]:
"""Route agent skill to appropriate agent""" """Route agent skill to appropriate agent"""
try: try:
@@ -104,7 +104,7 @@ async def intelligent_job_offloading(
request: JobOffloadingRequest, request: JobOffloadingRequest,
session: Session = Depends(Annotated[Session, Depends(get_session)]), session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()), current_user: str = Depends(require_admin_key()),
): ) -> dict[str, Any]:
"""Intelligent job offloading strategies""" """Intelligent job offloading strategies"""
try: try:
@@ -127,7 +127,7 @@ async def coordinate_agent_collaboration(
request: AgentCollaborationRequest, request: AgentCollaborationRequest,
session: Session = Depends(Annotated[Session, Depends(get_session)]), session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()), current_user: str = Depends(require_admin_key()),
): ) -> dict[str, Any]:
"""Agent collaboration and coordination""" """Agent collaboration and coordination"""
try: try:
@@ -148,7 +148,7 @@ async def optimize_hybrid_execution(
request: HybridExecutionRequest, request: HybridExecutionRequest,
session: Session = Depends(Annotated[Session, Depends(get_session)]), session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()), current_user: str = Depends(require_admin_key()),
): ) -> dict[str, Any]:
"""Hybrid execution optimization""" """Hybrid execution optimization"""
try: try:
@@ -169,7 +169,7 @@ async def deploy_to_edge(
request: EdgeDeploymentRequest, request: EdgeDeploymentRequest,
session: Session = Depends(Annotated[Session, Depends(get_session)]), session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()), current_user: str = Depends(require_admin_key()),
): ) -> dict[str, Any]:
"""Deploy agent to edge computing infrastructure""" """Deploy agent to edge computing infrastructure"""
try: try:
@@ -190,7 +190,7 @@ async def coordinate_edge_to_cloud(
request: EdgeCoordinationRequest, request: EdgeCoordinationRequest,
session: Session = Depends(Annotated[Session, Depends(get_session)]), session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()), current_user: str = Depends(require_admin_key()),
): ) -> dict[str, Any]:
"""Coordinate edge-to-cloud agent operations""" """Coordinate edge-to-cloud agent operations"""
try: try:
@@ -211,7 +211,7 @@ async def develop_openclaw_ecosystem(
request: EcosystemDevelopmentRequest, request: EcosystemDevelopmentRequest,
session: Session = Depends(Annotated[Session, Depends(get_session)]), session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()), current_user: str = Depends(require_admin_key()),
): ) -> dict[str, Any]:
"""Build OpenClaw ecosystem components""" """Build OpenClaw ecosystem components"""
try: try:

View File

@@ -267,7 +267,7 @@ async def llm_stream(
request: LLMRequest, request: LLMRequest,
session: Annotated[Session, Depends(get_session)], session: Annotated[Session, Depends(get_session)],
client_id: str = Depends(require_client_key()), client_id: str = Depends(require_client_key()),
): ) -> ServiceResponse:
"""Stream LLM inference response""" """Stream LLM inference response"""
# Force streaming mode # Force streaming mode
request.stream = True request.stream = True

View File

@@ -3,6 +3,7 @@ Settlement router for cross-chain settlements
""" """
import asyncio import asyncio
from typing import Any
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException
from pydantic import BaseModel, Field from pydantic import BaseModel, Field
@@ -38,7 +39,7 @@ class CrossChainSettlementResponse(BaseModel):
@router.post("/cross-chain", response_model=CrossChainSettlementResponse) @router.post("/cross-chain", response_model=CrossChainSettlementResponse)
async def initiate_cross_chain_settlement( async def initiate_cross_chain_settlement(
request: CrossChainSettlementRequest, background_tasks: BackgroundTasks, api_key: str = Depends(get_api_key) request: CrossChainSettlementRequest, background_tasks: BackgroundTasks, api_key: str = Depends(get_api_key)
): ) -> CrossChainSettlementResponse:
"""Initiate a cross-chain settlement""" """Initiate a cross-chain settlement"""
try: try:
# Initialize settlement manager # Initialize settlement manager
@@ -70,7 +71,7 @@ async def initiate_cross_chain_settlement(
@router.get("/cross-chain/{settlement_id}") @router.get("/cross-chain/{settlement_id}")
async def get_settlement_status(settlement_id: str, api_key: str = Depends(get_api_key)): async def get_settlement_status(settlement_id: str, api_key: str = Depends(get_api_key)) -> dict[str, Any]:
"""Get settlement status""" """Get settlement status"""
try: try:
manager = BridgeManager() manager = BridgeManager()
@@ -95,7 +96,7 @@ async def get_settlement_status(settlement_id: str, api_key: str = Depends(get_a
@router.get("/cross-chain") @router.get("/cross-chain")
async def list_settlements(api_key: str = Depends(get_api_key), limit: int = 50, offset: int = 0): async def list_settlements(api_key: str = Depends(get_api_key), limit: int = 50, offset: int = 0) -> dict[str, Any]:
"""List settlements with pagination""" """List settlements with pagination"""
try: try:
manager = BridgeManager() manager = BridgeManager()
@@ -108,7 +109,7 @@ async def list_settlements(api_key: str = Depends(get_api_key), limit: int = 50,
@router.delete("/cross-chain/{settlement_id}") @router.delete("/cross-chain/{settlement_id}")
async def cancel_settlement(settlement_id: str, api_key: str = Depends(get_api_key)): async def cancel_settlement(settlement_id: str, api_key: str = Depends(get_api_key)) -> dict[str, str]:
"""Cancel a pending settlement""" """Cancel a pending settlement"""
try: try:
manager = BridgeManager() manager = BridgeManager()

View File

@@ -29,7 +29,7 @@ class StakeCreateRequest(BaseModel):
auto_compound: bool = Field(default=False) auto_compound: bool = Field(default=False)
@validator('amount') @validator('amount')
def validate_amount(cls, v): def validate_amount(cls, v: float) -> float:
if v < 100.0: if v < 100.0:
raise ValueError('Minimum stake amount is 100 AITBC') raise ValueError('Minimum stake amount is 100 AITBC')
if v > 100000.0: if v > 100000.0:
@@ -151,7 +151,7 @@ async def create_stake(
staking_service: StakingService = Depends(get_staking_service), staking_service: StakingService = Depends(get_staking_service),
blockchain_service: BlockchainService = Depends(get_blockchain_service), blockchain_service: BlockchainService = Depends(get_blockchain_service),
current_user: dict = Depends(get_current_user) current_user: dict = Depends(get_current_user)
): ) -> StakeResponse:
"""Create a new stake on an agent wallet""" """Create a new stake on an agent wallet"""
try: try:
logger.info(f"Creating stake: {request.amount} AITBC on {request.agent_wallet} by {current_user['address']}") logger.info(f"Creating stake: {request.amount} AITBC on {request.agent_wallet} by {current_user['address']}")
@@ -191,7 +191,7 @@ async def get_stake(
session: Session = Depends(get_session), session: Session = Depends(get_session),
staking_service: StakingService = Depends(get_staking_service), staking_service: StakingService = Depends(get_staking_service),
current_user: dict = Depends(get_current_user) current_user: dict = Depends(get_current_user)
): ) -> StakeResponse:
"""Get stake details""" """Get stake details"""
try: try:
stake = await staking_service.get_stake(stake_id) stake = await staking_service.get_stake(stake_id)
@@ -216,7 +216,7 @@ async def get_stakes(
session: Session = Depends(get_session), session: Session = Depends(get_session),
staking_service: StakingService = Depends(get_staking_service), staking_service: StakingService = Depends(get_staking_service),
current_user: dict = Depends(get_current_user) current_user: dict = Depends(get_current_user)
): ) -> List[StakeResponse]:
"""Get filtered list of user's stakes""" """Get filtered list of user's stakes"""
try: try:
stakes = await staking_service.get_user_stakes( stakes = await staking_service.get_user_stakes(
@@ -246,7 +246,7 @@ async def add_to_stake(
staking_service: StakingService = Depends(get_staking_service), staking_service: StakingService = Depends(get_staking_service),
blockchain_service: BlockchainService = Depends(get_blockchain_service), blockchain_service: BlockchainService = Depends(get_blockchain_service),
current_user: dict = Depends(get_current_user) current_user: dict = Depends(get_current_user)
): ) -> StakeResponse:
"""Add more tokens to an existing stake""" """Add more tokens to an existing stake"""
try: try:
# Get stake and verify ownership # Get stake and verify ownership
@@ -289,7 +289,7 @@ async def unbond_stake(
staking_service: StakingService = Depends(get_staking_service), staking_service: StakingService = Depends(get_staking_service),
blockchain_service: BlockchainService = Depends(get_blockchain_service), blockchain_service: BlockchainService = Depends(get_blockchain_service),
current_user: dict = Depends(get_current_user) current_user: dict = Depends(get_current_user)
): ) -> Dict[str, str]:
"""Initiate unbonding for a stake""" """Initiate unbonding for a stake"""
try: try:
# Get stake and verify ownership # Get stake and verify ownership
@@ -331,7 +331,7 @@ async def complete_unbonding(
staking_service: StakingService = Depends(get_staking_service), staking_service: StakingService = Depends(get_staking_service),
blockchain_service: BlockchainService = Depends(get_blockchain_service), blockchain_service: BlockchainService = Depends(get_blockchain_service),
current_user: dict = Depends(get_current_user) current_user: dict = Depends(get_current_user)
): ) -> Dict[str, Any]:
"""Complete unbonding and return stake + rewards""" """Complete unbonding and return stake + rewards"""
try: try:
# Get stake and verify ownership # Get stake and verify ownership
@@ -373,7 +373,7 @@ async def get_stake_rewards(
session: Session = Depends(get_session), session: Session = Depends(get_session),
staking_service: StakingService = Depends(get_staking_service), staking_service: StakingService = Depends(get_staking_service),
current_user: dict = Depends(get_current_user) current_user: dict = Depends(get_current_user)
): ) -> Dict[str, Any]:
"""Get current rewards for a stake""" """Get current rewards for a stake"""
try: try:
# Get stake and verify ownership # Get stake and verify ownership
@@ -407,7 +407,7 @@ async def get_agent_metrics(
agent_wallet: str, agent_wallet: str,
session: Session = Depends(get_session), session: Session = Depends(get_session),
staking_service: StakingService = Depends(get_staking_service) staking_service: StakingService = Depends(get_staking_service)
): ) -> AgentMetricsResponse:
"""Get agent performance metrics""" """Get agent performance metrics"""
try: try:
metrics = await staking_service.get_agent_metrics(agent_wallet) metrics = await staking_service.get_agent_metrics(agent_wallet)
@@ -427,7 +427,7 @@ async def get_staking_pool(
agent_wallet: str, agent_wallet: str,
session: Session = Depends(get_session), session: Session = Depends(get_session),
staking_service: StakingService = Depends(get_staking_service) staking_service: StakingService = Depends(get_staking_service)
): ) -> StakingPoolResponse:
"""Get staking pool information for an agent""" """Get staking pool information for an agent"""
try: try:
pool = await staking_service.get_staking_pool(agent_wallet) pool = await staking_service.get_staking_pool(agent_wallet)
@@ -448,7 +448,7 @@ async def get_agent_apy(
lock_period: int = Field(default=30, ge=1, le=365), lock_period: int = Field(default=30, ge=1, le=365),
session: Session = Depends(get_session), session: Session = Depends(get_session),
staking_service: StakingService = Depends(get_staking_service) staking_service: StakingService = Depends(get_staking_service)
): ) -> Dict[str, Any]:
"""Get current APY for staking on an agent""" """Get current APY for staking on an agent"""
try: try:
apy = await staking_service.calculate_apy(agent_wallet, lock_period) apy = await staking_service.calculate_apy(agent_wallet, lock_period)
@@ -474,7 +474,7 @@ async def update_agent_performance(
staking_service: StakingService = Depends(get_staking_service), staking_service: StakingService = Depends(get_staking_service),
blockchain_service: BlockchainService = Depends(get_blockchain_service), blockchain_service: BlockchainService = Depends(get_blockchain_service),
current_user: dict = Depends(get_current_user) current_user: dict = Depends(get_current_user)
): ) -> Dict[str, str]:
"""Update agent performance metrics (oracle only)""" """Update agent performance metrics (oracle only)"""
try: try:
# Check permissions # Check permissions
@@ -512,7 +512,7 @@ async def distribute_agent_earnings(
staking_service: StakingService = Depends(get_staking_service), staking_service: StakingService = Depends(get_staking_service),
blockchain_service: BlockchainService = Depends(get_blockchain_service), blockchain_service: BlockchainService = Depends(get_blockchain_service),
current_user: dict = Depends(get_current_user) current_user: dict = Depends(get_current_user)
): ) -> Dict[str, Any]:
"""Distribute agent earnings to stakers""" """Distribute agent earnings to stakers"""
try: try:
# Check permissions # Check permissions
@@ -553,7 +553,7 @@ async def get_supported_agents(
tier: Optional[PerformanceTier] = None, tier: Optional[PerformanceTier] = None,
session: Session = Depends(get_session), session: Session = Depends(get_session),
staking_service: StakingService = Depends(get_staking_service) staking_service: StakingService = Depends(get_staking_service)
): ) -> Dict[str, Any]:
"""Get list of supported agents for staking""" """Get list of supported agents for staking"""
try: try:
agents = await staking_service.get_supported_agents( agents = await staking_service.get_supported_agents(
@@ -578,7 +578,7 @@ async def get_staking_stats(
period: str = Field(default="daily", regex="^(hourly|daily|weekly|monthly)$"), period: str = Field(default="daily", regex="^(hourly|daily|weekly|monthly)$"),
session: Session = Depends(get_session), session: Session = Depends(get_session),
staking_service: StakingService = Depends(get_staking_service) staking_service: StakingService = Depends(get_staking_service)
): ) -> StakingStatsResponse:
"""Get staking system statistics""" """Get staking system statistics"""
try: try:
stats = await staking_service.get_staking_stats(period=period) stats = await staking_service.get_staking_stats(period=period)
@@ -596,7 +596,7 @@ async def get_staking_leaderboard(
limit: int = Field(default=50, ge=1, le=100), limit: int = Field(default=50, ge=1, le=100),
session: Session = Depends(get_session), session: Session = Depends(get_session),
staking_service: StakingService = Depends(get_staking_service) staking_service: StakingService = Depends(get_staking_service)
): ) -> Dict[str, Any]:
"""Get staking leaderboard""" """Get staking leaderboard"""
try: try:
leaderboard = await staking_service.get_leaderboard( leaderboard = await staking_service.get_leaderboard(
@@ -620,7 +620,7 @@ async def get_my_staking_positions(
session: Session = Depends(get_session), session: Session = Depends(get_session),
staking_service: StakingService = Depends(get_staking_service), staking_service: StakingService = Depends(get_staking_service),
current_user: dict = Depends(get_current_user) current_user: dict = Depends(get_current_user)
): ) -> List[StakeResponse]:
"""Get current user's staking positions""" """Get current user's staking positions"""
try: try:
stakes = await staking_service.get_user_stakes( stakes = await staking_service.get_user_stakes(
@@ -643,7 +643,7 @@ async def get_my_staking_rewards(
session: Session = Depends(get_session), session: Session = Depends(get_session),
staking_service: StakingService = Depends(get_staking_service), staking_service: StakingService = Depends(get_staking_service),
current_user: dict = Depends(get_current_user) current_user: dict = Depends(get_current_user)
): ) -> Dict[str, Any]:
"""Get current user's staking rewards""" """Get current user's staking rewards"""
try: try:
rewards = await staking_service.get_user_rewards( rewards = await staking_service.get_user_rewards(
@@ -665,7 +665,7 @@ async def claim_staking_rewards(
staking_service: StakingService = Depends(get_staking_service), staking_service: StakingService = Depends(get_staking_service),
blockchain_service: BlockchainService = Depends(get_blockchain_service), blockchain_service: BlockchainService = Depends(get_blockchain_service),
current_user: dict = Depends(get_current_user) current_user: dict = Depends(get_current_user)
): ) -> Dict[str, Any]:
"""Claim accumulated rewards for multiple stakes""" """Claim accumulated rewards for multiple stakes"""
try: try:
# Verify ownership of all stakes # Verify ownership of all stakes
@@ -710,7 +710,7 @@ async def get_risk_assessment(
agent_wallet: str, agent_wallet: str,
session: Session = Depends(get_session), session: Session = Depends(get_session),
staking_service: StakingService = Depends(get_staking_service) staking_service: StakingService = Depends(get_staking_service)
): ) -> Dict[str, Any]:
"""Get risk assessment for staking on an agent""" """Get risk assessment for staking on an agent"""
try: try:
assessment = await staking_service.get_risk_assessment(agent_wallet) assessment = await staking_service.get_risk_assessment(agent_wallet)

View File

@@ -3,6 +3,9 @@
Web Vitals API endpoint for collecting performance metrics Web Vitals API endpoint for collecting performance metrics
""" """
import logging
from typing import Any
from fastapi import APIRouter, HTTPException from fastapi import APIRouter, HTTPException
from pydantic import BaseModel from pydantic import BaseModel
@@ -32,7 +35,7 @@ class WebVitalsMetric(BaseModel):
@router.post("/web-vitals") @router.post("/web-vitals")
async def collect_web_vitals(metric: WebVitalsMetric): async def collect_web_vitals(metric: WebVitalsMetric) -> dict[str, Any]:
""" """
Collect Web Vitals performance metrics from the frontend. Collect Web Vitals performance metrics from the frontend.
This endpoint receives Core Web Vitals (LCP, FID, CLS, TTFB, FCP) for monitoring. This endpoint receives Core Web Vitals (LCP, FID, CLS, TTFB, FCP) for monitoring.
@@ -70,6 +73,6 @@ async def collect_web_vitals(metric: WebVitalsMetric):
# Health check for web vitals endpoint # Health check for web vitals endpoint
@router.get("/web-vitals/health") @router.get("/web-vitals/health")
async def web_vitals_health(): async def web_vitals_health() -> dict[str, str]:
"""Health check for web vitals collection endpoint""" """Health check for web vitals collection endpoint"""
return {"status": "healthy", "service": "web-vitals"} return {"status": "healthy", "service": "web-vitals"}