feat: migrate coordinator-api services and exchange CLI to use centralized aitbc package utilities
Some checks failed
Python Tests / test-python (push) Waiting to run
Security Scanning / security-scan (push) Waiting to run
Staking Tests / test-staking-integration (push) Blocked by required conditions
Staking Tests / test-staking-contract (push) Blocked by required conditions
Staking Tests / run-staking-test-runner (push) Blocked by required conditions
API Endpoint Tests / test-api-endpoints (push) Successful in 9s
CLI Tests / test-cli (push) Failing after 8s
Integration Tests / test-service-integration (push) Successful in 45s
Staking Tests / test-staking-service (push) Failing after 14m32s

- Replace logging.getLogger with aitbc.get_logger in analytics_service.py, staking_service.py, wallet_service.py
- Migrate payments.py from httpx to aitbc.AITBCHTTPClient for token escrow creation
- Add NetworkError exception handling in payments.py
- Remove async context manager and status code checks in favor of AITBCHTTPClient
- Update exchange.py CLI commands (create_pair, start_trading) to use
This commit is contained in:
aitbc
2026-04-24 23:37:21 +02:00
parent 3103debecf
commit 0ccd8ef995
5 changed files with 55 additions and 74 deletions

View File

@@ -3,12 +3,13 @@ Marketplace Analytics Service
Implements comprehensive analytics, insights, and reporting for the marketplace Implements comprehensive analytics, insights, and reporting for the marketplace
""" """
import logging
from datetime import datetime, timedelta from datetime import datetime, timedelta
from typing import Any from typing import Any
from uuid import uuid4 from uuid import uuid4
logger = logging.getLogger(__name__) from aitbc import get_logger
logger = get_logger(__name__)
from sqlmodel import Session, and_, select from sqlmodel import Session, and_, select

View File

@@ -5,14 +5,11 @@ from sqlalchemy.orm import Session
"""Payment service for job payments""" """Payment service for job payments"""
import logging
from datetime import datetime, timedelta from datetime import datetime, timedelta
from __future__ import annotations from __future__ import annotations
import httpx from aitbc import get_logger, AITBCHTTPClient, NetworkError
from aitbc import get_logger
logger = get_logger(__name__) logger = get_logger(__name__)
@@ -71,41 +68,43 @@ class PaymentService:
"""Create an escrow for AITBC token payments""" """Create an escrow for AITBC token payments"""
try: try:
# For AITBC tokens, we use the token contract escrow # For AITBC tokens, we use the token contract escrow
async with httpx.AsyncClient() as client: client = AITBCHTTPClient(timeout=10.0)
# Call exchange API to create token escrow # Call exchange API to create token escrow
response = await client.post( response = client.post(
f"{self.exchange_base_url}/api/v1/token/escrow/create", f"{self.exchange_base_url}/api/v1/token/escrow/create",
json={ json={
"amount": float(payment.amount), "amount": float(payment.amount),
"currency": payment.currency, "currency": payment.currency,
"job_id": payment.job_id, "job_id": payment.job_id,
"timeout_seconds": 3600, # 1 hour "timeout_seconds": 3600, # 1 hour
}, },
) )
if response.status_code == 200: escrow_data = response
escrow_data = response.json() payment.escrow_address = escrow_data.get("escrow_id")
payment.escrow_address = escrow_data.get("escrow_id") payment.status = "escrowed"
payment.status = "escrowed" payment.escrowed_at = datetime.utcnow()
payment.escrowed_at = datetime.utcnow() payment.updated_at = datetime.utcnow()
payment.updated_at = datetime.utcnow()
# Create escrow record # Create escrow record
escrow = PaymentEscrow( escrow = PaymentEscrow(
payment_id=payment.id, payment_id=payment.id,
amount=payment.amount, amount=payment.amount,
currency=payment.currency, currency=payment.currency,
address=escrow_data.get("escrow_id"), address=escrow_data.get("escrow_id"),
expires_at=datetime.utcnow() + timedelta(hours=1), expires_at=datetime.utcnow() + timedelta(hours=1),
) )
if escrow is not None: if escrow is not None:
self.session.add(escrow) self.session.add(escrow)
self.session.commit() self.session.commit()
logger.info(f"Created AITBC token escrow for payment {payment.id}") logger.info(f"Created AITBC token escrow for payment {payment.id}")
else:
logger.error(f"Failed to create token escrow: {response.text}")
except NetworkError as e:
logger.error(f"Failed to create token escrow: {e}")
payment.status = "failed"
payment.updated_at = datetime.utcnow()
self.session.commit()
except Exception as e: except Exception as e:
logger.error(f"Error creating token escrow: {e}") logger.error(f"Error creating token escrow: {e}")
payment.status = "failed" payment.status = "failed"

