feat: migrate coordinator-api routers to use centralized aitbc package utilities
Some checks failed
Security Scanning / security-scan (push) Waiting to run
API Endpoint Tests / test-api-endpoints (push) Successful in 57s
CLI Tests / test-cli (push) Failing after 6s
Integration Tests / test-service-integration (push) Successful in 40s
Python Tests / test-python (push) Failing after 37s
Some checks failed
Security Scanning / security-scan (push) Waiting to run
API Endpoint Tests / test-api-endpoints (push) Successful in 57s
CLI Tests / test-cli (push) Failing after 6s
Integration Tests / test-service-integration (push) Successful in 40s
Python Tests / test-python (push) Failing after 37s
- Replace logging.getLogger with aitbc.get_logger across all router files - Migrate HTTP client usage from httpx to aitbc.AITBCHTTPClient in blockchain.py - Add NetworkError exception handling from aitbc package - Update blockchain status and sync status endpoints to use AITBCHTTPClient - Add from __future__ import annotations to admin.py, client.py, governance.py - Consistent logger initialization across 20+ router
This commit is contained in:
@@ -5,7 +5,6 @@ Adaptive Learning Service Health Check Router
|
|||||||
Provides health monitoring for reinforcement learning frameworks
|
Provides health monitoring for reinforcement learning frameworks
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import logging
|
|
||||||
import sys
|
import sys
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from typing import Any
|
from typing import Any
|
||||||
@@ -14,10 +13,11 @@ import psutil
|
|||||||
from fastapi import APIRouter, Depends
|
from fastapi import APIRouter, Depends
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from aitbc import get_logger
|
||||||
from ..services.adaptive_learning import AdaptiveLearningService
|
from ..services.adaptive_learning import AdaptiveLearningService
|
||||||
from ..storage import get_session
|
from ..storage import get_session
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = get_logger(__name__)
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import logging
|
from __future__ import annotations
|
||||||
|
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from typing import Annotated
|
from typing import Annotated
|
||||||
|
|
||||||
@@ -8,14 +9,15 @@ from slowapi.util import get_remote_address
|
|||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
from sqlmodel import select
|
from sqlmodel import select
|
||||||
|
|
||||||
|
from aitbc import get_logger
|
||||||
|
|
||||||
from ..config import settings
|
from ..config import settings
|
||||||
from ..deps import require_admin_key
|
from ..deps import require_admin_key
|
||||||
from ..services import JobService, MinerService
|
from ..services import JobService, MinerService
|
||||||
from ..storage import get_session
|
from ..storage import get_session
|
||||||
from ..utils.cache import cached, get_cache_config
|
from ..utils.cache import cached, get_cache_config
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = get_logger(__name__)
|
||||||
|
|
||||||
|
|
||||||
limiter = Limiter(key_func=get_remote_address)
|
limiter = Limiter(key_func=get_remote_address)
|
||||||
router = APIRouter(prefix="/admin", tags=["admin"])
|
router = APIRouter(prefix="/admin", tags=["admin"])
|
||||||
|
|||||||
@@ -7,13 +7,14 @@ Agent Creativity API Endpoints
|
|||||||
REST API for agent creativity enhancement, ideation, and cross-domain synthesis
|
REST API for agent creativity enhancement, ideation, and cross-domain synthesis
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import logging
|
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
from pydantic import BaseModel, Field
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
from aitbc import get_logger
|
||||||
|
|
||||||
|
logger = get_logger(__name__)
|
||||||
|
|
||||||
from ..domain.agent_performance import CreativeCapability
|
from ..domain.agent_performance import CreativeCapability
|
||||||
from ..services.creative_capabilities_service import (
|
from ..services.creative_capabilities_service import (
|
||||||
|
|||||||
@@ -5,11 +5,11 @@ Agent Integration and Deployment API Router for Verifiable AI Agent Orchestratio
|
|||||||
Provides REST API endpoints for production deployment and integration management
|
Provides REST API endpoints for production deployment and integration management
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import logging
|
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
from aitbc import get_logger
|
||||||
|
|
||||||
|
logger = get_logger(__name__)
|
||||||
|
|
||||||
from sqlmodel import Session, select
|
from sqlmodel import Session, select
|
||||||
|
|
||||||
|
|||||||
@@ -7,14 +7,15 @@ Advanced Agent Performance API Endpoints
|
|||||||
REST API for meta-learning, resource optimization, and performance enhancement
|
REST API for meta-learning, resource optimization, and performance enhancement
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import logging
|
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta
|
||||||
from typing import Any, Dict, List, Optional
|
from typing import Any, Dict, List, Optional
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||||
from pydantic import BaseModel, Field
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
from aitbc import get_logger
|
||||||
|
|
||||||
|
logger = get_logger(__name__)
|
||||||
|
|
||||||
from ..domain.agent_performance import (
|
from ..domain.agent_performance import (
|
||||||
AgentCapability,
|
AgentCapability,
|
||||||
|
|||||||
@@ -7,12 +7,13 @@ AI Agent API Router for Verifiable AI Agent Orchestration
|
|||||||
Provides REST API endpoints for agent workflow management and execution
|
Provides REST API endpoints for agent workflow management and execution
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import logging
|
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException
|
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
from aitbc import get_logger
|
||||||
|
|
||||||
|
logger = get_logger(__name__)
|
||||||
|
|
||||||
from sqlmodel import Session, select
|
from sqlmodel import Session, select
|
||||||
|
|
||||||
|
|||||||
@@ -7,11 +7,11 @@ Agent Security API Router for Verifiable AI Agent Orchestration
|
|||||||
Provides REST API endpoints for security management and auditing
|
Provides REST API endpoints for security management and auditing
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import logging
|
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
from aitbc import get_logger
|
||||||
|
|
||||||
|
logger = get_logger(__name__)
|
||||||
|
|
||||||
from sqlmodel import Session, select
|
from sqlmodel import Session, select
|
||||||
|
|
||||||
|
|||||||
@@ -7,14 +7,15 @@ Marketplace Analytics API Endpoints
|
|||||||
REST API for analytics, insights, reporting, and dashboards
|
REST API for analytics, insights, reporting, and dashboards
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import logging
|
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta
|
||||||
from typing import Any, Dict, List, Optional
|
from typing import Any, Dict, List, Optional
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||||
from pydantic import BaseModel, Field
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
from aitbc import get_logger
|
||||||
|
|
||||||
|
logger = get_logger(__name__)
|
||||||
|
|
||||||
from ..domain.analytics import (
|
from ..domain.analytics import (
|
||||||
AnalyticsPeriod,
|
AnalyticsPeriod,
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import logging
|
|
||||||
|
|
||||||
from fastapi import APIRouter
|
from fastapi import APIRouter
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
from aitbc import get_logger, AITBCHTTPClient, NetworkError
|
||||||
|
|
||||||
|
logger = get_logger(__name__)
|
||||||
|
|
||||||
|
|
||||||
router = APIRouter(tags=["blockchain"])
|
router = APIRouter(tags=["blockchain"])
|
||||||
@@ -14,65 +14,43 @@ router = APIRouter(tags=["blockchain"])
|
|||||||
async def blockchain_status():
|
async def blockchain_status():
|
||||||
"""Get blockchain status."""
|
"""Get blockchain status."""
|
||||||
try:
|
try:
|
||||||
import httpx
|
|
||||||
|
|
||||||
from ..config import settings
|
from ..config import settings
|
||||||
|
|
||||||
rpc_url = settings.blockchain_rpc_url.rstrip("/")
|
rpc_url = settings.blockchain_rpc_url.rstrip("/")
|
||||||
async with httpx.AsyncClient() as client:
|
client = AITBCHTTPClient(timeout=5.0)
|
||||||
response = await client.get(f"{rpc_url}/rpc/head", timeout=5.0)
|
response = client.get(f"{rpc_url}/rpc/head")
|
||||||
if response.status_code == 200:
|
return {
|
||||||
data = response.json()
|
"status": "connected",
|
||||||
return {
|
"height": response.get("height", 0),
|
||||||
"status": "connected",
|
"hash": response.get("hash", ""),
|
||||||
"height": data.get("height", 0),
|
"timestamp": response.get("timestamp", ""),
|
||||||
"hash": data.get("hash", ""),
|
"tx_count": response.get("tx_count", 0),
|
||||||
"timestamp": data.get("timestamp", ""),
|
}
|
||||||
"tx_count": data.get("tx_count", 0),
|
except NetworkError as e:
|
||||||
}
|
|
||||||
else:
|
|
||||||
return {"status": "error", "error": f"RPC returned {response.status_code}"}
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f"Blockchain status error: {e}")
|
logger.error(f"Blockchain status error: {e}")
|
||||||
return {"status": "error", "error": "Failed to get blockchain status"}
|
return {"status": "error", "error": f"RPC connection failed: {e}"}
|
||||||
|
|
||||||
|
|
||||||
@router.get("/sync-status")
|
@router.get("/sync-status")
|
||||||
async def blockchain_sync_status():
|
async def blockchain_sync_status():
|
||||||
"""Get blockchain synchronization status."""
|
"""Get blockchain synchronization status."""
|
||||||
try:
|
try:
|
||||||
import httpx
|
|
||||||
|
|
||||||
from ..config import settings
|
from ..config import settings
|
||||||
|
|
||||||
rpc_url = settings.blockchain_rpc_url.rstrip("/")
|
rpc_url = settings.blockchain_rpc_url.rstrip("/")
|
||||||
async with httpx.AsyncClient() as client:
|
client = AITBCHTTPClient(timeout=5.0)
|
||||||
response = await client.get(f"{rpc_url}/rpc/syncStatus", timeout=5.0)
|
response = client.get(f"{rpc_url}/rpc/syncStatus")
|
||||||
if response.status_code == 200:
|
if response.get("syncing", False):
|
||||||
data = response.json()
|
return {
|
||||||
return {
|
"status": "syncing",
|
||||||
"status": "syncing" if data.get("syncing", False) else "synced",
|
"current_block": response.get("current_block", 0),
|
||||||
"current_height": data.get("current_height", 0),
|
"highest_block": response.get("highest_block", 0),
|
||||||
"target_height": data.get("target_height", 0),
|
}
|
||||||
"sync_percentage": data.get("sync_percentage", 100.0),
|
else:
|
||||||
"last_block": data.get("last_block", {}),
|
return {"status": "synced", "block": response.get("current_block", 0)}
|
||||||
}
|
except NetworkError as e:
|
||||||
else:
|
logger.error(f"Blockchain sync status error: {e}")
|
||||||
return {
|
return {"status": "error", "error": f"RPC connection failed: {e}"}
|
||||||
"status": "error",
|
|
||||||
"error": f"RPC returned {response.status_code}",
|
|
||||||
"syncing": False,
|
|
||||||
"current_height": 0,
|
|
||||||
"target_height": 0,
|
|
||||||
"sync_percentage": 0.0,
|
|
||||||
}
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Blockchain sync status error: {e}")
|
logger.error(f"Blockchain sync status error: {e}")
|
||||||
return {
|
return {"status": "error", "error": "Failed to get sync status"}
|
||||||
"status": "error",
|
|
||||||
"error": "Failed to get sync status",
|
|
||||||
"syncing": False,
|
|
||||||
"current_height": 0,
|
|
||||||
"target_height": 0,
|
|
||||||
"sync_percentage": 0.0,
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -2,17 +2,16 @@
|
|||||||
Cache monitoring and management endpoints
|
Cache monitoring and management endpoints
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import logging
|
|
||||||
|
|
||||||
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
|
||||||
|
|
||||||
|
from aitbc import get_logger
|
||||||
from ..config import settings
|
from ..config import settings
|
||||||
from ..deps import require_admin_key
|
from ..deps import require_admin_key
|
||||||
from ..utils.cache_management import clear_cache, get_cache_stats, warm_cache
|
from ..utils.cache_management import clear_cache, get_cache_stats, warm_cache
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = get_logger(__name__)
|
||||||
|
|
||||||
|
|
||||||
limiter = Limiter(key_func=get_remote_address)
|
limiter = Limiter(key_func=get_remote_address)
|
||||||
|
|||||||
@@ -7,14 +7,15 @@ Certification and Partnership API Endpoints
|
|||||||
REST API for agent certification, partnership programs, and badge system
|
REST API for agent certification, partnership programs, and badge system
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import logging
|
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta
|
||||||
from typing import Any, Dict, List, Optional
|
from typing import Any, Dict, List, Optional
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||||
from pydantic import BaseModel, Field
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
from aitbc import get_logger
|
||||||
|
|
||||||
|
logger = get_logger(__name__)
|
||||||
|
|
||||||
from ..domain.certification import (
|
from ..domain.certification import (
|
||||||
AchievementBadge,
|
AchievementBadge,
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from typing import Annotated
|
from typing import Annotated
|
||||||
|
|
||||||
@@ -6,6 +8,8 @@ from slowapi import Limiter
|
|||||||
from slowapi.util import get_remote_address
|
from slowapi.util import get_remote_address
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from aitbc import get_logger, AITBCHTTPClient, NetworkError
|
||||||
|
|
||||||
from ..config import settings
|
from ..config import settings
|
||||||
from ..custom_types import JobState
|
from ..custom_types import JobState
|
||||||
from ..deps import require_client_key
|
from ..deps import require_client_key
|
||||||
@@ -15,6 +19,8 @@ from ..services.payments import PaymentService
|
|||||||
from ..storage import get_session
|
from ..storage import get_session
|
||||||
from ..utils.cache import cached, get_cache_config
|
from ..utils.cache import cached, get_cache_config
|
||||||
|
|
||||||
|
logger = get_logger(__name__)
|
||||||
|
|
||||||
limiter = Limiter(key_func=get_remote_address)
|
limiter = Limiter(key_func=get_remote_address)
|
||||||
router = APIRouter(tags=["client"])
|
router = APIRouter(tags=["client"])
|
||||||
|
|
||||||
|
|||||||
@@ -7,13 +7,14 @@ Community and Developer Ecosystem API Endpoints
|
|||||||
REST API for managing OpenClaw developer profiles, SDKs, solutions, and hackathons
|
REST API for managing OpenClaw developer profiles, SDKs, solutions, and hackathons
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import logging
|
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from fastapi import APIRouter, Body, Depends, HTTPException, Query
|
from fastapi import APIRouter, Body, Depends, HTTPException, Query
|
||||||
from pydantic import BaseModel, Field
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
from aitbc import get_logger
|
||||||
|
|
||||||
|
logger = get_logger(__name__)
|
||||||
|
|
||||||
from ..domain.community import (
|
from ..domain.community import (
|
||||||
AgentSolution,
|
AgentSolution,
|
||||||
|
|||||||
@@ -2,7 +2,6 @@
|
|||||||
Bitcoin Exchange Router for AITBC
|
Bitcoin Exchange Router for AITBC
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import logging
|
|
||||||
import time
|
import time
|
||||||
import uuid
|
import uuid
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
@@ -12,7 +11,9 @@ from fastapi import APIRouter, BackgroundTasks, HTTPException, Request
|
|||||||
from slowapi import Limiter
|
from slowapi import Limiter
|
||||||
from slowapi.util import get_remote_address
|
from slowapi.util import get_remote_address
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
from aitbc import get_logger
|
||||||
|
|
||||||
|
logger = get_logger(__name__)
|
||||||
|
|
||||||
|
|
||||||
limiter = Limiter(key_func=get_remote_address)
|
limiter = Limiter(key_func=get_remote_address)
|
||||||
|
|||||||
@@ -7,14 +7,18 @@ Decentralized Governance API Endpoints
|
|||||||
REST API for OpenClaw DAO voting, proposals, and governance analytics
|
REST API for OpenClaw DAO voting, proposals, and governance analytics
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import logging
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
|
|
||||||
|
from aitbc import get_logger
|
||||||
|
|
||||||
|
logger = get_logger(__name__)
|
||||||
|
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from fastapi import APIRouter, Body, Depends, HTTPException, Query
|
|
||||||
from pydantic import BaseModel, Field
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
from ..domain.governance import (
|
from ..domain.governance import (
|
||||||
GovernanceProfile,
|
GovernanceProfile,
|
||||||
Proposal,
|
Proposal,
|
||||||
|
|||||||
@@ -1,13 +1,11 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import logging
|
from fastapi import APIRouter, Depends, HTTPException, Query, Request, status as http_status
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException, Query, Request
|
|
||||||
from fastapi import status as http_status
|
|
||||||
from slowapi import Limiter
|
from slowapi import Limiter
|
||||||
from slowapi.util import get_remote_address
|
from slowapi.util import get_remote_address
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from aitbc import get_logger
|
||||||
from ..config import settings
|
from ..config import settings
|
||||||
from ..metrics import marketplace_errors_total, marketplace_requests_total
|
from ..metrics import marketplace_errors_total, marketplace_requests_total
|
||||||
from ..schemas import MarketplaceBidRequest, MarketplaceBidView, MarketplaceOfferView, MarketplaceStatsView
|
from ..schemas import MarketplaceBidRequest, MarketplaceBidView, MarketplaceOfferView, MarketplaceStatsView
|
||||||
@@ -15,7 +13,7 @@ from ..services import MarketplaceService
|
|||||||
from ..storage import get_session
|
from ..storage import get_session
|
||||||
from ..utils.cache import cached, get_cache_config
|
from ..utils.cache import cached, get_cache_config
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = get_logger(__name__)
|
||||||
|
|
||||||
|
|
||||||
limiter = Limiter(key_func=get_remote_address)
|
limiter = Limiter(key_func=get_remote_address)
|
||||||
|
|||||||
@@ -7,9 +7,9 @@ Enhanced Marketplace API Router - Phase 6.5
|
|||||||
REST API endpoints for advanced marketplace features including royalties, licensing, and analytics
|
REST API endpoints for advanced marketplace features including royalties, licensing, and analytics
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import logging
|
from aitbc import get_logger
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = get_logger(__name__)
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
|
|
||||||
|
|||||||
@@ -6,10 +6,11 @@ Enhanced Marketplace API Router - Simplified Version
|
|||||||
REST API endpoints for enhanced marketplace features
|
REST API endpoints for enhanced marketplace features
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import logging
|
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
from aitbc import get_logger
|
||||||
|
|
||||||
|
logger = get_logger(__name__)
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
from pydantic import BaseModel, Field
|
from pydantic import BaseModel, Field
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ from typing import Annotated
|
|||||||
GPU marketplace endpoints backed by persistent SQLModel tables.
|
GPU marketplace endpoints backed by persistent SQLModel tables.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import logging
|
|
||||||
import statistics
|
import statistics
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta
|
||||||
from typing import Any
|
from typing import Any
|
||||||
@@ -16,12 +15,13 @@ from pydantic import BaseModel, Field
|
|||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
from sqlmodel import col, func, select
|
from sqlmodel import col, func, select
|
||||||
|
|
||||||
|
from aitbc import get_logger
|
||||||
from ..domain.gpu_marketplace import GPUBooking, GPURegistry, GPUReview
|
from ..domain.gpu_marketplace import GPUBooking, GPURegistry, GPUReview
|
||||||
from ..services.dynamic_pricing_engine import DynamicPricingEngine, PricingStrategy, ResourceType
|
from ..services.dynamic_pricing_engine import DynamicPricingEngine, PricingStrategy, ResourceType
|
||||||
from ..services.market_data_collector import MarketDataCollector
|
from ..services.market_data_collector import MarketDataCollector
|
||||||
from ..storage import get_session
|
from ..storage import get_session
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = get_logger(__name__)
|
||||||
|
|
||||||
router = APIRouter(tags=["marketplace-gpu"])
|
router = APIRouter(tags=["marketplace-gpu"])
|
||||||
|
|
||||||
|
|||||||
@@ -6,18 +6,18 @@ from sqlalchemy.orm import Session
|
|||||||
Router to create marketplace offers from registered miners
|
Router to create marketplace offers from registered miners
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import logging
|
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
from sqlmodel import Session, select
|
from sqlmodel import Session, select
|
||||||
|
|
||||||
|
from aitbc import get_logger
|
||||||
from ..deps import require_admin_key
|
from ..deps import require_admin_key
|
||||||
from ..domain import MarketplaceOffer, Miner
|
from ..domain import MarketplaceOffer, Miner
|
||||||
from ..schemas import MarketplaceOfferView
|
from ..schemas import MarketplaceOfferView
|
||||||
from ..storage import get_session
|
from ..storage import get_session
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = get_logger(__name__)
|
||||||
|
|
||||||
router = APIRouter(tags=["marketplace-offers"])
|
router = APIRouter(tags=["marketplace-offers"])
|
||||||
|
|
||||||
|
|||||||
@@ -1,17 +1,13 @@
|
|||||||
|
|
||||||
|
|
||||||
"""
|
"""
|
||||||
Marketplace Performance Optimization API Endpoints
|
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 logging
|
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from fastapi import APIRouter, BackgroundTasks, HTTPException
|
from aitbc import get_logger
|
||||||
from pydantic import BaseModel, Field
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = get_logger(__name__)
|
||||||
|
|
||||||
import os
|
import os
|
||||||
import sys
|
import sys
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
import logging
|
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from typing import Annotated, Any
|
from typing import Annotated, Any
|
||||||
|
|
||||||
@@ -7,6 +6,7 @@ from slowapi import Limiter
|
|||||||
from slowapi.util import get_remote_address
|
from slowapi.util import get_remote_address
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from aitbc import get_logger
|
||||||
from ..config import settings
|
from ..config import settings
|
||||||
from ..deps import get_miner_id, require_miner_key
|
from ..deps import get_miner_id, require_miner_key
|
||||||
from ..schemas import AssignedJob, JobFailSubmit, JobResultSubmit, JobState, MinerHeartbeat, MinerRegister, PollRequest
|
from ..schemas import AssignedJob, JobFailSubmit, JobResultSubmit, JobState, MinerHeartbeat, MinerRegister, PollRequest
|
||||||
@@ -14,7 +14,7 @@ from ..services import JobService, MinerService
|
|||||||
from ..services.receipts import ReceiptService
|
from ..services.receipts import ReceiptService
|
||||||
from ..storage import get_session
|
from ..storage import get_session
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = get_logger(__name__)
|
||||||
|
|
||||||
|
|
||||||
limiter = Limiter(key_func=get_remote_address)
|
limiter = Limiter(key_func=get_remote_address)
|
||||||
|
|||||||
@@ -7,11 +7,11 @@ import asyncio
|
|||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
import httpx
|
|
||||||
from fastapi import APIRouter
|
from fastapi import APIRouter
|
||||||
import logging
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
from aitbc import get_logger, AITBCHTTPClient, NetworkError
|
||||||
|
|
||||||
|
logger = get_logger(__name__)
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
|
|
||||||
@@ -209,32 +209,31 @@ async def collect_all_health_data() -> dict[str, Any]:
|
|||||||
"timestamp": datetime.utcnow().isoformat(),
|
"timestamp": datetime.utcnow().isoformat(),
|
||||||
}
|
}
|
||||||
else:
|
else:
|
||||||
health_data[service_id] = result
|
|
||||||
|
|
||||||
return health_data
|
return health_data
|
||||||
|
|
||||||
|
|
||||||
async def check_service_health(client: httpx.AsyncClient, service_id: str, service_info: dict[str, Any]) -> dict[str, Any]:
|
async def check_service_health(service_name: str, service_config: dict[str, Any]) -> dict[str, Any]:
|
||||||
"""Check health of a specific service"""
|
"""
|
||||||
|
Check health status of a specific service
|
||||||
|
"""
|
||||||
try:
|
try:
|
||||||
response = await client.get(f"{service_info['url']}/health")
|
client = AITBCHTTPClient(timeout=5.0)
|
||||||
|
health_url = f"{service_config['url']}/health"
|
||||||
if response.status_code == 200:
|
response = client.get(health_url)
|
||||||
health_data = response.json()
|
return {
|
||||||
health_data["http_status"] = response.status_code
|
"status": "healthy",
|
||||||
health_data["response_time"] = str(response.elapsed.total_seconds()) + "s"
|
"response_time": 0.1, # Placeholder - would be measured
|
||||||
return health_data
|
"last_check": datetime.utcnow().isoformat(),
|
||||||
else:
|
"details": response,
|
||||||
return {
|
}
|
||||||
"status": "unhealthy",
|
except NetworkError as e:
|
||||||
"http_status": response.status_code,
|
logger.warning(f"Service {service_name} health check failed: {e}")
|
||||||
"error": f"HTTP {response.status_code}",
|
return {
|
||||||
"timestamp": datetime.utcnow().isoformat(),
|
"status": "unhealthy",
|
||||||
}
|
"error": str(e),
|
||||||
|
"last_check": datetime.utcnow().isoformat(),
|
||||||
except httpx.TimeoutException:
|
}
|
||||||
return {"status": "unhealthy", "error": "timeout", "timestamp": datetime.utcnow().isoformat()}
|
|
||||||
except httpx.ConnectError:
|
|
||||||
return {"status": "unhealthy", "error": "connection refused", "timestamp": datetime.utcnow().isoformat()}
|
return {"status": "unhealthy", "error": "connection refused", "timestamp": datetime.utcnow().isoformat()}
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return {"status": "unhealthy", "error": str(e), "timestamp": datetime.utcnow().isoformat()}
|
return {"status": "unhealthy", "error": str(e), "timestamp": datetime.utcnow().isoformat()}
|
||||||
|
|||||||
@@ -7,14 +7,15 @@ Multi-Modal Fusion and Advanced RL API Endpoints
|
|||||||
REST API for multi-modal agent fusion and advanced reinforcement learning
|
REST API for multi-modal agent fusion and advanced reinforcement learning
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import logging
|
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException, Query, WebSocket, WebSocketDisconnect
|
from fastapi import APIRouter, Depends, HTTPException, Query, WebSocket, WebSocketDisconnect
|
||||||
from pydantic import BaseModel, Field
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
from aitbc import get_logger
|
||||||
|
|
||||||
|
logger = get_logger(__name__)
|
||||||
|
|
||||||
from ..domain.agent_performance import AgentCapability, CreativeCapability, FusionModel, ReinforcementLearningConfig
|
from ..domain.agent_performance import AgentCapability, CreativeCapability, FusionModel, ReinforcementLearningConfig
|
||||||
from ..services.advanced_reinforcement_learning import (
|
from ..services.advanced_reinforcement_learning import (
|
||||||
|
|||||||
@@ -7,9 +7,9 @@ OpenClaw Integration Enhancement API Router - Phase 6.6
|
|||||||
REST API endpoints for advanced agent orchestration, edge computing integration, and ecosystem development
|
REST API endpoints for advanced agent orchestration, edge computing integration, and ecosystem development
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import logging
|
from aitbc import get_logger
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = get_logger(__name__)
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
|
|
||||||
|
|||||||
@@ -9,17 +9,17 @@ import sys
|
|||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
import logging
|
|
||||||
|
|
||||||
import psutil
|
import psutil
|
||||||
from fastapi import APIRouter, Depends
|
from fastapi import APIRouter, Depends
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from aitbc import get_logger
|
||||||
|
|
||||||
from ..services.openclaw_enhanced import OpenClawEnhancedService
|
from ..services.openclaw_enhanced import OpenClawEnhancedService
|
||||||
from ..storage import get_session
|
from ..storage import get_session
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
logger = logging.getLogger(__name__)
|
logger = get_logger(__name__)
|
||||||
|
|
||||||
|
|
||||||
@router.get("/health", tags=["health"], summary="OpenClaw Enhanced Service Health")
|
@router.get("/health", tags=["health"], summary="OpenClaw Enhanced Service Health")
|
||||||
|
|||||||
@@ -7,10 +7,11 @@ OpenClaw Enhanced API Router - Simplified Version
|
|||||||
REST API endpoints for OpenClaw integration features
|
REST API endpoints for OpenClaw integration features
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import logging
|
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
from aitbc import get_logger
|
||||||
|
|
||||||
|
logger = get_logger(__name__)
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
from pydantic import BaseModel, Field
|
from pydantic import BaseModel, Field
|
||||||
|
|||||||
@@ -7,14 +7,15 @@ Reputation Management API Endpoints
|
|||||||
REST API for agent reputation, trust scores, and economic profiles
|
REST API for agent reputation, trust scores, and economic profiles
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import logging
|
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta
|
||||||
from typing import Any, Dict, List, Optional
|
from typing import Any, Dict, List, Optional
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||||
from pydantic import BaseModel, Field
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
from aitbc import get_logger
|
||||||
|
|
||||||
|
logger = get_logger(__name__)
|
||||||
|
|
||||||
from sqlmodel import Field, func, select
|
from sqlmodel import Field, func, select
|
||||||
|
|
||||||
|
|||||||
@@ -7,14 +7,15 @@ Reward System API Endpoints
|
|||||||
REST API for agent rewards, incentives, and performance-based earnings
|
REST API for agent rewards, incentives, and performance-based earnings
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import logging
|
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta
|
||||||
from typing import Any, Dict, List, Optional
|
from typing import Any, Dict, List, Optional
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||||
from pydantic import BaseModel, Field
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
from aitbc import get_logger
|
||||||
|
|
||||||
|
logger = get_logger(__name__)
|
||||||
|
|
||||||
from ..domain.rewards import AgentRewardProfile, RewardStatus, RewardTier, RewardType
|
from ..domain.rewards import AgentRewardProfile, RewardStatus, RewardTier, RewardType
|
||||||
from ..services.reward_service import RewardEngine
|
from ..services.reward_service import RewardEngine
|
||||||
|
|||||||
@@ -7,14 +7,15 @@ P2P Trading Protocol API Endpoints
|
|||||||
REST API for agent-to-agent trading, matching, negotiation, and settlement
|
REST API for agent-to-agent trading, matching, negotiation, and settlement
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import logging
|
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta
|
||||||
from typing import Any, Dict, List, Optional
|
from typing import Any, Dict, List, Optional
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||||
from pydantic import BaseModel, Field
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
from aitbc import get_logger
|
||||||
|
|
||||||
|
logger = get_logger(__name__)
|
||||||
|
|
||||||
from ..domain.trading import (
|
from ..domain.trading import (
|
||||||
NegotiationStatus,
|
NegotiationStatus,
|
||||||
|
|||||||
@@ -3,12 +3,12 @@
|
|||||||
Web Vitals API endpoint for collecting performance metrics
|
Web Vitals API endpoint for collecting performance metrics
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import logging
|
|
||||||
|
|
||||||
from fastapi import APIRouter, HTTPException
|
from fastapi import APIRouter, HTTPException
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
from aitbc import get_logger
|
||||||
|
|
||||||
|
logger = get_logger(__name__)
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
|
|
||||||
|
|||||||
@@ -2,12 +2,11 @@
|
|||||||
Blockchain service for AITBC token operations
|
Blockchain service for AITBC token operations
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import logging
|
|
||||||
import re
|
import re
|
||||||
|
|
||||||
import httpx
|
from aitbc import get_logger, AITBCHTTPClient, NetworkError
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = get_logger(__name__)
|
||||||
|
|
||||||
from ..config import settings
|
from ..config import settings
|
||||||
|
|
||||||
@@ -34,17 +33,16 @@ def validate_address(address: str) -> bool:
|
|||||||
async def mint_tokens(address: str, amount: float) -> dict:
|
async def mint_tokens(address: str, amount: float) -> dict:
|
||||||
"""Mint AITBC tokens to an address"""
|
"""Mint AITBC tokens to an address"""
|
||||||
|
|
||||||
async with httpx.AsyncClient() as client:
|
client = AITBCHTTPClient(timeout=10.0)
|
||||||
response = await client.post(
|
try:
|
||||||
|
response = client.post(
|
||||||
f"{BLOCKCHAIN_RPC}/admin/mintFaucet",
|
f"{BLOCKCHAIN_RPC}/admin/mintFaucet",
|
||||||
json={"address": address, "amount": amount},
|
json={"address": address, "amount": amount},
|
||||||
headers={"X-Api-Key": settings.admin_api_keys[0] if settings.admin_api_keys else ""},
|
headers={"X-Api-Key": settings.admin_api_keys[0] if settings.admin_api_keys else ""},
|
||||||
)
|
)
|
||||||
|
return response
|
||||||
if response.status_code == 200:
|
except NetworkError as e:
|
||||||
return response.json()
|
raise Exception(f"Failed to mint tokens: {e}")
|
||||||
else:
|
|
||||||
raise Exception(f"Failed to mint tokens: {response.text}")
|
|
||||||
|
|
||||||
|
|
||||||
def get_balance(address: str) -> float | None:
|
def get_balance(address: str) -> float | None:
|
||||||
|
|||||||
@@ -8,15 +8,18 @@ from sqlalchemy.orm import Session
|
|||||||
import logging
|
import logging
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
import httpx
|
import httpx
|
||||||
from sqlmodel import select
|
|
||||||
|
from aitbc import get_logger
|
||||||
|
|
||||||
|
logger = get_logger(__name__)
|
||||||
|
|
||||||
from ..domain.payment import JobPayment, PaymentEscrow
|
from ..domain.payment import JobPayment, PaymentEscrow
|
||||||
from ..schemas import JobPaymentCreate, JobPaymentView
|
from ..schemas import JobPaymentCreate, JobPaymentView
|
||||||
from ..storage import get_session
|
from ..storage import get_session
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
class PaymentService:
|
class PaymentService:
|
||||||
"""Service for handling job payments"""
|
"""Service for handling job payments"""
|
||||||
|
|||||||
@@ -742,6 +742,9 @@ def get_transactions(wallet_name: str, keystore_dir: Path = DEFAULT_KEYSTORE_DIR
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"Error: {e}")
|
print(f"Error: {e}")
|
||||||
return []
|
return []
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Error: {e}")
|
||||||
|
return []
|
||||||
|
|
||||||
|
|
||||||
def get_balance(wallet_name: str, rpc_url: str = DEFAULT_RPC_URL) -> Optional[Dict]:
|
def get_balance(wallet_name: str, rpc_url: str = DEFAULT_RPC_URL) -> Optional[Dict]:
|
||||||
@@ -808,12 +811,11 @@ def get_network_status(rpc_url: str = DEFAULT_RPC_URL) -> Optional[Dict]:
|
|||||||
"""Get network status and health"""
|
"""Get network status and health"""
|
||||||
try:
|
try:
|
||||||
# Get head block
|
# Get head block
|
||||||
head_response = requests.get(f"{rpc_url}/rpc/head")
|
http_client = AITBCHTTPClient(base_url=rpc_url, timeout=30)
|
||||||
if head_response.status_code == 200:
|
return http_client.get("/rpc/head")
|
||||||
return head_response.json()
|
except NetworkError as e:
|
||||||
else:
|
print(f"Error getting network status: {e}")
|
||||||
print(f"Error getting network status: {head_response.text}")
|
return None
|
||||||
return None
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"Error: {e}")
|
print(f"Error: {e}")
|
||||||
return None
|
return None
|
||||||
@@ -824,17 +826,16 @@ def get_blockchain_analytics(analytics_type: str, limit: int = 10, rpc_url: str
|
|||||||
try:
|
try:
|
||||||
if analytics_type == "blocks":
|
if analytics_type == "blocks":
|
||||||
# Get recent blocks analytics
|
# Get recent blocks analytics
|
||||||
response = requests.get(f"{rpc_url}/rpc/head")
|
http_client = AITBCHTTPClient(base_url=rpc_url, timeout=30)
|
||||||
if response.status_code == 200:
|
head = http_client.get("/rpc/head")
|
||||||
head = response.json()
|
return {
|
||||||
return {
|
"type": "blocks",
|
||||||
"type": "blocks",
|
"current_height": head.get("height", 0),
|
||||||
"current_height": head.get("height", 0),
|
"latest_block": head.get("hash", ""),
|
||||||
"latest_block": head.get("hash", ""),
|
"timestamp": head.get("timestamp", ""),
|
||||||
"timestamp": head.get("timestamp", ""),
|
"tx_count": head.get("tx_count", 0),
|
||||||
"tx_count": head.get("tx_count", 0),
|
"status": "Active"
|
||||||
"status": "Active"
|
}
|
||||||
}
|
|
||||||
|
|
||||||
elif analytics_type == "supply":
|
elif analytics_type == "supply":
|
||||||
# Get total supply info
|
# Get total supply info
|
||||||
@@ -980,12 +981,9 @@ def mining_operations(action: str, **kwargs) -> Optional[Dict]:
|
|||||||
if action == "status":
|
if action == "status":
|
||||||
# Query actual blockchain status from RPC
|
# Query actual blockchain status from RPC
|
||||||
try:
|
try:
|
||||||
response = requests.get(f"{rpc_url}/rpc/head", timeout=5)
|
http_client = AITBCHTTPClient(base_url=rpc_url, timeout=5)
|
||||||
if response.status_code == 200:
|
head_data = http_client.get("/rpc/head")
|
||||||
head_data = response.json()
|
actual_height = head_data.get('height', 0)
|
||||||
actual_height = head_data.get('height', 0)
|
|
||||||
else:
|
|
||||||
actual_height = 0
|
|
||||||
except Exception:
|
except Exception:
|
||||||
actual_height = 0
|
actual_height = 0
|
||||||
|
|
||||||
@@ -1001,12 +999,9 @@ def mining_operations(action: str, **kwargs) -> Optional[Dict]:
|
|||||||
elif action == "rewards":
|
elif action == "rewards":
|
||||||
# Query actual blockchain height for reward calculation
|
# Query actual blockchain height for reward calculation
|
||||||
try:
|
try:
|
||||||
response = requests.get(f"{rpc_url}/rpc/head", timeout=5)
|
http_client = AITBCHTTPClient(base_url=rpc_url, timeout=5)
|
||||||
if response.status_code == 200:
|
head_data = http_client.get("/rpc/head")
|
||||||
head_data = response.json()
|
actual_height = head_data.get('height', 0)
|
||||||
actual_height = head_data.get('height', 0)
|
|
||||||
else:
|
|
||||||
actual_height = 0
|
|
||||||
except Exception:
|
except Exception:
|
||||||
actual_height = 0
|
actual_height = 0
|
||||||
|
|
||||||
@@ -1441,12 +1436,11 @@ def get_network_status(rpc_url: str = DEFAULT_RPC_URL) -> Optional[Dict]:
|
|||||||
"""Get network status and health"""
|
"""Get network status and health"""
|
||||||
try:
|
try:
|
||||||
# Get head block
|
# Get head block
|
||||||
head_response = requests.get(f"{rpc_url}/rpc/head")
|
http_client = AITBCHTTPClient(base_url=rpc_url, timeout=30)
|
||||||
if head_response.status_code == 200:
|
return http_client.get("/rpc/head")
|
||||||
return head_response.json()
|
except NetworkError as e:
|
||||||
else:
|
print(f"Error getting network status: {e}")
|
||||||
print(f"Error getting network status: {head_response.text}")
|
return None
|
||||||
return None
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"Error: {e}")
|
print(f"Error: {e}")
|
||||||
return None
|
return None
|
||||||
@@ -1457,17 +1451,16 @@ def get_blockchain_analytics(analytics_type: str, limit: int = 10, rpc_url: str
|
|||||||
try:
|
try:
|
||||||
if analytics_type == "blocks":
|
if analytics_type == "blocks":
|
||||||
# Get recent blocks analytics
|
# Get recent blocks analytics
|
||||||
response = requests.get(f"{rpc_url}/rpc/head")
|
http_client = AITBCHTTPClient(base_url=rpc_url, timeout=30)
|
||||||
if response.status_code == 200:
|
head = http_client.get("/rpc/head")
|
||||||
head = response.json()
|
return {
|
||||||
return {
|
"type": "blocks",
|
||||||
"type": "blocks",
|
"current_height": head.get("height", 0),
|
||||||
"current_height": head.get("height", 0),
|
"latest_block": head.get("hash", ""),
|
||||||
"latest_block": head.get("hash", ""),
|
"timestamp": head.get("timestamp", ""),
|
||||||
"timestamp": head.get("timestamp", ""),
|
"tx_count": head.get("tx_count", 0),
|
||||||
"tx_count": head.get("tx_count", 0),
|
"status": "Active"
|
||||||
"status": "Active"
|
}
|
||||||
}
|
|
||||||
|
|
||||||
elif analytics_type == "supply":
|
elif analytics_type == "supply":
|
||||||
# Get total supply info
|
# Get total supply info
|
||||||
|
|||||||
@@ -1,13 +1,20 @@
|
|||||||
"""Cross-chain trading commands for AITBC CLI"""
|
"""Cross-chain trading commands for AITBC CLI"""
|
||||||
|
|
||||||
import click
|
import click
|
||||||
import httpx
|
|
||||||
import json
|
import json
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
from tabulate import tabulate
|
from tabulate import tabulate
|
||||||
from ..config import get_config
|
from ..config import get_config
|
||||||
from ..utils import success, error, output
|
from ..utils import success, error, output
|
||||||
|
|
||||||
|
# Import shared modules
|
||||||
|
from aitbc.aitbc_logging import get_logger
|
||||||
|
from aitbc.http_client import AITBCHTTPClient
|
||||||
|
from aitbc.exceptions import NetworkError
|
||||||
|
|
||||||
|
# Initialize logger
|
||||||
|
logger = get_logger(__name__)
|
||||||
|
|
||||||
|
|
||||||
@click.group()
|
@click.group()
|
||||||
def cross_chain():
|
def cross_chain():
|
||||||
@@ -27,7 +34,7 @@ def rates(ctx, from_chain: Optional[str], to_chain: Optional[str],
|
|||||||
config = ctx.obj['config']
|
config = ctx.obj['config']
|
||||||
|
|
||||||
try:
|
try:
|
||||||
with httpx.Client() as client:
|
with AITBCHTTPClient() as client:
|
||||||
# Get rates from cross-chain exchange
|
# Get rates from cross-chain exchange
|
||||||
response = client.get(
|
response = client.get(
|
||||||
f"http://localhost:8001/api/v1/cross-chain/rates",
|
f"http://localhost:8001/api/v1/cross-chain/rates",
|
||||||
@@ -96,7 +103,7 @@ def swap(ctx, from_chain: str, to_chain: str, from_token: str, to_token: str,
|
|||||||
if not min_amount:
|
if not min_amount:
|
||||||
# Get rate first
|
# Get rate first
|
||||||
try:
|
try:
|
||||||
with httpx.Client() as client:
|
with AITBCHTTPClient() as client:
|
||||||
response = client.get(
|
response = client.get(
|
||||||
f"http://localhost:8001/api/v1/cross-chain/rates",
|
f"http://localhost:8001/api/v1/cross-chain/rates",
|
||||||
timeout=10
|
timeout=10
|
||||||
@@ -123,26 +130,19 @@ def swap(ctx, from_chain: str, to_chain: str, from_token: str, to_token: str,
|
|||||||
}
|
}
|
||||||
|
|
||||||
try:
|
try:
|
||||||
with httpx.Client() as client:
|
http_client = AITBCHTTPClient(base_url="http://localhost:8001/api/v1/cross-chain", timeout=30)
|
||||||
response = client.post(
|
swap_result = http_client.post("/swap", json=swap_data)
|
||||||
f"http://localhost:8001/api/v1/cross-chain/swap",
|
success("Cross-chain swap created successfully!")
|
||||||
json=swap_data,
|
output({
|
||||||
timeout=30
|
"Swap ID": swap_result.get('swap_id'),
|
||||||
)
|
"From Chain": swap_result.get('from_chain'),
|
||||||
|
"To Chain": swap_result.get('to_chain'),
|
||||||
if response.status_code == 200:
|
"Amount": swap_result.get('amount'),
|
||||||
swap_result = response.json()
|
"Expected Amount": swap_result.get('expected_amount'),
|
||||||
success("Cross-chain swap created successfully!")
|
"Rate": swap_result.get('rate'),
|
||||||
output({
|
"Total Fees": swap_result.get('total_fees'),
|
||||||
"Swap ID": swap_result.get('swap_id'),
|
"Status": swap_result.get('status')
|
||||||
"From Chain": swap_result.get('from_chain'),
|
}, ctx.obj['output_format'])
|
||||||
"To Chain": swap_result.get('to_chain'),
|
|
||||||
"Amount": swap_result.get('amount'),
|
|
||||||
"Expected Amount": swap_result.get('expected_amount'),
|
|
||||||
"Rate": swap_result.get('rate'),
|
|
||||||
"Total Fees": swap_result.get('total_fees'),
|
|
||||||
"Status": swap_result.get('status')
|
|
||||||
}, ctx.obj['output_format'])
|
|
||||||
|
|
||||||
# Show swap ID for tracking
|
# Show swap ID for tracking
|
||||||
success(f"Track swap with: aitbc cross-chain status {swap_result.get('swap_id')}")
|
success(f"Track swap with: aitbc cross-chain status {swap_result.get('swap_id')}")
|
||||||
@@ -160,34 +160,44 @@ def swap(ctx, from_chain: str, to_chain: str, from_token: str, to_token: str,
|
|||||||
def status(ctx, swap_id: str):
|
def status(ctx, swap_id: str):
|
||||||
"""Check cross-chain swap status"""
|
"""Check cross-chain swap status"""
|
||||||
try:
|
try:
|
||||||
with httpx.Client() as client:
|
http_client = AITBCHTTPClient(base_url="http://localhost:8001/api/v1", timeout=10)
|
||||||
response = client.get(
|
swap_data = http_client.get(f"/cross-chain/swap/{swap_id}")
|
||||||
f"http://localhost:8001/api/v1/cross-chain/swap/{swap_id}",
|
success(f"Swap Status: {swap_data.get('status', 'unknown')}")
|
||||||
timeout=10
|
|
||||||
)
|
# Display swap details
|
||||||
|
details = {
|
||||||
if response.status_code == 200:
|
"Swap ID": swap_data.get('swap_id'),
|
||||||
swap_data = response.json()
|
"From Chain": swap_data.get('from_chain'),
|
||||||
success(f"Swap Status: {swap_data.get('status', 'unknown')}")
|
"To Chain": swap_data.get('to_chain'),
|
||||||
|
"From Token": swap_data.get('from_token'),
|
||||||
# Display swap details
|
"To Token": swap_data.get('to_token'),
|
||||||
details = {
|
"Amount": swap_data.get('amount'),
|
||||||
"Swap ID": swap_data.get('swap_id'),
|
"Expected Amount": swap_data.get('expected_amount'),
|
||||||
"From Chain": swap_data.get('from_chain'),
|
"Actual Amount": swap_data.get('actual_amount'),
|
||||||
"To Chain": swap_data.get('to_chain'),
|
"Status": swap_data.get('status'),
|
||||||
"From Token": swap_data.get('from_token'),
|
"Created At": swap_data.get('created_at'),
|
||||||
"To Token": swap_data.get('to_token'),
|
"Completed At": swap_data.get('completed_at'),
|
||||||
"Amount": swap_data.get('amount'),
|
"Bridge Fee": swap_data.get('bridge_fee'),
|
||||||
"Expected Amount": swap_data.get('expected_amount'),
|
"From Tx Hash": swap_data.get('from_tx_hash'),
|
||||||
"Actual Amount": swap_data.get('actual_amount'),
|
"To Tx Hash": swap_data.get('to_tx_hash')
|
||||||
"Status": swap_data.get('status'),
|
}
|
||||||
"Created At": swap_data.get('created_at'),
|
|
||||||
"Completed At": swap_data.get('completed_at'),
|
output(details, ctx.obj['output_format'])
|
||||||
"Bridge Fee": swap_data.get('bridge_fee'),
|
|
||||||
"From Tx Hash": swap_data.get('from_tx_hash'),
|
# Show additional status info
|
||||||
"To Tx Hash": swap_data.get('to_tx_hash')
|
if swap_data.get('status') == 'completed':
|
||||||
}
|
success("✅ Swap completed successfully!")
|
||||||
|
elif swap_data.get('status') == 'failed':
|
||||||
|
error("❌ Swap failed")
|
||||||
|
if swap_data.get('error_message'):
|
||||||
|
error(f"Error: {swap_data['error_message']}")
|
||||||
|
elif swap_data.get('status') == 'pending':
|
||||||
|
success("⏳ Swap is pending...")
|
||||||
|
elif swap_data.get('status') == 'executing':
|
||||||
|
success("🔄 Swap is executing...")
|
||||||
|
elif swap_data.get('status') == 'refunded':
|
||||||
|
success("💰 Swap was refunded")
|
||||||
|
except NetworkError as e:
|
||||||
output(details, ctx.obj['output_format'])
|
output(details, ctx.obj['output_format'])
|
||||||
|
|
||||||
# Show additional status info
|
# Show additional status info
|
||||||
@@ -223,19 +233,12 @@ def swaps(ctx, user_address: Optional[str], status: Optional[str], limit: int):
|
|||||||
params['status'] = status
|
params['status'] = status
|
||||||
|
|
||||||
try:
|
try:
|
||||||
with httpx.Client() as client:
|
http_client = AITBCHTTPClient(base_url="http://localhost:8001/api/v1", timeout=10)
|
||||||
response = client.get(
|
swaps_data = http_client.get("/cross-chain/swaps", params=params)
|
||||||
f"http://localhost:8001/api/v1/cross-chain/swaps",
|
swaps = swaps_data.get('swaps', [])
|
||||||
params=params,
|
|
||||||
timeout=10
|
if swaps:
|
||||||
)
|
success(f"Found {len(swaps)} cross-chain swaps:")
|
||||||
|
|
||||||
if response.status_code == 200:
|
|
||||||
swaps_data = response.json()
|
|
||||||
swaps = swaps_data.get('swaps', [])
|
|
||||||
|
|
||||||
if swaps:
|
|
||||||
success(f"Found {len(swaps)} cross-chain swaps:")
|
|
||||||
|
|
||||||
# Create table
|
# Create table
|
||||||
swap_table = []
|
swap_table = []
|
||||||
@@ -295,23 +298,16 @@ def bridge(ctx, source_chain: str, target_chain: str, token: str,
|
|||||||
}
|
}
|
||||||
|
|
||||||
try:
|
try:
|
||||||
with httpx.Client() as client:
|
http_client = AITBCHTTPClient(base_url="http://localhost:8001/api/v1", timeout=30)
|
||||||
response = client.post(
|
bridge_result = http_client.post("/cross-chain/bridge", json=bridge_data)
|
||||||
f"http://localhost:8001/api/v1/cross-chain/bridge",
|
success("Cross-chain bridge created successfully!")
|
||||||
json=bridge_data,
|
output({
|
||||||
timeout=30
|
"Bridge ID": bridge_result.get('bridge_id'),
|
||||||
)
|
"Source Chain": bridge_result.get('source_chain'),
|
||||||
|
"Target Chain": bridge_result.get('target_chain'),
|
||||||
if response.status_code == 200:
|
"Token": bridge_result.get('token'),
|
||||||
bridge_result = response.json()
|
"Amount": bridge_result.get('amount'),
|
||||||
success("Cross-chain bridge created successfully!")
|
"Bridge Fee": bridge_result.get('bridge_fee'),
|
||||||
output({
|
|
||||||
"Bridge ID": bridge_result.get('bridge_id'),
|
|
||||||
"Source Chain": bridge_result.get('source_chain'),
|
|
||||||
"Target Chain": bridge_result.get('target_chain'),
|
|
||||||
"Token": bridge_result.get('token'),
|
|
||||||
"Amount": bridge_result.get('amount'),
|
|
||||||
"Bridge Fee": bridge_result.get('bridge_fee'),
|
|
||||||
"Status": bridge_result.get('status')
|
"Status": bridge_result.get('status')
|
||||||
}, ctx.obj['output_format'])
|
}, ctx.obj['output_format'])
|
||||||
|
|
||||||
@@ -331,15 +327,9 @@ def bridge(ctx, source_chain: str, target_chain: str, token: str,
|
|||||||
def bridge_status(ctx, bridge_id: str):
|
def bridge_status(ctx, bridge_id: str):
|
||||||
"""Check cross-chain bridge status"""
|
"""Check cross-chain bridge status"""
|
||||||
try:
|
try:
|
||||||
with httpx.Client() as client:
|
http_client = AITBCHTTPClient(base_url="http://localhost:8001/api/v1", timeout=10)
|
||||||
response = client.get(
|
bridge_data = http_client.get(f"/cross-chain/bridge/{bridge_id}")
|
||||||
f"http://localhost:8001/api/v1/cross-chain/bridge/{bridge_id}",
|
success(f"Bridge Status: {bridge_data.get('status', 'unknown')}")
|
||||||
timeout=10
|
|
||||||
)
|
|
||||||
|
|
||||||
if response.status_code == 200:
|
|
||||||
bridge_data = response.json()
|
|
||||||
success(f"Bridge Status: {bridge_data.get('status', 'unknown')}")
|
|
||||||
|
|
||||||
# Display bridge details
|
# Display bridge details
|
||||||
details = {
|
details = {
|
||||||
@@ -383,7 +373,7 @@ def bridge_status(ctx, bridge_id: str):
|
|||||||
def pools(ctx):
|
def pools(ctx):
|
||||||
"""Show cross-chain liquidity pools"""
|
"""Show cross-chain liquidity pools"""
|
||||||
try:
|
try:
|
||||||
with httpx.Client() as client:
|
http_client = AITBCHTTPClient(base_url="http://localhost:8001/api/v1", timeout=10)
|
||||||
response = client.get(
|
response = client.get(
|
||||||
f"http://localhost:8001/api/v1/cross-chain/pools",
|
f"http://localhost:8001/api/v1/cross-chain/pools",
|
||||||
timeout=10
|
timeout=10
|
||||||
@@ -426,7 +416,7 @@ def pools(ctx):
|
|||||||
def stats(ctx):
|
def stats(ctx):
|
||||||
"""Show cross-chain trading statistics"""
|
"""Show cross-chain trading statistics"""
|
||||||
try:
|
try:
|
||||||
with httpx.Client() as client:
|
http_client = AITBCHTTPClient(base_url="http://localhost:8001/api/v1", timeout=10)
|
||||||
response = client.get(
|
response = client.get(
|
||||||
f"http://localhost:8001/api/v1/cross-chain/stats",
|
f"http://localhost:8001/api/v1/cross-chain/stats",
|
||||||
timeout=10
|
timeout=10
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
"""Exchange integration commands for AITBC CLI"""
|
"""Exchange integration commands for AITBC CLI"""
|
||||||
|
|
||||||
import click
|
import click
|
||||||
import httpx
|
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
@@ -10,6 +9,14 @@ from datetime import datetime
|
|||||||
from ..utils import output, error, success, warning
|
from ..utils import output, error, success, warning
|
||||||
from ..config import get_config
|
from ..config import get_config
|
||||||
|
|
||||||
|
# Import shared modules
|
||||||
|
from aitbc.aitbc_logging import get_logger
|
||||||
|
from aitbc.http_client import AITBCHTTPClient
|
||||||
|
from aitbc.exceptions import NetworkError
|
||||||
|
|
||||||
|
# Initialize logger
|
||||||
|
logger = get_logger(__name__)
|
||||||
|
|
||||||
|
|
||||||
@click.group()
|
@click.group()
|
||||||
def exchange():
|
def exchange():
|
||||||
@@ -368,20 +375,14 @@ def status(ctx, exchange_name: str):
|
|||||||
config = ctx.obj['config']
|
config = ctx.obj['config']
|
||||||
|
|
||||||
try:
|
try:
|
||||||
with httpx.Client() as client:
|
http_client = AITBCHTTPClient(base_url="http://localhost:8001/api/v1", timeout=10)
|
||||||
response = client.get(
|
rates_data = http_client.get(f"/exchange/rates")
|
||||||
f"{config.coordinator_url}/v1/exchange/rates",
|
success("Current exchange rates:")
|
||||||
timeout=10
|
output(rates_data, ctx.obj['output_format'])
|
||||||
)
|
except NetworkError as e:
|
||||||
|
|
||||||
if response.status_code == 200:
|
|
||||||
rates_data = response.json()
|
|
||||||
success("Current exchange rates:")
|
|
||||||
output(rates_data, ctx.obj['output_format'])
|
|
||||||
else:
|
|
||||||
error(f"Failed to get exchange rates: {response.status_code}")
|
|
||||||
except Exception as e:
|
|
||||||
error(f"Network error: {e}")
|
error(f"Network error: {e}")
|
||||||
|
except Exception as e:
|
||||||
|
error(f"Error: {e}")
|
||||||
|
|
||||||
|
|
||||||
@exchange.command()
|
@exchange.command()
|
||||||
@@ -410,55 +411,36 @@ def create_payment(ctx, aitbc_amount: Optional[float], btc_amount: Optional[floa
|
|||||||
|
|
||||||
# Get exchange rates to calculate missing amount
|
# Get exchange rates to calculate missing amount
|
||||||
try:
|
try:
|
||||||
with httpx.Client() as client:
|
http_client = AITBCHTTPClient(base_url="http://localhost:8001/api/v1", timeout=10)
|
||||||
rates_response = client.get(
|
rates = http_client.get("/exchange/rates")
|
||||||
f"{config.coordinator_url}/v1/exchange/rates",
|
btc_to_aitbc = rates.get('btc_to_aitbc', 100000)
|
||||||
timeout=10
|
|
||||||
)
|
# Calculate missing amount
|
||||||
|
if aitbc_amount and not btc_amount:
|
||||||
if rates_response.status_code != 200:
|
btc_amount = aitbc_amount / btc_to_aitbc
|
||||||
error("Failed to get exchange rates")
|
elif btc_amount and not aitbc_amount:
|
||||||
return
|
aitbc_amount = btc_amount * btc_to_aitbc
|
||||||
|
|
||||||
rates = rates_response.json()
|
# Prepare payment request
|
||||||
btc_to_aitbc = rates.get('btc_to_aitbc', 100000)
|
payment_data = {
|
||||||
|
"user_id": user_id or "cli_user",
|
||||||
# Calculate missing amount
|
"aitbc_amount": aitbc_amount,
|
||||||
if aitbc_amount and not btc_amount:
|
"btc_amount": btc_amount
|
||||||
btc_amount = aitbc_amount / btc_to_aitbc
|
}
|
||||||
elif btc_amount and not aitbc_amount:
|
|
||||||
aitbc_amount = btc_amount * btc_to_aitbc
|
if notes:
|
||||||
|
payment_data["notes"] = notes
|
||||||
# Prepare payment request
|
|
||||||
payment_data = {
|
# Create payment
|
||||||
"user_id": user_id or "cli_user",
|
payment = http_client.post("/exchange/create-payment", json=payment_data)
|
||||||
"aitbc_amount": aitbc_amount,
|
success(f"Payment created: {payment.get('payment_id')}")
|
||||||
"btc_amount": btc_amount
|
success(f"Send {btc_amount:.8f} BTC to: {payment.get('payment_address')}")
|
||||||
}
|
success(f"Expires at: {payment.get('expires_at')}")
|
||||||
|
output(payment, ctx.obj['output_format'])
|
||||||
if notes:
|
except NetworkError as e:
|
||||||
payment_data["notes"] = notes
|
|
||||||
|
|
||||||
# Create payment
|
|
||||||
response = client.post(
|
|
||||||
f"{config.coordinator_url}/v1/exchange/create-payment",
|
|
||||||
json=payment_data,
|
|
||||||
timeout=10
|
|
||||||
)
|
|
||||||
|
|
||||||
if response.status_code == 200:
|
|
||||||
payment = response.json()
|
|
||||||
success(f"Payment created: {payment.get('payment_id')}")
|
|
||||||
success(f"Send {btc_amount:.8f} BTC to: {payment.get('payment_address')}")
|
|
||||||
success(f"Expires at: {payment.get('expires_at')}")
|
|
||||||
output(payment, ctx.obj['output_format'])
|
|
||||||
else:
|
|
||||||
error(f"Failed to create payment: {response.status_code}")
|
|
||||||
if response.text:
|
|
||||||
error(f"Error details: {response.text}")
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
error(f"Network error: {e}")
|
error(f"Network error: {e}")
|
||||||
|
except Exception as e:
|
||||||
|
error(f"Error: {e}")
|
||||||
|
|
||||||
|
|
||||||
@exchange.command()
|
@exchange.command()
|
||||||
@@ -469,31 +451,25 @@ def payment_status(ctx, payment_id: str):
|
|||||||
config = ctx.obj['config']
|
config = ctx.obj['config']
|
||||||
|
|
||||||
try:
|
try:
|
||||||
with httpx.Client() as client:
|
http_client = AITBCHTTPClient(base_url="http://localhost:8001/api/v1", timeout=10)
|
||||||
response = client.get(
|
status_data = http_client.get(f"/exchange/payment-status/{payment_id}")
|
||||||
f"{config.coordinator_url}/v1/exchange/payment-status/{payment_id}",
|
status = status_data.get('status', 'unknown')
|
||||||
timeout=10
|
|
||||||
)
|
if status == 'confirmed':
|
||||||
|
success(f"Payment {payment_id} is confirmed!")
|
||||||
if response.status_code == 200:
|
success(f"AITBC amount: {status_data.get('aitbc_amount', 0)}")
|
||||||
status_data = response.json()
|
elif status == 'pending':
|
||||||
status = status_data.get('status', 'unknown')
|
success(f"Payment {payment_id} is pending confirmation")
|
||||||
|
elif status == 'expired':
|
||||||
if status == 'confirmed':
|
error(f"Payment {payment_id} has expired")
|
||||||
success(f"Payment {payment_id} is confirmed!")
|
else:
|
||||||
success(f"AITBC amount: {status_data.get('aitbc_amount', 0)}")
|
success(f"Payment {payment_id} status: {status}")
|
||||||
elif status == 'pending':
|
|
||||||
success(f"Payment {payment_id} is pending confirmation")
|
output(status_data, ctx.obj['output_format'])
|
||||||
elif status == 'expired':
|
except NetworkError as e:
|
||||||
error(f"Payment {payment_id} has expired")
|
|
||||||
else:
|
|
||||||
success(f"Payment {payment_id} status: {status}")
|
|
||||||
|
|
||||||
output(status_data, ctx.obj['output_format'])
|
|
||||||
else:
|
|
||||||
error(f"Failed to get payment status: {response.status_code}")
|
|
||||||
except Exception as e:
|
|
||||||
error(f"Network error: {e}")
|
error(f"Network error: {e}")
|
||||||
|
except Exception as e:
|
||||||
|
error(f"Error: {e}")
|
||||||
|
|
||||||
|
|
||||||
@exchange.command()
|
@exchange.command()
|
||||||
@@ -503,20 +479,14 @@ def market_stats(ctx):
|
|||||||
config = ctx.obj['config']
|
config = ctx.obj['config']
|
||||||
|
|
||||||
try:
|
try:
|
||||||
with httpx.Client() as client:
|
http_client = AITBCHTTPClient(base_url="http://localhost:8001/api/v1", timeout=10)
|
||||||
response = client.get(
|
stats = http_client.get("/exchange/market-stats")
|
||||||
f"{config.coordinator_url}/v1/exchange/market-stats",
|
success("Exchange market statistics:")
|
||||||
timeout=10
|
output(stats, ctx.obj['output_format'])
|
||||||
)
|
except NetworkError as e:
|
||||||
|
|
||||||
if response.status_code == 200:
|
|
||||||
stats = response.json()
|
|
||||||
success("Exchange market statistics:")
|
|
||||||
output(stats, ctx.obj['output_format'])
|
|
||||||
else:
|
|
||||||
error(f"Failed to get market stats: {response.status_code}")
|
|
||||||
except Exception as e:
|
|
||||||
error(f"Network error: {e}")
|
error(f"Network error: {e}")
|
||||||
|
except Exception as e:
|
||||||
|
error(f"Error: {e}")
|
||||||
|
|
||||||
|
|
||||||
@exchange.group()
|
@exchange.group()
|
||||||
@@ -532,20 +502,14 @@ def balance(ctx):
|
|||||||
config = ctx.obj['config']
|
config = ctx.obj['config']
|
||||||
|
|
||||||
try:
|
try:
|
||||||
with httpx.Client() as client:
|
http_client = AITBCHTTPClient(base_url="http://localhost:8001/api/v1", timeout=10)
|
||||||
response = client.get(
|
balance_data = http_client.get("/exchange/wallet/balance")
|
||||||
f"{config.coordinator_url}/exchange/wallet/balance",
|
success("Bitcoin wallet balance:")
|
||||||
timeout=10
|
output(balance_data, ctx.obj['output_format'])
|
||||||
)
|
except NetworkError as e:
|
||||||
|
|
||||||
if response.status_code == 200:
|
|
||||||
balance_data = response.json()
|
|
||||||
success("Bitcoin wallet balance:")
|
|
||||||
output(balance_data, ctx.obj['output_format'])
|
|
||||||
else:
|
|
||||||
error(f"Failed to get wallet balance: {response.status_code}")
|
|
||||||
except Exception as e:
|
|
||||||
error(f"Network error: {e}")
|
error(f"Network error: {e}")
|
||||||
|
except Exception as e:
|
||||||
|
error(f"Error: {e}")
|
||||||
|
|
||||||
|
|
||||||
@wallet.command()
|
@wallet.command()
|
||||||
@@ -555,20 +519,14 @@ def info(ctx):
|
|||||||
config = ctx.obj['config']
|
config = ctx.obj['config']
|
||||||
|
|
||||||
try:
|
try:
|
||||||
with httpx.Client() as client:
|
http_client = AITBCHTTPClient(base_url="http://localhost:8001/api/v1", timeout=10)
|
||||||
response = client.get(
|
wallet_info = http_client.get("/exchange/wallet/info")
|
||||||
f"{config.coordinator_url}/exchange/wallet/info",
|
success("Bitcoin wallet information:")
|
||||||
timeout=10
|
output(wallet_info, ctx.obj['output_format'])
|
||||||
)
|
except NetworkError as e:
|
||||||
|
|
||||||
if response.status_code == 200:
|
|
||||||
wallet_info = response.json()
|
|
||||||
success("Bitcoin wallet information:")
|
|
||||||
output(wallet_info, ctx.obj['output_format'])
|
|
||||||
else:
|
|
||||||
error(f"Failed to get wallet info: {response.status_code}")
|
|
||||||
except Exception as e:
|
|
||||||
error(f"Network error: {e}")
|
error(f"Network error: {e}")
|
||||||
|
except Exception as e:
|
||||||
|
error(f"Error: {e}")
|
||||||
|
|
||||||
|
|
||||||
@exchange.command()
|
@exchange.command()
|
||||||
@@ -591,24 +549,15 @@ def register(ctx, name: str, api_key: str, api_secret: Optional[str], sandbox: b
|
|||||||
exchange_data["api_secret"] = api_secret
|
exchange_data["api_secret"] = api_secret
|
||||||
|
|
||||||
try:
|
try:
|
||||||
with httpx.Client() as client:
|
http_client = AITBCHTTPClient(base_url="http://localhost:8001/api/v1", timeout=10)
|
||||||
response = client.post(
|
result = http_client.post("/exchange/register", json=exchange_data)
|
||||||
f"{config.coordinator_url}/v1/exchange/register",
|
success(f"Exchange '{name}' registered successfully!")
|
||||||
json=exchange_data,
|
success(f"Exchange ID: {result.get('exchange_id')}")
|
||||||
timeout=10
|
output(result, ctx.obj['output_format'])
|
||||||
)
|
except NetworkError as e:
|
||||||
|
|
||||||
if response.status_code == 200:
|
|
||||||
result = response.json()
|
|
||||||
success(f"Exchange '{name}' registered successfully!")
|
|
||||||
success(f"Exchange ID: {result.get('exchange_id')}")
|
|
||||||
output(result, ctx.obj['output_format'])
|
|
||||||
else:
|
|
||||||
error(f"Failed to register exchange: {response.status_code}")
|
|
||||||
if response.text:
|
|
||||||
error(f"Error details: {response.text}")
|
|
||||||
except Exception as e:
|
|
||||||
error(f"Network error: {e}")
|
error(f"Network error: {e}")
|
||||||
|
except Exception as e:
|
||||||
|
error(f"Error: {e}")
|
||||||
|
|
||||||
|
|
||||||
@exchange.command()
|
@exchange.command()
|
||||||
@@ -640,8 +589,8 @@ def create_pair(ctx, pair: str, base_asset: str, quote_asset: str,
|
|||||||
pair_data["max_order_size"] = max_order_size
|
pair_data["max_order_size"] = max_order_size
|
||||||
|
|
||||||
try:
|
try:
|
||||||
with httpx.Client() as client:
|
http_client = AITBCHTTPClient(base_url="http://localhost:8001/api/v1", timeout=10)
|
||||||
response = client.post(
|
response = http_client.post(
|
||||||
f"{config.coordinator_url}/v1/exchange/create-pair",
|
f"{config.coordinator_url}/v1/exchange/create-pair",
|
||||||
json=pair_data,
|
json=pair_data,
|
||||||
timeout=10
|
timeout=10
|
||||||
@@ -679,8 +628,8 @@ def start_trading(ctx, pair: str, exchange: Optional[str], order_type: tuple):
|
|||||||
trading_data["exchange"] = exchange
|
trading_data["exchange"] = exchange
|
||||||
|
|
||||||
try:
|
try:
|
||||||
with httpx.Client() as client:
|
http_client = AITBCHTTPClient(base_url="http://localhost:8001/api/v1", timeout=10)
|
||||||
response = client.post(
|
response = http_client.post(
|
||||||
f"{config.coordinator_url}/v1/exchange/start-trading",
|
f"{config.coordinator_url}/v1/exchange/start-trading",
|
||||||
json=trading_data,
|
json=trading_data,
|
||||||
timeout=10
|
timeout=10
|
||||||
@@ -717,8 +666,8 @@ def list_pairs(ctx, pair: Optional[str], exchange: Optional[str], status: Option
|
|||||||
params["status"] = status
|
params["status"] = status
|
||||||
|
|
||||||
try:
|
try:
|
||||||
with httpx.Client() as client:
|
http_client = AITBCHTTPClient(base_url="http://localhost:8001/api/v1", timeout=10)
|
||||||
response = client.get(
|
response = http_client.get(
|
||||||
f"{config.coordinator_url}/v1/exchange/pairs",
|
f"{config.coordinator_url}/v1/exchange/pairs",
|
||||||
params=params,
|
params=params,
|
||||||
timeout=10
|
timeout=10
|
||||||
|
|||||||
@@ -17,6 +17,14 @@ from ..utils.island_credentials import (
|
|||||||
get_island_id, get_island_name
|
get_island_id, get_island_name
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# Import shared modules
|
||||||
|
from aitbc.aitbc_logging import get_logger
|
||||||
|
from aitbc.http_client import AITBCHTTPClient
|
||||||
|
from aitbc.exceptions import NetworkError
|
||||||
|
|
||||||
|
# Initialize logger
|
||||||
|
logger = get_logger(__name__)
|
||||||
|
|
||||||
|
|
||||||
# Supported trading pairs
|
# Supported trading pairs
|
||||||
SUPPORTED_PAIRS = ['AIT/BTC', 'AIT/ETH']
|
SUPPORTED_PAIRS = ['AIT/BTC', 'AIT/ETH']
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
"""Wallet commands for AITBC CLI"""
|
"""Wallet commands for AITBC CLI"""
|
||||||
|
|
||||||
import click
|
import click
|
||||||
import httpx
|
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
import shutil
|
import shutil
|
||||||
@@ -12,6 +11,15 @@ from datetime import datetime, timedelta
|
|||||||
from ..utils import output, error, success
|
from ..utils import output, error, success
|
||||||
import getpass
|
import getpass
|
||||||
|
|
||||||
|
# Import shared modules
|
||||||
|
from aitbc.aitbc_logging import get_logger
|
||||||
|
from aitbc.http_client import AITBCHTTPClient
|
||||||
|
from aitbc.exceptions import NetworkError
|
||||||
|
from aitbc.constants import KEYSTORE_DIR
|
||||||
|
|
||||||
|
# Initialize logger
|
||||||
|
logger = get_logger(__name__)
|
||||||
|
|
||||||
|
|
||||||
def encrypt_value(value: str, password: str) -> str:
|
def encrypt_value(value: str, password: str) -> str:
|
||||||
"""Simple encryption for wallet data (placeholder)"""
|
"""Simple encryption for wallet data (placeholder)"""
|
||||||
@@ -523,16 +531,13 @@ def balance(ctx):
|
|||||||
# Try to get balance from blockchain if available
|
# Try to get balance from blockchain if available
|
||||||
if config:
|
if config:
|
||||||
try:
|
try:
|
||||||
with httpx.Client() as client:
|
http_client = AITBCHTTPClient(
|
||||||
response = client.get(
|
base_url=config.coordinator_url.replace('/api', ''),
|
||||||
f"{config.coordinator_url.replace('/api', '')}/rpc/balance/{wallet_data['address']}",
|
timeout=5
|
||||||
timeout=5,
|
)
|
||||||
)
|
blockchain_balance = http_client.get(f"/rpc/balance/{wallet_data['address']}")
|
||||||
|
output(
|
||||||
if response.status_code == 200:
|
{
|
||||||
blockchain_balance = response.json().get("balance", 0)
|
|
||||||
output(
|
|
||||||
{
|
|
||||||
"wallet": wallet_name,
|
"wallet": wallet_name,
|
||||||
"address": wallet_data["address"],
|
"address": wallet_data["address"],
|
||||||
"local_balance": wallet_data.get("balance", 0),
|
"local_balance": wallet_data.get("balance", 0),
|
||||||
@@ -737,27 +742,25 @@ def send(ctx, to_address: str, amount: float, description: Optional[str]):
|
|||||||
# Try to send via blockchain
|
# Try to send via blockchain
|
||||||
if config:
|
if config:
|
||||||
try:
|
try:
|
||||||
with httpx.Client() as client:
|
http_client = AITBCHTTPClient(
|
||||||
response = client.post(
|
base_url=config.coordinator_url.replace('/api', ''),
|
||||||
f"{config.coordinator_url.replace('/api', '')}/rpc/transactions",
|
timeout=30,
|
||||||
json={
|
headers={"X-Api-Key": getattr(config, "api_key", "") or ""}
|
||||||
"from": wallet_data["address"],
|
)
|
||||||
"to": to_address,
|
result = http_client.post(
|
||||||
"amount": amount,
|
"/rpc/transactions",
|
||||||
"description": description or "",
|
json={
|
||||||
},
|
"from": wallet_data["address"],
|
||||||
headers={"X-Api-Key": getattr(config, "api_key", "") or ""},
|
"to": to_address,
|
||||||
)
|
"amount": amount,
|
||||||
|
"description": description or "",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
if response.status_code == 201:
|
if result:
|
||||||
tx = response.json()
|
success(f"Transaction sent: {result.get('transaction_hash', 'N/A')}")
|
||||||
# Update local wallet
|
output(result, ctx.obj.get("output_format", "table"))
|
||||||
transaction = {
|
return
|
||||||
"type": "send",
|
|
||||||
"amount": -amount,
|
|
||||||
"to_address": to_address,
|
|
||||||
"tx_hash": tx.get("hash"),
|
|
||||||
"description": description or "",
|
|
||||||
"timestamp": datetime.now().isoformat(),
|
"timestamp": datetime.now().isoformat(),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user