View File

@@ -3,16 +3,16 @@ Staking Management Service
Business logic for AI agent staking system with reputation-based yield farming Business logic for AI agent staking system with reputation-based yield farming
""" """
import logging
from datetime import datetime, timedelta from datetime import datetime, timedelta
from typing import Any from typing import Any
from sqlalchemy import and_, func, select from sqlalchemy import and_, func, select
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from aitbc import get_logger
from ..domain.bounty import AgentMetrics, AgentStake, PerformanceTier, StakeStatus, StakingPool from ..domain.bounty import AgentMetrics, AgentStake, PerformanceTier, StakeStatus, StakingPool
logger = logging.getLogger(__name__) logger = get_logger(__name__)
class StakingService: class StakingService:

View File

@@ -6,19 +6,18 @@ Service for managing agent wallets across multiple blockchain networks.
from __future__ import annotations from __future__ import annotations
import logging
# In a real scenario, these would be proper cryptographic key generation utilities # In a real scenario, these would be proper cryptographic key generation utilities
import secrets import secrets
from sqlalchemy import select from sqlalchemy import select
from sqlmodel import Session from sqlmodel import Session
from aitbc import get_logger
from ..blockchain.contract_interactions import ContractInteractionService from ..blockchain.contract_interactions import ContractInteractionService
from ..domain.wallet import AgentWallet, TokenBalance, TransactionStatus, WalletTransaction from ..domain.wallet import AgentWallet, TokenBalance, TransactionStatus, WalletTransaction
from ..schemas.wallet import TransactionRequest, WalletCreate from ..schemas.wallet import TransactionRequest, WalletCreate
logger = logging.getLogger(__name__) logger = get_logger(__name__)
class WalletService: class WalletService:

View File

@@ -590,23 +590,14 @@ def create_pair(ctx, pair: str, base_asset: str, quote_asset: str,
try: try:
http_client = AITBCHTTPClient(base_url="http://localhost:8001/api/v1", timeout=10) http_client = AITBCHTTPClient(base_url="http://localhost:8001/api/v1", timeout=10)
response = http_client.post( result = http_client.post("/exchange/create-pair", json=pair_data)
f"{config.coordinator_url}/v1/exchange/create-pair", success(f"Trading pair '{pair}' created successfully!")
json=pair_data, success(f"Pair ID: {result.get('pair_id')}")
timeout=10 output(result, ctx.obj['output_format'])
) except NetworkError as e:
if response.status_code == 200:
result = response.json()
success(f"Trading pair '{pair}' created successfully!")
success(f"Pair ID: {result.get('pair_id')}")
output(result, ctx.obj['output_format'])
else:
error(f"Failed to create trading pair: {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()
@@ -629,23 +620,14 @@ def start_trading(ctx, pair: str, exchange: Optional[str], order_type: tuple):
try: try:
http_client = AITBCHTTPClient(base_url="http://localhost:8001/api/v1", timeout=10) http_client = AITBCHTTPClient(base_url="http://localhost:8001/api/v1", timeout=10)
response = http_client.post( result = http_client.post("/exchange/start-trading", json=trading_data)
f"{config.coordinator_url}/v1/exchange/start-trading", success(f"Trading started for pair '{pair}'!")
json=trading_data, success(f"Order types: {', '.join(order_type)}")
timeout=10 output(result, ctx.obj['output_format'])
) except NetworkError as e:
if response.status_code == 200:
result = response.json()
success(f"Trading started for pair '{pair}'!")
success(f"Order types: {', '.join(order_type)}")
output(result, ctx.obj['output_format'])
else:
error(f"Failed to start trading: {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()