Fix datetime.UTC to timezone.utc across agent-coordinator codebase
Some checks failed
API Endpoint Tests / test-api-endpoints (push) Successful in 26s
Blockchain Synchronization Verification / sync-verification (push) Failing after 2s
Cross-Chain Functionality Tests / test-cross-chain-sync (push) Failing after 3s
Cross-Chain Functionality Tests / test-cross-chain-transactions (push) Successful in 5s
Cross-Chain Functionality Tests / test-cross-chain-bridge (push) Has been skipped
Cross-Chain Functionality Tests / test-multi-chain-consensus (push) Failing after 2s
Cross-Chain Functionality Tests / aggregate-results (push) Has been skipped
Cross-Node Transaction Testing / transaction-test (push) Successful in 10s
Deploy to Testnet / deploy-testnet (push) Successful in 1m17s
Documentation Validation / validate-docs (push) Successful in 26s
Deploy to Testnet / notify-deployment (push) Has been cancelled
Integration Tests / test-service-integration (push) Has been cancelled
Multi-Node Blockchain Health Monitoring / health-check (push) Has been cancelled
Multi-Node Stress Testing / stress-test (push) Has been cancelled
Node Failover Simulation / failover-test (push) Has been cancelled
P2P Network Verification / p2p-verification (push) Has been cancelled
Python Tests / test-python (push) Has been cancelled
Security Scanning / security-scan (push) Has been cancelled
Documentation Validation / validate-policies-strict (push) Successful in 6s
Production Tests / Production Integration Tests (push) Successful in 42s
Staking Tests / test-staking-service (push) Failing after 11s
Staking Tests / test-staking-integration (push) Has been skipped
Staking Tests / test-staking-contract (push) Has been skipped
Staking Tests / run-staking-test-runner (push) Has been skipped
Systemd Sync / sync-systemd (push) Successful in 26s
Some checks failed
API Endpoint Tests / test-api-endpoints (push) Successful in 26s
Blockchain Synchronization Verification / sync-verification (push) Failing after 2s
Cross-Chain Functionality Tests / test-cross-chain-sync (push) Failing after 3s
Cross-Chain Functionality Tests / test-cross-chain-transactions (push) Successful in 5s
Cross-Chain Functionality Tests / test-cross-chain-bridge (push) Has been skipped
Cross-Chain Functionality Tests / test-multi-chain-consensus (push) Failing after 2s
Cross-Chain Functionality Tests / aggregate-results (push) Has been skipped
Cross-Node Transaction Testing / transaction-test (push) Successful in 10s
Deploy to Testnet / deploy-testnet (push) Successful in 1m17s
Documentation Validation / validate-docs (push) Successful in 26s
Deploy to Testnet / notify-deployment (push) Has been cancelled
Integration Tests / test-service-integration (push) Has been cancelled
Multi-Node Blockchain Health Monitoring / health-check (push) Has been cancelled
Multi-Node Stress Testing / stress-test (push) Has been cancelled
Node Failover Simulation / failover-test (push) Has been cancelled
P2P Network Verification / p2p-verification (push) Has been cancelled
Python Tests / test-python (push) Has been cancelled
Security Scanning / security-scan (push) Has been cancelled
Documentation Validation / validate-policies-strict (push) Successful in 6s
Production Tests / Production Integration Tests (push) Successful in 42s
Staking Tests / test-staking-service (push) Failing after 11s
Staking Tests / test-staking-integration (push) Has been skipped
Staking Tests / test-staking-contract (push) Has been skipped
Staking Tests / run-staking-test-runner (push) Has been skipped
Systemd Sync / sync-systemd (push) Successful in 26s
- Changed datetime.UTC to timezone.utc in advanced_ai.py - Changed datetime.UTC to timezone.utc in realtime_learning.py - Changed datetime.UTC to timezone.utc in jwt_handler.py - Changed datetime.UTC to timezone.utc in distributed_consensus.py - Changed datetime.UTC to timezone.utc in exceptions.py - Changed datetime.UTC to timezone.utc in alerting.py - Changed datetime.UTC to timezone.utc in communication.py - Changed datetime.UTC to timezone.utc in message_types.py - Updated imports from `datetime import
This commit is contained in:
@@ -3,7 +3,7 @@ AI Agent Domain Models for Verifiable AI Agent Orchestration
|
||||
Implements SQLModel definitions for agent workflows, steps, and execution tracking
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
@@ -68,8 +68,8 @@ class AIAgentWorkflow(SQLModel, table=True):
|
||||
is_public: bool = Field(default=False)
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
class AgentStep(SQLModel, table=True):
|
||||
@@ -102,8 +102,8 @@ class AgentStep(SQLModel, table=True):
|
||||
depends_on: str = Field(default="") # JSON string of step IDs
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
class AgentExecution(SQLModel, table=True):
|
||||
@@ -141,8 +141,8 @@ class AgentExecution(SQLModel, table=True):
|
||||
completed_steps: int = Field(default=0)
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
class AgentStepExecution(SQLModel, table=True):
|
||||
@@ -180,8 +180,8 @@ class AgentStepExecution(SQLModel, table=True):
|
||||
completed_at: datetime | None = Field(default=None)
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
class AgentMarketplace(SQLModel, table=True):
|
||||
@@ -219,8 +219,8 @@ class AgentMarketplace(SQLModel, table=True):
|
||||
last_execution_at: datetime | None = Field(default=None)
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
# Request/Response Models for API
|
||||
|
||||
@@ -3,7 +3,7 @@ Agent Identity Domain Models for Cross-Chain Agent Identity Management
|
||||
Implements SQLModel definitions for unified agent identity across multiple blockchains
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
@@ -80,8 +80,8 @@ class AgentIdentity(SQLModel, table=True):
|
||||
tags: list[str] = Field(default_factory=list, sa_column=Column(JSON))
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Indexes for performance
|
||||
__table_args__ = {
|
||||
@@ -122,8 +122,8 @@ class CrossChainMapping(SQLModel, table=True):
|
||||
transaction_count: int = Field(default=0)
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Unique constraint
|
||||
__table_args__ = {
|
||||
@@ -162,8 +162,8 @@ class IdentityVerification(SQLModel, table=True):
|
||||
verification_meta_data: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON))
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Indexes
|
||||
__table_args__ = {
|
||||
@@ -208,8 +208,8 @@ class AgentWallet(SQLModel, table=True):
|
||||
transaction_count: int = Field(default=0)
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Indexes
|
||||
__table_args__ = {
|
||||
|
||||
@@ -3,7 +3,7 @@ Advanced Agent Performance Domain Models
|
||||
Implements SQLModel definitions for meta-learning, resource management, and performance optimization
|
||||
"""
|
||||
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
@@ -102,8 +102,8 @@ class AgentPerformanceProfile(SQLModel, table=True):
|
||||
percentile_rank: float | None = None
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
last_assessed: datetime | None = None
|
||||
|
||||
# Additional data
|
||||
@@ -152,8 +152,8 @@ class MetaLearningModel(SQLModel, table=True):
|
||||
success_rate: float = Field(default=0.0, ge=0, le=1.0)
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
trained_at: datetime | None = None
|
||||
deployed_at: datetime | None = None
|
||||
|
||||
@@ -205,8 +205,8 @@ class ResourceAllocation(SQLModel, table=True):
|
||||
performance_improvement: float = Field(default=0.0)
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Additional data
|
||||
allocation_profile_meta_data: dict[str, Any] = Field(default={}, sa_column=Column(JSON))
|
||||
@@ -259,8 +259,8 @@ class PerformanceOptimization(SQLModel, table=True):
|
||||
rollback_available: bool = Field(default=True)
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
completed_at: datetime | None = None
|
||||
|
||||
# Additional data
|
||||
@@ -304,7 +304,7 @@ class AgentCapability(SQLModel, table=True):
|
||||
tool_proficiency: dict[str, float] = Field(default={}, sa_column=Column(JSON))
|
||||
|
||||
# Development history
|
||||
acquired_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
acquired_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
last_improved: datetime | None = None
|
||||
improvement_count: int = Field(default=0)
|
||||
|
||||
@@ -314,8 +314,8 @@ class AgentCapability(SQLModel, table=True):
|
||||
last_validated: datetime | None = None
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Additional data
|
||||
capability_profile_meta_data: dict[str, Any] = Field(default={}, sa_column=Column(JSON))
|
||||
@@ -365,8 +365,8 @@ class FusionModel(SQLModel, table=True):
|
||||
performance_stability: float = Field(default=0.0, ge=0, le=1.0)
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
trained_at: datetime | None = None
|
||||
deployed_at: datetime | None = None
|
||||
|
||||
@@ -420,8 +420,8 @@ class ReinforcementLearningConfig(SQLModel, table=True):
|
||||
deployment_performance: dict[str, float] = Field(default={}, sa_column=Column(JSON))
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
trained_at: datetime | None = None
|
||||
deployed_at: datetime | None = None
|
||||
|
||||
@@ -476,8 +476,8 @@ class CreativeCapability(SQLModel, table=True):
|
||||
last_evaluation: datetime | None = None
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Additional data
|
||||
creative_profile_meta_data: dict[str, Any] = Field(default={}, sa_column=Column(JSON))
|
||||
|
||||
@@ -6,7 +6,7 @@ Domain models for agent portfolio management, trading strategies, and risk asses
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from enum import StrEnum
|
||||
|
||||
from sqlalchemy import JSON, Column
|
||||
@@ -47,8 +47,8 @@ class PortfolioStrategy(SQLModel, table=True):
|
||||
rebalance_frequency: int = Field(default=86400) # Rebalancing frequency in seconds
|
||||
volatility_threshold: float = Field(default=15.0) # Volatility threshold for rebalancing
|
||||
is_active: bool = Field(default=True, index=True)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Relationships
|
||||
# DISABLED: portfolios: List["AgentPortfolio"] = Relationship(back_populates="strategy")
|
||||
@@ -68,9 +68,9 @@ class AgentPortfolio(SQLModel, table=True):
|
||||
risk_score: float = Field(default=0.0) # Risk score (0-100)
|
||||
risk_tolerance: float = Field(default=50.0) # Risk tolerance percentage
|
||||
is_active: bool = Field(default=True, index=True)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC), index=True)
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
last_rebalance: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True)
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
last_rebalance: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Relationships
|
||||
# DISABLED: strategy: PortfolioStrategy = Relationship(back_populates="portfolios")
|
||||
@@ -93,8 +93,8 @@ class PortfolioAsset(SQLModel, table=True):
|
||||
current_allocation: float = Field(default=0.0) # Current allocation percentage
|
||||
average_cost: float = Field(default=0.0) # Average cost basis
|
||||
unrealized_pnl: float = Field(default=0.0) # Unrealized profit/loss
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Relationships
|
||||
# DISABLED: portfolio: AgentPortfolio = Relationship(back_populates="assets")
|
||||
@@ -116,7 +116,7 @@ class PortfolioTrade(SQLModel, table=True):
|
||||
status: TradeStatus = Field(default=TradeStatus.PENDING, index=True)
|
||||
transaction_hash: str | None = Field(default=None, index=True)
|
||||
executed_at: datetime | None = Field(default=None, index=True)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC), index=True)
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True)
|
||||
|
||||
# Relationships
|
||||
# DISABLED: portfolio: AgentPortfolio = Relationship(back_populates="trades")
|
||||
@@ -140,7 +140,7 @@ class RiskMetrics(SQLModel, table=True):
|
||||
risk_level: RiskLevel = Field(default=RiskLevel.LOW, index=True)
|
||||
overall_risk_score: float = Field(default=0.0) # Overall risk score (0-100)
|
||||
stress_test_results: dict[str, float] = Field(default_factory=dict, sa_column=Column(JSON))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Relationships
|
||||
# DISABLED: portfolio: AgentPortfolio = Relationship(back_populates="risk_metrics")
|
||||
@@ -159,7 +159,7 @@ class RebalanceHistory(SQLModel, table=True):
|
||||
trades_executed: int = Field(default=0)
|
||||
rebalance_cost: float = Field(default=0.0) # Cost of rebalancing
|
||||
execution_time_ms: int = Field(default=0) # Execution time in milliseconds
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC), index=True)
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True)
|
||||
|
||||
|
||||
class PerformanceMetrics(SQLModel, table=True):
|
||||
@@ -184,9 +184,9 @@ class PerformanceMetrics(SQLModel, table=True):
|
||||
beta: float = Field(default=0.0) # Beta vs benchmark
|
||||
tracking_error: float = Field(default=0.0) # Tracking error
|
||||
information_ratio: float = Field(default=0.0) # Information ratio
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
period_start: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
period_end: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
period_start: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
period_end: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
class PortfolioAlert(SQLModel, table=True):
|
||||
@@ -202,7 +202,7 @@ class PortfolioAlert(SQLModel, table=True):
|
||||
meta_data: dict[str, str] = Field(default_factory=dict, sa_column=Column(JSON))
|
||||
is_acknowledged: bool = Field(default=False, index=True)
|
||||
acknowledged_at: datetime | None = Field(default=None)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC), index=True)
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True)
|
||||
resolved_at: datetime | None = Field(default=None)
|
||||
|
||||
|
||||
@@ -223,8 +223,8 @@ class StrategySignal(SQLModel, table=True):
|
||||
meta_data: dict[str, str] = Field(default_factory=dict, sa_column=Column(JSON))
|
||||
is_executed: bool = Field(default=False, index=True)
|
||||
executed_at: datetime | None = Field(default=None)
|
||||
expires_at: datetime = Field(default_factory=lambda: datetime.now(datetime.UTC) + timedelta(hours=24))
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC), index=True)
|
||||
expires_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc) + timedelta(hours=24))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True)
|
||||
|
||||
|
||||
class PortfolioSnapshot(SQLModel, table=True):
|
||||
@@ -243,7 +243,7 @@ class PortfolioSnapshot(SQLModel, table=True):
|
||||
geographic_allocation: dict[str, float] = Field(default_factory=dict, sa_column=Column(JSON))
|
||||
risk_metrics: dict[str, float] = Field(default_factory=dict, sa_column=Column(JSON))
|
||||
performance_metrics: dict[str, float] = Field(default_factory=dict, sa_column=Column(JSON))
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
class TradingRule(SQLModel, table=True):
|
||||
@@ -258,8 +258,8 @@ class TradingRule(SQLModel, table=True):
|
||||
parameters: dict[str, str] = Field(default_factory=dict, sa_column=Column(JSON))
|
||||
is_active: bool = Field(default=True, index=True)
|
||||
priority: int = Field(default=0) # Rule priority (higher = more important)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
class MarketCondition(SQLModel, table=True):
|
||||
@@ -277,5 +277,5 @@ class MarketCondition(SQLModel, table=True):
|
||||
trend_strength: float = Field(default=0.0) # Trend strength
|
||||
support_level: float = Field(default=0.0) # Support level
|
||||
resistance_level: float = Field(default=0.0) # Resistance level
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC), index=True)
|
||||
expires_at: datetime = Field(default_factory=lambda: datetime.now(datetime.UTC) + timedelta(hours=24))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True)
|
||||
expires_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc) + timedelta(hours=24))
|
||||
|
||||
@@ -6,7 +6,7 @@ Domain models for automated market making, liquidity pools, and swap transaction
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from enum import StrEnum
|
||||
|
||||
from sqlalchemy import JSON, Column
|
||||
@@ -59,8 +59,8 @@ class LiquidityPool(SQLModel, table=True):
|
||||
is_active: bool = Field(default=True, index=True)
|
||||
status: PoolStatus = Field(default=PoolStatus.ACTIVE, index=True)
|
||||
created_by: str = Field(index=True) # Creator address
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC), index=True)
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True)
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
last_trade_time: datetime | None = Field(default=None)
|
||||
|
||||
# Relationships
|
||||
@@ -88,8 +88,8 @@ class LiquidityPosition(SQLModel, table=True):
|
||||
fees_earned: float = Field(default=0.0) # Fees earned
|
||||
impermanent_loss: float = Field(default=0.0) # Impermanent loss
|
||||
status: LiquidityPositionStatus = Field(default=LiquidityPositionStatus.ACTIVE, index=True)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC), index=True)
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True)
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
last_deposit: datetime | None = Field(default=None)
|
||||
last_withdrawal: datetime | None = Field(default=None)
|
||||
|
||||
@@ -121,8 +121,8 @@ class SwapTransaction(SQLModel, table=True):
|
||||
gas_used: int | None = Field(default=None)
|
||||
gas_price: float | None = Field(default=None)
|
||||
executed_at: datetime | None = Field(default=None, index=True)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC), index=True)
|
||||
deadline: datetime = Field(default_factory=lambda: datetime.now(datetime.UTC) + timedelta(minutes=20))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True)
|
||||
deadline: datetime = Field(default_factory=lambda: datetime.now(timezone.utc) + timedelta(minutes=20))
|
||||
|
||||
# Relationships
|
||||
# DISABLED: pool: LiquidityPool = Relationship(back_populates="swaps")
|
||||
@@ -149,7 +149,7 @@ class PoolMetrics(SQLModel, table=True):
|
||||
impermanent_loss_24h: float = Field(default=0.0) # 24h impermanent loss
|
||||
liquidity_provider_count: int = Field(default=0) # Number of liquidity providers
|
||||
top_lps: dict[str, float] = Field(default_factory=dict, sa_column=Column(JSON)) # Top LPs by share
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Relationships
|
||||
# DISABLED: pool: LiquidityPool = Relationship(back_populates="metrics")
|
||||
@@ -168,10 +168,10 @@ class FeeStructure(SQLModel, table=True):
|
||||
volume_adjustment: float = Field(default=0.0) # Volume-based adjustment
|
||||
liquidity_adjustment: float = Field(default=0.0) # Liquidity-based adjustment
|
||||
time_adjustment: float = Field(default=0.0) # Time-based adjustment
|
||||
adjusted_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
expires_at: datetime = Field(default_factory=lambda: datetime.now(datetime.UTC) + timedelta(hours=24))
|
||||
adjusted_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
expires_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc) + timedelta(hours=24))
|
||||
adjustment_reason: str = Field(default="") # Reason for adjustment
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
class IncentiveProgram(SQLModel, table=True):
|
||||
@@ -192,10 +192,10 @@ class IncentiveProgram(SQLModel, table=True):
|
||||
maximum_liquidity: float = Field(default=0.0) # Maximum liquidity cap (0 = no cap)
|
||||
vesting_period_days: int = Field(default=0) # Vesting period (0 = no vesting)
|
||||
is_active: bool = Field(default=True, index=True)
|
||||
start_time: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
end_time: datetime = Field(default_factory=lambda: datetime.now(datetime.UTC) + timedelta(days=30))
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
start_time: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
end_time: datetime = Field(default_factory=lambda: datetime.now(timezone.utc) + timedelta(days=30))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Relationships
|
||||
# DISABLED: pool: LiquidityPool = Relationship(back_populates="incentives")
|
||||
@@ -220,7 +220,7 @@ class LiquidityReward(SQLModel, table=True):
|
||||
claim_transaction_hash: str | None = Field(default=None)
|
||||
vesting_start: datetime | None = Field(default=None)
|
||||
vesting_end: datetime | None = Field(default=None)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC), index=True)
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True)
|
||||
|
||||
# Relationships
|
||||
# DISABLED: program: IncentiveProgram = Relationship(back_populates="rewards")
|
||||
@@ -243,7 +243,7 @@ class FeeClaim(SQLModel, table=True):
|
||||
is_claimed: bool = Field(default=False, index=True)
|
||||
claimed_at: datetime | None = Field(default=None)
|
||||
claim_transaction_hash: str | None = Field(default=None)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC), index=True)
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True)
|
||||
|
||||
# Relationships
|
||||
# DISABLED: position: LiquidityPosition = Relationship(back_populates="fee_claims")
|
||||
@@ -260,8 +260,8 @@ class PoolConfiguration(SQLModel, table=True):
|
||||
config_value: str = Field(default="")
|
||||
config_type: str = Field(default="string") # string, number, boolean, json
|
||||
is_active: bool = Field(default=True)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
class PoolAlert(SQLModel, table=True):
|
||||
@@ -283,8 +283,8 @@ class PoolAlert(SQLModel, table=True):
|
||||
acknowledged_at: datetime | None = Field(default=None)
|
||||
is_resolved: bool = Field(default=False, index=True)
|
||||
resolved_at: datetime | None = Field(default=None)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC), index=True)
|
||||
expires_at: datetime = Field(default_factory=lambda: datetime.now(datetime.UTC) + timedelta(hours=24))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True)
|
||||
expires_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc) + timedelta(hours=24))
|
||||
|
||||
|
||||
class PoolSnapshot(SQLModel, table=True):
|
||||
@@ -310,7 +310,7 @@ class PoolSnapshot(SQLModel, table=True):
|
||||
average_slippage: float = Field(default=0.0)
|
||||
average_price_impact: float = Field(default=0.0)
|
||||
impermanent_loss: float = Field(default=0.0)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
class ArbitrageOpportunity(SQLModel, table=True):
|
||||
@@ -335,5 +335,5 @@ class ArbitrageOpportunity(SQLModel, table=True):
|
||||
executed_at: datetime | None = Field(default=None)
|
||||
execution_tx_hash: str | None = Field(default=None)
|
||||
actual_profit: float | None = Field(default=None)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC), index=True)
|
||||
expires_at: datetime = Field(default_factory=lambda: datetime.now(datetime.UTC) + timedelta(minutes=5))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True)
|
||||
expires_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc) + timedelta(minutes=5))
|
||||
|
||||
@@ -3,7 +3,7 @@ Marketplace Analytics Domain Models
|
||||
Implements SQLModel definitions for analytics, insights, and reporting
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
@@ -87,7 +87,7 @@ class MarketMetric(SQLModel, table=True):
|
||||
metric_meta_data: dict[str, Any] = Field(default={}, sa_column=Column(JSON))
|
||||
|
||||
# Timestamps
|
||||
recorded_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
recorded_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
period_start: datetime
|
||||
period_end: datetime
|
||||
|
||||
@@ -134,8 +134,8 @@ class MarketInsight(SQLModel, table=True):
|
||||
resolved_at: datetime | None = None
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
expires_at: datetime | None = None
|
||||
|
||||
# Additional data
|
||||
@@ -184,9 +184,9 @@ class AnalyticsReport(SQLModel, table=True):
|
||||
recipients: list[str] = Field(default=[], sa_column=Column(JSON))
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
generated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
generated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
delivered_at: datetime | None = None
|
||||
|
||||
# Additional data
|
||||
@@ -230,8 +230,8 @@ class DashboardConfig(SQLModel, table=True):
|
||||
last_modified_by: str | None = None
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
last_viewed_at: datetime | None = None
|
||||
|
||||
# Additional data
|
||||
@@ -281,8 +281,8 @@ class DataCollectionJob(SQLModel, table=True):
|
||||
cpu_usage: float = Field(default=0.0) # percentage
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Additional data
|
||||
job_metric_meta_data: dict[str, Any] = Field(default={}, sa_column=Column(JSON))
|
||||
@@ -331,8 +331,8 @@ class AlertRule(SQLModel, table=True):
|
||||
trigger_count: int = Field(default=0)
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Additional data
|
||||
rule_metric_meta_data: dict[str, Any] = Field(default={}, sa_column=Column(JSON))
|
||||
@@ -383,8 +383,8 @@ class AnalyticsAlert(SQLModel, table=True):
|
||||
delivery_status: dict[str, str] = Field(default={}, sa_column=Column(JSON))
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
expires_at: datetime | None = None
|
||||
|
||||
# Additional data
|
||||
@@ -434,8 +434,8 @@ class UserPreference(SQLModel, table=True):
|
||||
anonymous_usage: bool = Field(default=False)
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
last_login: datetime | None = None
|
||||
|
||||
# Additional preferences
|
||||
|
||||
@@ -6,7 +6,7 @@ Domain models for managing trustless cross-chain atomic swaps between agents.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from enum import StrEnum
|
||||
from uuid import uuid4
|
||||
|
||||
@@ -60,5 +60,5 @@ class AtomicSwapOrder(SQLModel, table=True):
|
||||
|
||||
status: SwapStatus = Field(default=SwapStatus.CREATED, index=True)
|
||||
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
@@ -4,7 +4,7 @@ Database models for AI agent bounty system with ZK-proof verification
|
||||
"""
|
||||
|
||||
import uuid
|
||||
from datetime import datetime, timedelta
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
|
||||
@@ -70,7 +70,7 @@ class Bounty(SQLModel, table=True):
|
||||
|
||||
# Timing
|
||||
deadline: datetime = Field(index=True)
|
||||
creation_time: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
creation_time: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Limits
|
||||
max_submissions: int = Field(default=100)
|
||||
@@ -137,7 +137,7 @@ class BountySubmission(SQLModel, table=True):
|
||||
dispute_resolved: bool = Field(default=False)
|
||||
|
||||
# Timing
|
||||
submission_time: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
submission_time: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Metadata
|
||||
submission_data: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON))
|
||||
@@ -168,13 +168,13 @@ class AgentStake(SQLModel, table=True):
|
||||
# Stake details
|
||||
amount: float = Field(index=True)
|
||||
lock_period: int = Field(default=30) # days
|
||||
start_time: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
start_time: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
end_time: datetime
|
||||
|
||||
# Status and rewards
|
||||
status: StakeStatus = Field(default=StakeStatus.ACTIVE)
|
||||
accumulated_rewards: float = Field(default=0.0)
|
||||
last_reward_time: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
last_reward_time: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# APY and performance
|
||||
current_apy: float = Field(default=5.0) # percentage
|
||||
@@ -226,7 +226,7 @@ class AgentMetrics(SQLModel, table=True):
|
||||
reputation_score: float = Field(default=0.0)
|
||||
|
||||
# Timing
|
||||
last_update_time: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
last_update_time: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
first_submission_time: datetime | None = Field(default=None)
|
||||
|
||||
# Additional metrics
|
||||
@@ -271,7 +271,7 @@ class StakingPool(SQLModel, table=True):
|
||||
active_stakers: list[str] = Field(default_factory=list, sa_column=Column(JSON))
|
||||
|
||||
# Distribution
|
||||
last_distribution_time: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
last_distribution_time: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
distribution_frequency: int = Field(default=1) # days
|
||||
|
||||
# Pool configuration
|
||||
@@ -309,7 +309,7 @@ class BountyIntegration(SQLModel, table=True):
|
||||
|
||||
# Status and timing
|
||||
status: BountyStatus = Field(default=BountyStatus.CREATED)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
processed_at: datetime | None = Field(default=None)
|
||||
|
||||
# Processing information
|
||||
@@ -393,7 +393,7 @@ class EcosystemMetrics(SQLModel, table=True):
|
||||
metrics_id: str = Field(primary_key=True, default_factory=lambda: f"eco_{uuid.uuid4().hex[:8]}")
|
||||
|
||||
# Time period
|
||||
timestamp: datetime = Field(default_factory=datetime.now(datetime.UTC), index=True)
|
||||
timestamp: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True)
|
||||
period_type: str = Field(default="hourly") # hourly, daily, weekly
|
||||
|
||||
# Developer metrics
|
||||
|
||||
@@ -3,7 +3,7 @@ Agent Certification and Partnership Domain Models
|
||||
Implements SQLModel definitions for certification, verification, and partnership programs
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
@@ -80,7 +80,7 @@ class AgentCertification(SQLModel, table=True):
|
||||
|
||||
# Issuance information
|
||||
issued_by: str = Field(index=True) # Who issued the certification
|
||||
issued_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
issued_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
expires_at: datetime | None = None
|
||||
verification_hash: str = Field(max_length=64) # Blockchain verification hash
|
||||
|
||||
@@ -142,9 +142,9 @@ class CertificationRequirement(SQLModel, table=True):
|
||||
weight: float = Field(default=1.0) # Importance weight
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
effective_date: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
effective_date: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
expiry_date: datetime | None = None
|
||||
|
||||
# Additional data
|
||||
@@ -167,7 +167,7 @@ class VerificationRecord(SQLModel, table=True):
|
||||
|
||||
# Request information
|
||||
requested_by: str = Field(index=True)
|
||||
requested_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
requested_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
priority: str = Field(default="normal") # low, normal, high, urgent
|
||||
|
||||
# Verification process
|
||||
@@ -242,8 +242,8 @@ class PartnershipProgram(SQLModel, table=True):
|
||||
current_participants: int = Field(default=0)
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
launched_at: datetime | None = None
|
||||
expires_at: datetime | None = None
|
||||
|
||||
@@ -268,7 +268,7 @@ class AgentPartnership(SQLModel, table=True):
|
||||
current_tier: str = Field(default="basic")
|
||||
|
||||
# Application and approval
|
||||
applied_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
applied_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
approved_by: str | None = None
|
||||
approved_at: datetime | None = None
|
||||
rejection_reasons: list[str] = Field(default=[], sa_column=Column(JSON))
|
||||
@@ -294,8 +294,8 @@ class AgentPartnership(SQLModel, table=True):
|
||||
agreement_expires_at: datetime | None = None
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
last_activity: datetime | None = None
|
||||
|
||||
# Additional data
|
||||
@@ -339,9 +339,9 @@ class AchievementBadge(SQLModel, table=True):
|
||||
current_awards: int = Field(default=0)
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
available_from: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
available_from: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
available_until: datetime | None = None
|
||||
|
||||
# Additional data
|
||||
@@ -363,7 +363,7 @@ class AgentBadge(SQLModel, table=True):
|
||||
|
||||
# Award details
|
||||
awarded_by: str = Field(index=True) # System or user who awarded the badge
|
||||
awarded_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
awarded_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
award_reason: str = Field(default="", max_length=500)
|
||||
|
||||
# Achievement context
|
||||
@@ -391,8 +391,8 @@ class AgentBadge(SQLModel, table=True):
|
||||
congratulation_count: int = Field(default=0)
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
last_viewed_at: datetime | None = None
|
||||
|
||||
# Additional data
|
||||
@@ -416,7 +416,7 @@ class CertificationAudit(SQLModel, table=True):
|
||||
|
||||
# Audit scheduling
|
||||
scheduled_by: str = Field(index=True)
|
||||
scheduled_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
scheduled_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
started_at: datetime | None = None
|
||||
completed_at: datetime | None = None
|
||||
|
||||
@@ -449,8 +449,8 @@ class CertificationAudit(SQLModel, table=True):
|
||||
evidence_documents: list[str] = Field(default=[], sa_column=Column(JSON))
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Additional data
|
||||
audit_cert_meta_data: dict[str, Any] = Field(default={}, sa_column=Column(JSON))
|
||||
|
||||
@@ -4,7 +4,7 @@ Database models for OpenClaw agent community, third-party solutions, and innovat
|
||||
"""
|
||||
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
|
||||
@@ -61,8 +61,8 @@ class DeveloperProfile(SQLModel, table=True):
|
||||
github_handle: str | None = None
|
||||
website: str | None = None
|
||||
|
||||
joined_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
last_active: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
joined_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
last_active: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
class AgentSolution(SQLModel, table=True):
|
||||
@@ -91,8 +91,8 @@ class AgentSolution(SQLModel, table=True):
|
||||
|
||||
solution_meta_data: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON))
|
||||
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
published_at: datetime | None = None
|
||||
|
||||
|
||||
@@ -116,7 +116,7 @@ class InnovationLab(SQLModel, table=True):
|
||||
milestones: list[dict[str, Any]] = Field(default_factory=list, sa_column=Column(JSON))
|
||||
publications: list[dict[str, Any]] = Field(default_factory=list, sa_column=Column(JSON))
|
||||
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
target_completion: datetime | None = None
|
||||
|
||||
|
||||
@@ -139,8 +139,8 @@ class CommunityPost(SQLModel, table=True):
|
||||
|
||||
parent_post_id: str | None = Field(default=None, foreign_key="community_posts.post_id")
|
||||
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
class Hackathon(SQLModel, table=True):
|
||||
@@ -165,4 +165,4 @@ class Hackathon(SQLModel, table=True):
|
||||
registration_end: datetime
|
||||
event_start: datetime
|
||||
event_end: datetime
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
@@ -6,7 +6,7 @@ Domain models for cross-chain asset transfers, bridge requests, and validator ma
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from enum import StrEnum
|
||||
|
||||
from sqlalchemy import JSON, Column
|
||||
@@ -75,12 +75,12 @@ class BridgeRequest(SQLModel, table=True):
|
||||
required_confirmations: int = Field(default=3) # Required confirmations
|
||||
dispute_reason: str | None = Field(default=None)
|
||||
resolution_action: str | None = Field(default=None)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC), index=True)
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True)
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
confirmed_at: datetime | None = Field(default=None)
|
||||
completed_at: datetime | None = Field(default=None)
|
||||
resolved_at: datetime | None = Field(default=None)
|
||||
expires_at: datetime = Field(default_factory=lambda: datetime.now(datetime.UTC) + timedelta(hours=24))
|
||||
expires_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc) + timedelta(hours=24))
|
||||
|
||||
# Relationships
|
||||
# transactions: List["BridgeTransaction"] = Relationship(back_populates="bridge_request")
|
||||
@@ -107,8 +107,8 @@ class SupportedToken(SQLModel, table=True):
|
||||
original_token: str | None = Field(default=None) # Original token address for wrapped tokens
|
||||
supported_chains: list[int] = Field(default_factory=list, sa_column=Column(JSON))
|
||||
bridge_contracts: dict[int, str] = Field(default_factory=dict, sa_column=Column(JSON)) # Chain ID -> Contract address
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
class ChainConfig(SQLModel, table=True):
|
||||
@@ -135,8 +135,8 @@ class ChainConfig(SQLModel, table=True):
|
||||
is_testnet: bool = Field(default=False)
|
||||
requires_validator: bool = Field(default=True) # Whether validator confirmation is required
|
||||
validator_threshold: float = Field(default=0.67) # Validator threshold percentage
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
class Validator(SQLModel, table=True):
|
||||
@@ -162,8 +162,8 @@ class Validator(SQLModel, table=True):
|
||||
is_active: bool = Field(default=True, index=True)
|
||||
supported_chains: list[int] = Field(default_factory=list, sa_column=Column(JSON))
|
||||
val_meta_data: dict[str, str] = Field(default_factory=dict, sa_column=Column(JSON))
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Relationships
|
||||
# transactions: List["BridgeTransaction"] = Relationship(back_populates="validator")
|
||||
@@ -190,7 +190,7 @@ class BridgeTransaction(SQLModel, table=True):
|
||||
is_successful: bool = Field(default=False)
|
||||
error_message: str | None = Field(default=None)
|
||||
retry_count: int = Field(default=0)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC), index=True)
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True)
|
||||
confirmed_at: datetime | None = Field(default=None)
|
||||
completed_at: datetime | None = Field(default=None)
|
||||
|
||||
@@ -219,8 +219,8 @@ class BridgeDispute(SQLModel, table=True):
|
||||
investigator_address: str | None = Field(default=None)
|
||||
investigation_notes: str | None = Field(default=None)
|
||||
is_resolved: bool = Field(default=False, index=True)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC), index=True)
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True)
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
resolved_at: datetime | None = Field(default=None)
|
||||
|
||||
# Relationships
|
||||
@@ -241,8 +241,8 @@ class MerkleProof(SQLModel, table=True):
|
||||
tree_depth: int = Field(default=0) # Tree depth
|
||||
is_valid: bool = Field(default=False)
|
||||
verified_at: datetime | None = Field(default=None)
|
||||
expires_at: datetime = Field(default_factory=lambda: datetime.now(datetime.UTC) + timedelta(hours=24))
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
expires_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc) + timedelta(hours=24))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
class BridgeStatistics(SQLModel, table=True):
|
||||
@@ -264,7 +264,7 @@ class BridgeStatistics(SQLModel, table=True):
|
||||
unique_users: int = Field(default=0) # Unique users for the day
|
||||
peak_hour_volume: float = Field(default=0.0) # Peak hour volume
|
||||
peak_hour_transactions: int = Field(default=0) # Peak hour transactions
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
class BridgeAlert(SQLModel, table=True):
|
||||
@@ -290,8 +290,8 @@ class BridgeAlert(SQLModel, table=True):
|
||||
is_resolved: bool = Field(default=False, index=True)
|
||||
resolved_at: datetime | None = Field(default=None)
|
||||
resolution_notes: str | None = Field(default=None)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC), index=True)
|
||||
expires_at: datetime = Field(default_factory=lambda: datetime.now(datetime.UTC) + timedelta(hours=24))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True)
|
||||
expires_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc) + timedelta(hours=24))
|
||||
|
||||
|
||||
class BridgeConfiguration(SQLModel, table=True):
|
||||
@@ -305,8 +305,8 @@ class BridgeConfiguration(SQLModel, table=True):
|
||||
config_type: str = Field(default="string") # string, number, boolean, json
|
||||
description: str = Field(default="")
|
||||
is_active: bool = Field(default=True)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
class LiquidityPool(SQLModel, table=True):
|
||||
@@ -323,9 +323,9 @@ class LiquidityPool(SQLModel, table=True):
|
||||
utilized_liquidity: float = Field(default=0.0) # Utilized liquidity
|
||||
utilization_rate: float = Field(default=0.0) # Utilization rate
|
||||
interest_rate: float = Field(default=0.0) # Interest rate
|
||||
last_updated: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
last_updated: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
is_active: bool = Field(default=True, index=True)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
class BridgeSnapshot(SQLModel, table=True):
|
||||
@@ -347,7 +347,7 @@ class BridgeSnapshot(SQLModel, table=True):
|
||||
bridge_utilization: float = Field(default=0.0)
|
||||
top_tokens: dict[str, float] = Field(default_factory=dict, sa_column=Column(JSON))
|
||||
top_chains: dict[str, int] = Field(default_factory=dict, sa_column=Column(JSON))
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
class ValidatorReward(SQLModel, table=True):
|
||||
@@ -365,4 +365,4 @@ class ValidatorReward(SQLModel, table=True):
|
||||
is_claimed: bool = Field(default=False, index=True)
|
||||
claimed_at: datetime | None = Field(default=None)
|
||||
claim_transaction_hash: str | None = Field(default=None)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC), index=True)
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True)
|
||||
|
||||
@@ -3,7 +3,7 @@ Cross-Chain Reputation Extensions
|
||||
Extends the existing reputation system with cross-chain capabilities
|
||||
"""
|
||||
|
||||
from datetime import date, datetime
|
||||
from datetime import date, datetime, timezone
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
@@ -38,8 +38,8 @@ class CrossChainReputationConfig(SQLModel, table=True):
|
||||
configuration_data: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON))
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
class CrossChainReputationAggregation(SQLModel, table=True):
|
||||
@@ -72,8 +72,8 @@ class CrossChainReputationAggregation(SQLModel, table=True):
|
||||
verification_details: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON))
|
||||
|
||||
# Timestamps
|
||||
last_updated: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
last_updated: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Indexes
|
||||
__table_args__ = {
|
||||
@@ -111,7 +111,7 @@ class CrossChainReputationEvent(SQLModel, table=True):
|
||||
verified: bool = Field(default=False)
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
processed_at: datetime | None = None
|
||||
|
||||
# Indexes
|
||||
@@ -153,8 +153,8 @@ class ReputationMetrics(SQLModel, table=True):
|
||||
chain_diversity_score: float = Field(default=0.0)
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
# Request/Response Models for Cross-Chain API
|
||||
|
||||
@@ -6,7 +6,7 @@ Domain models for managing multi-jurisdictional DAOs, regional councils, and glo
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from enum import StrEnum
|
||||
from uuid import uuid4
|
||||
|
||||
@@ -46,8 +46,8 @@ class DAOMember(SQLModel, table=True):
|
||||
is_council_member: bool = Field(default=False)
|
||||
council_region: str | None = Field(default=None, index=True)
|
||||
|
||||
joined_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
last_active: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
joined_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
last_active: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Relationships
|
||||
# DISABLED: votes: List["Vote"] = Relationship(back_populates="member")
|
||||
@@ -76,10 +76,10 @@ class DAOProposal(SQLModel, table=True):
|
||||
|
||||
execution_payload: dict[str, str] = Field(default_factory=dict, sa_column=Column(JSON))
|
||||
|
||||
start_time: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
end_time: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
start_time: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
end_time: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Relationships
|
||||
# DISABLED: votes: List["Vote"] = Relationship(back_populates="proposal")
|
||||
@@ -98,7 +98,7 @@ class Vote(SQLModel, table=True):
|
||||
weight: float = Field()
|
||||
|
||||
tx_hash: str | None = Field(default=None)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Relationships
|
||||
# DISABLED: proposal: DAOProposal = Relationship(back_populates="votes")
|
||||
@@ -120,4 +120,4 @@ class TreasuryAllocation(SQLModel, table=True):
|
||||
purpose: str = Field()
|
||||
|
||||
tx_hash: str | None = Field(default=None)
|
||||
executed_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
executed_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
@@ -6,7 +6,7 @@ Domain models for managing agent memory and knowledge graphs on IPFS/Filecoin.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from enum import StrEnum
|
||||
from uuid import uuid4
|
||||
|
||||
@@ -55,5 +55,5 @@ class AgentMemoryNode(SQLModel, table=True):
|
||||
# Blockchain Anchoring
|
||||
anchor_tx_hash: str | None = Field(default=None)
|
||||
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
@@ -6,7 +6,7 @@ Domain models for managing the developer ecosystem, bounties, certifications, an
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from enum import StrEnum
|
||||
from uuid import uuid4
|
||||
|
||||
@@ -45,8 +45,8 @@ class DeveloperProfile(SQLModel, table=True):
|
||||
skills: list[str] = Field(default_factory=list, sa_column=Column(JSON))
|
||||
|
||||
is_active: bool = Field(default=True)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Relationships
|
||||
# DISABLED: certifications: List["DeveloperCertification"] = Relationship(back_populates="developer")
|
||||
@@ -65,7 +65,7 @@ class DeveloperCertification(SQLModel, table=True):
|
||||
level: CertificationLevel = Field(default=CertificationLevel.BEGINNER)
|
||||
|
||||
issued_by: str = Field() # Could be an agent or a DAO entity
|
||||
issued_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
issued_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
expires_at: datetime | None = Field(default=None)
|
||||
|
||||
ipfs_credential_cid: str | None = Field(default=None) # Proof of certification
|
||||
@@ -90,7 +90,7 @@ class RegionalHub(SQLModel, table=True):
|
||||
budget_allocation: float = Field(default=0.0)
|
||||
spent_budget: float = Field(default=0.0)
|
||||
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
class BountyTask(SQLModel, table=True):
|
||||
@@ -114,8 +114,8 @@ class BountyTask(SQLModel, table=True):
|
||||
assigned_developer_id: str | None = Field(foreign_key="developer_profile.id", default=None)
|
||||
|
||||
deadline: datetime | None = Field(default=None)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Relationships
|
||||
# DISABLED: submissions: List["BountySubmission"] = Relationship(back_populates="bounty")
|
||||
@@ -139,7 +139,7 @@ class BountySubmission(SQLModel, table=True):
|
||||
|
||||
tx_hash_reward: str | None = Field(default=None) # Hash of the reward payout transaction
|
||||
|
||||
submitted_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
submitted_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
reviewed_at: datetime | None = Field(default=None)
|
||||
|
||||
# Relationships
|
||||
|
||||
@@ -6,7 +6,7 @@ Domain models for managing cross-agent knowledge sharing and collaborative model
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from enum import StrEnum
|
||||
from uuid import uuid4
|
||||
|
||||
@@ -55,8 +55,8 @@ class FederatedLearningSession(SQLModel, table=True):
|
||||
|
||||
global_model_cid: str | None = Field(default=None) # Final aggregated model
|
||||
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Relationships
|
||||
# DISABLED: participants: List["TrainingParticipant"] = Relationship(back_populates="session")
|
||||
@@ -79,8 +79,8 @@ class TrainingParticipant(SQLModel, table=True):
|
||||
reputation_score_at_join: float = Field(default=0.0)
|
||||
earned_reward: float = Field(default=0.0)
|
||||
|
||||
joined_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
joined_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Relationships
|
||||
# DISABLED: session: FederatedLearningSession = Relationship(back_populates="participants")
|
||||
@@ -102,7 +102,7 @@ class TrainingRound(SQLModel, table=True):
|
||||
|
||||
metrics: dict[str, float] = Field(default_factory=dict, sa_column=Column(JSON)) # e.g. loss, accuracy
|
||||
|
||||
started_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
started_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
completed_at: datetime | None = Field(default=None)
|
||||
|
||||
# Relationships
|
||||
@@ -125,7 +125,7 @@ class LocalModelUpdate(SQLModel, table=True):
|
||||
is_aggregated: bool = Field(default=False)
|
||||
rejected_reason: str | None = Field(default=None) # e.g. "outlier", "failed zk verification"
|
||||
|
||||
submitted_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
submitted_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Relationships
|
||||
# DISABLED: round: TrainingRound = Relationship(back_populates="updates")
|
||||
|
||||
@@ -5,7 +5,7 @@ Domain models for global marketplace operations, multi-region support, and cross
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
@@ -71,8 +71,8 @@ class MarketplaceRegion(SQLModel, table=True):
|
||||
error_rate: float = Field(default=0.0)
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Indexes
|
||||
__table_args__ = {
|
||||
@@ -104,8 +104,8 @@ class GlobalMarketplaceConfig(SQLModel, table=True):
|
||||
allowed_values: list[str] = Field(default_factory=list, sa_column=Column(JSON))
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
last_modified_by: str | None = Field(default=None)
|
||||
|
||||
# Indexes
|
||||
@@ -153,8 +153,8 @@ class GlobalMarketplaceOffer(SQLModel, table=True):
|
||||
cross_chain_pricing: dict[int, float] = Field(default_factory=dict, sa_column=Column(JSON))
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
expires_at: datetime | None = Field(default=None)
|
||||
|
||||
# Indexes
|
||||
@@ -201,8 +201,8 @@ class GlobalMarketplaceTransaction(SQLModel, table=True):
|
||||
delivery_status: str = Field(default="pending") # pending, delivered, failed
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
confirmed_at: datetime | None = Field(default=None)
|
||||
completed_at: datetime | None = Field(default=None)
|
||||
|
||||
@@ -266,8 +266,8 @@ class GlobalMarketplaceAnalytics(SQLModel, table=True):
|
||||
analytics_data: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON))
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Indexes
|
||||
__table_args__ = {
|
||||
@@ -313,9 +313,9 @@ class GlobalMarketplaceGovernance(SQLModel, table=True):
|
||||
version: int = Field(default=1)
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
effective_from: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
effective_from: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
expires_at: datetime | None = Field(default=None)
|
||||
|
||||
# Indexes
|
||||
|
||||
@@ -4,7 +4,7 @@ Database models for OpenClaw DAO, voting, proposals, and governance analytics
|
||||
"""
|
||||
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
|
||||
@@ -51,7 +51,7 @@ class GovernanceProfile(SQLModel, table=True):
|
||||
|
||||
delegate_to: str | None = Field(default=None) # Profile ID they delegate their vote to
|
||||
|
||||
joined_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
joined_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
last_voted_at: datetime | None = None
|
||||
|
||||
|
||||
@@ -81,7 +81,7 @@ class Proposal(SQLModel, table=True):
|
||||
snapshot_block: int | None = Field(default=None)
|
||||
snapshot_timestamp: datetime | None = Field(default=None)
|
||||
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
voting_starts: datetime
|
||||
voting_ends: datetime
|
||||
executed_at: datetime | None = None
|
||||
@@ -102,7 +102,7 @@ class Vote(SQLModel, table=True):
|
||||
power_at_snapshot: float = Field(default=0.0)
|
||||
delegated_power_at_snapshot: float = Field(default=0.0)
|
||||
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
class DaoTreasury(SQLModel, table=True):
|
||||
@@ -117,7 +117,7 @@ class DaoTreasury(SQLModel, table=True):
|
||||
|
||||
asset_breakdown: dict[str, float] = Field(default_factory=dict, sa_column=Column(JSON))
|
||||
|
||||
last_updated: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
last_updated: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
class TransparencyReport(SQLModel, table=True):
|
||||
@@ -138,4 +138,4 @@ class TransparencyReport(SQLModel, table=True):
|
||||
|
||||
metrics: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON))
|
||||
|
||||
generated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
generated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from enum import StrEnum
|
||||
from uuid import uuid4
|
||||
|
||||
@@ -36,7 +36,7 @@ class GPURegistry(SQLModel, table=True):
|
||||
capabilities: list = Field(default_factory=list, sa_column=Column(JSON, nullable=False))
|
||||
average_rating: float = Field(default=0.0)
|
||||
total_reviews: int = Field(default=0)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC), nullable=False, index=True)
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), nullable=False, index=True)
|
||||
|
||||
|
||||
class ConsumerGPUProfile(SQLModel, table=True):
|
||||
@@ -84,8 +84,8 @@ class ConsumerGPUProfile(SQLModel, table=True):
|
||||
edge_premium_multiplier: float = Field(default=1.0)
|
||||
availability_score: float = Field(default=1.0)
|
||||
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
class EdgeGPUMetrics(SQLModel, table=True):
|
||||
@@ -119,7 +119,7 @@ class EdgeGPUMetrics(SQLModel, table=True):
|
||||
isp: str | None = Field(default=None)
|
||||
connection_type: str | None = Field(default=None)
|
||||
|
||||
timestamp: datetime = Field(default_factory=datetime.now(datetime.UTC), index=True)
|
||||
timestamp: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True)
|
||||
|
||||
|
||||
class GPUBooking(SQLModel, table=True):
|
||||
@@ -135,9 +135,9 @@ class GPUBooking(SQLModel, table=True):
|
||||
duration_hours: float = Field(default=0.0)
|
||||
total_cost: float = Field(default=0.0)
|
||||
status: str = Field(default="active", index=True) # active, completed, cancelled
|
||||
start_time: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
start_time: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
end_time: datetime | None = Field(default=None)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC), nullable=False)
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), nullable=False)
|
||||
|
||||
|
||||
class GPUReview(SQLModel, table=True):
|
||||
@@ -151,4 +151,4 @@ class GPUReview(SQLModel, table=True):
|
||||
user_id: str = Field(default="")
|
||||
rating: int = Field(ge=1, le=5)
|
||||
comment: str = Field(default="")
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC), nullable=False, index=True)
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), nullable=False, index=True)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Dict
|
||||
from uuid import uuid4
|
||||
|
||||
@@ -20,8 +20,8 @@ class Job(SQLModel, table=True):
|
||||
constraints: Dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON, nullable=False))
|
||||
|
||||
ttl_seconds: int = Field(default=900)
|
||||
requested_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
expires_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
requested_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
expires_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
assigned_miner_id: str | None = Field(default=None, index=True)
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from uuid import uuid4
|
||||
|
||||
from sqlalchemy import JSON, Column
|
||||
@@ -15,4 +15,4 @@ class JobReceipt(SQLModel, table=True):
|
||||
job_id: str = Field(index=True, foreign_key="job.id")
|
||||
receipt_id: str = Field(index=True)
|
||||
payload: dict = Field(sa_column=Column(JSON, nullable=False))
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC), index=True)
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from uuid import uuid4
|
||||
|
||||
from sqlalchemy import JSON, Column
|
||||
@@ -17,7 +17,7 @@ class MarketplaceOffer(SQLModel, table=True):
|
||||
price: float = Field(default=0.0, nullable=False)
|
||||
sla: str = Field(default="")
|
||||
status: str = Field(default="open", max_length=20)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC), nullable=False, index=True)
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), nullable=False, index=True)
|
||||
attributes: dict = Field(default_factory=dict, sa_column=Column(JSON, nullable=False))
|
||||
# GPU-specific fields
|
||||
gpu_model: str | None = Field(default=None, index=True)
|
||||
@@ -38,4 +38,4 @@ class MarketplaceBid(SQLModel, table=True):
|
||||
price: float = Field(default=0.0, nullable=False)
|
||||
notes: str | None = Field(default=None)
|
||||
status: str = Field(default="pending", nullable=False)
|
||||
submitted_at: datetime = Field(default_factory=datetime.now(datetime.UTC), nullable=False, index=True)
|
||||
submitted_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), nullable=False, index=True)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Dict
|
||||
|
||||
from sqlalchemy import JSON, Column
|
||||
@@ -18,7 +18,7 @@ class Miner(SQLModel, table=True):
|
||||
status: str = Field(default="ONLINE", index=True)
|
||||
inflight: int = Field(default=0)
|
||||
extra_metadata: Dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON, nullable=False))
|
||||
last_heartbeat: datetime = Field(default_factory=datetime.now(datetime.UTC), index=True)
|
||||
last_heartbeat: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True)
|
||||
session_token: str | None = None
|
||||
last_job_at: datetime | None = Field(default=None, index=True)
|
||||
jobs_completed: int = Field(default=0)
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from uuid import uuid4
|
||||
|
||||
from sqlalchemy import JSON, Column, Numeric
|
||||
@@ -33,8 +33,8 @@ class JobPayment(SQLModel, table=True):
|
||||
refund_transaction_hash: str | None = Field(default=None, max_length=100)
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
escrowed_at: datetime | None = None
|
||||
released_at: datetime | None = None
|
||||
refunded_at: datetime | None = None
|
||||
@@ -67,7 +67,7 @@ class PaymentEscrow(SQLModel, table=True):
|
||||
is_refunded: bool = Field(default=False)
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
released_at: datetime | None = None
|
||||
refunded_at: datetime | None = None
|
||||
expires_at: datetime | None = None
|
||||
|
||||
@@ -5,7 +5,7 @@ SQLModel definitions for pricing history, strategies, and market metrics
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
@@ -92,8 +92,8 @@ class PricingHistory(SQLModel, table=True):
|
||||
recommendation_followed: bool | None = None
|
||||
|
||||
# Metadata
|
||||
timestamp: datetime = Field(default_factory=datetime.now(datetime.UTC), index=True)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
timestamp: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True)
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Additional context
|
||||
competitor_prices: list[float] = Field(default_factory=list, sa_column=Column(JSON))
|
||||
@@ -157,8 +157,8 @@ class ProviderPricingStrategy(SQLModel, table=True):
|
||||
strategy_effectiveness_score: float = Field(default=0.0)
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
last_applied: datetime | None = None
|
||||
expires_at: datetime | None = None
|
||||
|
||||
@@ -225,8 +225,8 @@ class MarketMetrics(SQLModel, table=True):
|
||||
completeness_score: float
|
||||
|
||||
# Timestamps
|
||||
timestamp: datetime = Field(default_factory=datetime.now(datetime.UTC), index=True)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
timestamp: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True)
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Additional metrics
|
||||
custom_metrics: dict[str, float] = Field(default_factory=dict, sa_column=Column(JSON))
|
||||
@@ -278,7 +278,7 @@ class PriceForecast(SQLModel, table=True):
|
||||
market_conditions_at_forecast: dict[str, float] = Field(default_factory=dict, sa_column=Column(JSON))
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC), index=True)
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True)
|
||||
target_timestamp: datetime = Field(index=True) # When forecast is for
|
||||
evaluated_at: datetime | None = None # When forecast was evaluated
|
||||
|
||||
@@ -344,8 +344,8 @@ class PricingOptimization(SQLModel, table=True):
|
||||
recommendations: list[str] = Field(default_factory=list, sa_column=Column(JSON))
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC), index=True)
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True)
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
completed_at: datetime | None = None
|
||||
|
||||
# Audit trail
|
||||
@@ -406,9 +406,9 @@ class PricingAlert(SQLModel, table=True):
|
||||
customer_impact_estimate: str | None = None
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC), index=True)
|
||||
first_seen: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
last_seen: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True)
|
||||
first_seen: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
last_seen: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
acknowledged_at: datetime | None = None
|
||||
resolved_at: datetime | None = None
|
||||
|
||||
@@ -470,8 +470,8 @@ class PricingRule(SQLModel, table=True):
|
||||
business_impact: float | None = None
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
expires_at: datetime | None = None
|
||||
|
||||
# Audit trail
|
||||
@@ -534,8 +534,8 @@ class PricingAuditLog(SQLModel, table=True):
|
||||
ip_address: str | None = None
|
||||
|
||||
# Timestamps
|
||||
timestamp: datetime = Field(default_factory=datetime.now(datetime.UTC), index=True)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
timestamp: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True)
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Additional metadata
|
||||
meta_data: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON))
|
||||
|
||||
@@ -4,7 +4,7 @@ Defines various pricing strategies and their configurations for dynamic pricing
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
|
||||
@@ -92,7 +92,7 @@ class StrategyRule:
|
||||
action: str # Action to take when condition is met
|
||||
priority: StrategyPriority
|
||||
enabled: bool = True
|
||||
created_at: datetime = field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Rule execution tracking
|
||||
execution_count: int = 0
|
||||
@@ -124,8 +124,8 @@ class PricingStrategyConfig:
|
||||
regions: list[str] = field(default_factory=list)
|
||||
|
||||
# Performance tracking
|
||||
created_at: datetime = field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
last_applied: datetime | None = None
|
||||
|
||||
# Strategy effectiveness metrics
|
||||
@@ -515,7 +515,7 @@ class StrategyOptimizer:
|
||||
if strategy_id not in self.performance_history:
|
||||
self.performance_history[strategy_id] = []
|
||||
|
||||
self.performance_history[strategy_id].append({"timestamp": datetime.now(datetime.UTC), "performance": performance_data})
|
||||
self.performance_history[strategy_id].append({"timestamp": datetime.now(timezone.utc), "performance": performance_data})
|
||||
|
||||
# Apply optimization rules
|
||||
optimized_config = self._apply_optimization_rules(strategy_config, performance_data)
|
||||
|
||||
@@ -3,7 +3,7 @@ Agent Reputation and Trust System Domain Models
|
||||
Implements SQLModel definitions for agent reputation, trust scores, and economic metrics
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
@@ -66,9 +66,9 @@ class AgentReputation(SQLModel, table=True):
|
||||
specialization_tags: list[str] = Field(default=[], sa_column=Column(JSON))
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
last_activity: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
last_activity: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Additional metadata
|
||||
reputation_history: list[dict[str, Any]] = Field(default=[], sa_column=Column(JSON))
|
||||
@@ -103,7 +103,7 @@ class TrustScoreCalculation(SQLModel, table=True):
|
||||
confidence_level: float = Field(default=0.8, ge=0, le=1.0)
|
||||
|
||||
# Timestamps
|
||||
calculated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
calculated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
effective_period: int = Field(default=86400) # seconds
|
||||
|
||||
# Additional data
|
||||
@@ -140,7 +140,7 @@ class ReputationEvent(SQLModel, table=True):
|
||||
verification_status: str = Field(default="pending") # pending, verified, rejected
|
||||
|
||||
# Timestamps
|
||||
occurred_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
occurred_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
processed_at: datetime | None = None
|
||||
expires_at: datetime | None = None
|
||||
|
||||
@@ -176,8 +176,8 @@ class AgentEconomicProfile(SQLModel, table=True):
|
||||
liquidity_score: float = Field(default=0.0, ge=0, le=100.0)
|
||||
|
||||
# Timestamps
|
||||
profile_date: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
last_updated: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
profile_date: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
last_updated: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Historical data
|
||||
earnings_history: list[dict[str, Any]] = Field(default=[], sa_column=Column(JSON))
|
||||
@@ -217,8 +217,8 @@ class CommunityFeedback(SQLModel, table=True):
|
||||
moderator_notes: str = Field(default="", max_length=500)
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
helpful_votes: int = Field(default=0)
|
||||
|
||||
# Additional metadata
|
||||
@@ -247,8 +247,8 @@ class ReputationLevelThreshold(SQLModel, table=True):
|
||||
fee_discount: float = Field(default=0.0, ge=0, le=100.0)
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
is_active: bool = Field(default=True)
|
||||
|
||||
# Additional configuration
|
||||
|
||||
@@ -3,7 +3,7 @@ Agent Reward System Domain Models
|
||||
Implements SQLModel definitions for performance-based rewards, incentives, and distributions
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
@@ -71,8 +71,8 @@ class RewardTierConfig(SQLModel, table=True):
|
||||
support_level: str = Field(default="basic")
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
is_active: bool = Field(default=True)
|
||||
|
||||
# Additional configuration
|
||||
@@ -112,9 +112,9 @@ class AgentRewardProfile(SQLModel, table=True):
|
||||
longest_streak: int = Field(default=0)
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
last_activity: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
last_activity: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Additional metadata
|
||||
reward_preferences: dict[str, Any] = Field(default={}, sa_column=Column(JSON))
|
||||
@@ -148,12 +148,12 @@ class RewardCalculation(SQLModel, table=True):
|
||||
|
||||
# Calculation metadata
|
||||
calculation_period: str = Field(default="daily") # daily, weekly, monthly
|
||||
reference_date: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
reference_date: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
trust_score_at_calculation: float = Field(ge=0, le=1000)
|
||||
performance_metrics: dict[str, Any] = Field(default={}, sa_column=Column(JSON))
|
||||
|
||||
# Timestamps
|
||||
calculated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
calculated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
expires_at: datetime | None = None
|
||||
|
||||
# Additional data
|
||||
@@ -192,8 +192,8 @@ class RewardDistribution(SQLModel, table=True):
|
||||
error_message: str | None = None
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
scheduled_at: datetime | None = None
|
||||
|
||||
# Additional data
|
||||
@@ -228,7 +228,7 @@ class RewardEvent(SQLModel, table=True):
|
||||
verification_status: str = Field(default="pending") # pending, verified, rejected
|
||||
|
||||
# Timestamps
|
||||
occurred_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
occurred_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
processed_at: datetime | None = None
|
||||
expires_at: datetime | None = None
|
||||
|
||||
@@ -266,8 +266,8 @@ class RewardMilestone(SQLModel, table=True):
|
||||
claimed_at: datetime | None = None
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
expires_at: datetime | None = None
|
||||
|
||||
# Additional data
|
||||
@@ -314,8 +314,8 @@ class RewardAnalytics(SQLModel, table=True):
|
||||
average_processing_time: float = Field(default=0.0) # milliseconds
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Additional analytics data
|
||||
analytics_data: dict[str, Any] = Field(default={}, sa_column=Column(JSON))
|
||||
|
||||
@@ -3,7 +3,7 @@ Agent-to-Agent Trading Protocol Domain Models
|
||||
Implements SQLModel definitions for P2P trading, matching, negotiation, and settlement
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
@@ -101,10 +101,10 @@ class TradeRequest(SQLModel, table=True):
|
||||
best_match_score: float = Field(default=0.0)
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
expires_at: datetime | None = None
|
||||
last_activity: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
last_activity: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Additional metadata
|
||||
tags: list[str] = Field(default=[], sa_column=Column(JSON))
|
||||
@@ -151,8 +151,8 @@ class TradeMatch(SQLModel, table=True):
|
||||
initial_terms: dict[str, Any] = Field(default={}, sa_column=Column(JSON))
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
expires_at: datetime | None = None
|
||||
last_interaction: datetime | None = None
|
||||
|
||||
@@ -202,8 +202,8 @@ class TradeNegotiation(SQLModel, table=True):
|
||||
auto_accept_threshold: float = Field(default=85.0, ge=0, le=100)
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
started_at: datetime | None = None
|
||||
completed_at: datetime | None = None
|
||||
expires_at: datetime | None = None
|
||||
@@ -260,9 +260,9 @@ class TradeAgreement(SQLModel, table=True):
|
||||
completion_percentage: float = Field(default=0.0, ge=0, le=100)
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
signed_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
signed_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
starts_at: datetime | None = None
|
||||
ends_at: datetime | None = None
|
||||
completed_at: datetime | None = None
|
||||
@@ -314,7 +314,7 @@ class TradeSettlement(SQLModel, table=True):
|
||||
|
||||
# Status and timestamps
|
||||
status: TradeStatus = Field(default=TradeStatus.SETTLING)
|
||||
initiated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
initiated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
processed_at: datetime | None = None
|
||||
completed_at: datetime | None = None
|
||||
refunded_at: datetime | None = None
|
||||
@@ -365,8 +365,8 @@ class TradeFeedback(SQLModel, table=True):
|
||||
moderator_notes: str = Field(default="", max_length=500)
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
trade_completed_at: datetime
|
||||
|
||||
# Additional data
|
||||
@@ -421,8 +421,8 @@ class TradingAnalytics(SQLModel, table=True):
|
||||
repeat_trade_rate: float = Field(default=0.0, ge=0, le=100.0)
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Additional analytics data
|
||||
analytics_data: dict[str, Any] = Field(default={}, sa_column=Column(JSON))
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
User domain models for AITBC
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from sqlalchemy import JSON
|
||||
from sqlmodel import Column, Field, SQLModel
|
||||
@@ -18,8 +18,8 @@ class User(SQLModel, table=True):
|
||||
email: str = Field(unique=True, index=True)
|
||||
username: str = Field(unique=True, index=True)
|
||||
status: str = Field(default="active", max_length=20)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
last_login: datetime | None = None
|
||||
|
||||
# Relationships
|
||||
@@ -37,8 +37,8 @@ class Wallet(SQLModel, table=True):
|
||||
user_id: str = Field(foreign_key="users.id")
|
||||
address: str = Field(unique=True, index=True)
|
||||
balance: float = Field(default=0.0)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Relationships
|
||||
# DISABLED: user: User = Relationship(back_populates="wallets")
|
||||
@@ -60,7 +60,7 @@ class Transaction(SQLModel, table=True):
|
||||
fee: float = Field(default=0.0)
|
||||
description: str | None = None
|
||||
tx_metadata: str | None = Field(default=None, sa_column=Column(JSON))
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
confirmed_at: datetime | None = None
|
||||
|
||||
# Relationships
|
||||
@@ -78,5 +78,5 @@ class UserSession(SQLModel, table=True):
|
||||
user_id: str = Field(foreign_key="users.id")
|
||||
token: str = Field(unique=True, index=True)
|
||||
expires_at: datetime
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
last_used: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
last_used: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
@@ -6,7 +6,7 @@ Domain models for managing agent wallets across multiple blockchain networks.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from enum import StrEnum
|
||||
|
||||
from sqlalchemy import JSON, Column
|
||||
@@ -41,8 +41,8 @@ class AgentWallet(SQLModel, table=True):
|
||||
encrypted_private_key: str | None = Field(default=None) # Only if managed internally
|
||||
kms_key_id: str | None = Field(default=None) # Reference to external KMS
|
||||
meta_data: dict[str, str] = Field(default_factory=dict, sa_column=Column(JSON))
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Relationships
|
||||
# DISABLED: balances: List["TokenBalance"] = Relationship(back_populates="wallet")
|
||||
@@ -78,7 +78,7 @@ class TokenBalance(SQLModel, table=True):
|
||||
token_address: str = Field(index=True) # "native" for native currency
|
||||
token_symbol: str = Field()
|
||||
balance: float = Field(default=0.0)
|
||||
last_updated: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
last_updated: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Relationships
|
||||
# DISABLED: wallet: AgentWallet = Relationship(back_populates="balances")
|
||||
@@ -109,8 +109,8 @@ class WalletTransaction(SQLModel, table=True):
|
||||
nonce: int | None = Field(default=None)
|
||||
status: TransactionStatus = Field(default=TransactionStatus.PENDING, index=True)
|
||||
error_message: str | None = Field(default=None)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Relationships
|
||||
# DISABLED: wallet: AgentWallet = Relationship(back_populates="transactions")
|
||||
|
||||
@@ -11,7 +11,13 @@ from .agent_identity import router as agent_identity
|
||||
from .blockchain import router as blockchain
|
||||
from .cache_management import router as cache_management
|
||||
from .client import router as client
|
||||
from .edge_gpu import router as edge_gpu
|
||||
|
||||
try:
|
||||
from .edge_gpu import router as edge_gpu
|
||||
except ImportError:
|
||||
edge_gpu = None
|
||||
print("WARNING: Edge GPU router not available (missing module)")
|
||||
|
||||
from .exchange import router as exchange
|
||||
from .explorer import router as explorer
|
||||
from .marketplace import router as marketplace
|
||||
|
||||
@@ -6,7 +6,7 @@ Provides health monitoring for reinforcement learning frameworks
|
||||
"""
|
||||
|
||||
import sys
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
import psutil
|
||||
@@ -40,7 +40,7 @@ async def adaptive_learning_health(session: Annotated[Session, Depends(get_sessi
|
||||
"status": "healthy",
|
||||
"service": "adaptive-learning",
|
||||
"port": 8011,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"python_version": f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}",
|
||||
# System metrics
|
||||
"system": {
|
||||
@@ -97,7 +97,7 @@ async def adaptive_learning_health(session: Annotated[Session, Depends(get_sessi
|
||||
"status": "unhealthy",
|
||||
"service": "adaptive-learning",
|
||||
"port": 8011,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"error": "Health check failed",
|
||||
}
|
||||
|
||||
@@ -177,7 +177,7 @@ async def adaptive_learning_deep_health(session: Annotated[Session, Depends(get_
|
||||
"status": "healthy",
|
||||
"service": "adaptive-learning",
|
||||
"port": 8011,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"algorithm_tests": algorithm_tests,
|
||||
"safety_tests": safety_tests,
|
||||
"overall_health": (
|
||||
@@ -196,6 +196,6 @@ async def adaptive_learning_deep_health(session: Annotated[Session, Depends(get_
|
||||
"status": "unhealthy",
|
||||
"service": "adaptive-learning",
|
||||
"port": 8011,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"error": "Deep health check failed",
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, Depends, Header, HTTPException, Request
|
||||
@@ -55,7 +55,7 @@ async def create_test_miner(
|
||||
if existing_miner:
|
||||
# Update existing miner to ONLINE
|
||||
existing_miner.status = "ONLINE"
|
||||
existing_miner.last_heartbeat = datetime.now(datetime.UTC)
|
||||
existing_miner.last_heartbeat = datetime.now(timezone.utc)
|
||||
existing_miner.session_token = session_token
|
||||
session.add(existing_miner)
|
||||
session.commit()
|
||||
@@ -79,7 +79,7 @@ async def create_test_miner(
|
||||
session_token=session_token,
|
||||
status="ONLINE",
|
||||
inflight=0,
|
||||
last_heartbeat=datetime.now(datetime.UTC),
|
||||
last_heartbeat=datetime.now(timezone.utc),
|
||||
)
|
||||
|
||||
session.add(miner)
|
||||
@@ -223,7 +223,7 @@ async def get_system_status(
|
||||
|
||||
# Get system info
|
||||
import sys
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import psutil
|
||||
|
||||
@@ -232,7 +232,7 @@ async def get_system_status(
|
||||
"memory_percent": psutil.virtual_memory().percent,
|
||||
"disk_percent": psutil.disk_usage("/").percent,
|
||||
"python_version": f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}",
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -275,7 +275,7 @@ async def create_agent_network(network_data: dict) -> dict:
|
||||
raise HTTPException(status_code=400, detail="Agent list is required")
|
||||
|
||||
# Create network record (simplified for now)
|
||||
network_id = f"network_{datetime.now(datetime.UTC).strftime('%Y%m%d_%H%M%S')}"
|
||||
network_id = f"network_{datetime.now(timezone.utc).strftime('%Y%m%d_%H%M%S')}"
|
||||
|
||||
network_response = {
|
||||
"id": network_id,
|
||||
@@ -284,7 +284,7 @@ async def create_agent_network(network_data: dict) -> dict:
|
||||
"agents": network_data["agents"],
|
||||
"coordination_strategy": network_data.get("coordination", "centralized"),
|
||||
"status": "active",
|
||||
"created_at": datetime.now(datetime.UTC).isoformat(),
|
||||
"created_at": datetime.now(timezone.utc).isoformat(),
|
||||
"owner_id": "temp_user",
|
||||
}
|
||||
|
||||
@@ -315,11 +315,11 @@ async def get_execution_receipt(execution_id: str) -> dict:
|
||||
{
|
||||
"coordinator_id": "coordinator_1",
|
||||
"signature": "0xmock_attestation_1",
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
],
|
||||
"minted_amount": 1000,
|
||||
"recorded_at": datetime.now(datetime.UTC).isoformat(),
|
||||
"recorded_at": datetime.now(timezone.utc).isoformat(),
|
||||
"verified": True,
|
||||
"block_hash": "0xmock_block_hash",
|
||||
"transaction_hash": "0xmock_tx_hash",
|
||||
|
||||
@@ -3,11 +3,12 @@ Agent Identity API Router
|
||||
REST API endpoints for agent identity management and cross-chain operations
|
||||
"""
|
||||
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from fastapi.responses import JSONResponse
|
||||
from sqlmodel import Session
|
||||
|
||||
from ..agent_identity.manager import AgentIdentityManager
|
||||
from ..domain.agent_identity import (
|
||||
@@ -85,7 +86,7 @@ async def deactivate_agent_identity(
|
||||
success = await manager.deactivate_agent_identity(agent_id, reason)
|
||||
if not success:
|
||||
raise HTTPException(status_code=400, detail="Deactivation failed")
|
||||
return {"agent_id": agent_id, "deactivated": True, "reason": reason, "timestamp": datetime.now(datetime.UTC).isoformat()}
|
||||
return {"agent_id": agent_id, "deactivated": True, "reason": reason, "timestamp": datetime.now(timezone.utc).isoformat()}
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
@@ -164,7 +165,7 @@ async def update_cross_chain_mapping(
|
||||
"chain_id": chain_id,
|
||||
"new_address": new_address,
|
||||
"updated": True,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
except HTTPException:
|
||||
raise
|
||||
@@ -255,7 +256,7 @@ async def get_wallet_balance(agent_id: str, chain_id: int, manager: AgentIdentit
|
||||
"agent_id": agent_id,
|
||||
"chain_id": chain_id,
|
||||
"balance": str(balance),
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=400, detail="Failed to create agent identity")
|
||||
@@ -427,7 +428,7 @@ async def cleanup_expired_verifications(manager: AgentIdentityManager = Depends(
|
||||
"""Clean up expired verification records"""
|
||||
try:
|
||||
cleaned_count = await manager.registry.cleanup_expired_verifications()
|
||||
return {"cleaned_verifications": cleaned_count, "timestamp": datetime.now(datetime.UTC).isoformat()}
|
||||
return {"cleaned_verifications": cleaned_count, "timestamp": datetime.now(timezone.utc).isoformat()}
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail="Operation failed")
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ Advanced Agent Performance API Endpoints
|
||||
REST API for meta-learning, resource optimization, and performance enhancement
|
||||
"""
|
||||
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
@@ -319,7 +319,7 @@ async def adapt_model_to_task(
|
||||
"success": True,
|
||||
"model_id": model_id,
|
||||
"adaptation_results": results,
|
||||
"adapted_at": datetime.now(datetime.UTC).isoformat(),
|
||||
"adapted_at": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
except ValueError as e:
|
||||
@@ -554,7 +554,7 @@ async def create_capability(
|
||||
skill_level=capability_request.skill_level,
|
||||
specialization_areas=capability_request.specialization_areas,
|
||||
proficiency_score=min(1.0, capability_request.skill_level / 10.0),
|
||||
created_at=datetime.now(datetime.UTC),
|
||||
created_at=datetime.now(timezone.utc),
|
||||
)
|
||||
|
||||
session.add(capability)
|
||||
@@ -718,7 +718,7 @@ async def health_check() -> Dict[str, Any]:
|
||||
|
||||
return {
|
||||
"status": "healthy",
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"version": "1.0.0",
|
||||
"services": {
|
||||
"meta_learning_engine": "operational",
|
||||
|
||||
@@ -7,7 +7,7 @@ AI Agent API Router for Verifiable AI Agent Orchestration
|
||||
Provides REST API endpoints for agent workflow management and execution
|
||||
"""
|
||||
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException
|
||||
@@ -142,7 +142,7 @@ async def update_workflow(
|
||||
for field, value in update_data.items():
|
||||
setattr(workflow, field, value)
|
||||
|
||||
workflow.updated_at = datetime.now(datetime.UTC)
|
||||
workflow.updated_at = datetime.now(timezone.utc)
|
||||
session.commit()
|
||||
session.refresh(workflow)
|
||||
|
||||
@@ -352,7 +352,7 @@ async def cancel_execution(
|
||||
|
||||
# Cancel execution
|
||||
state_manager = AgentStateManager(session)
|
||||
await state_manager.update_execution_status(execution_id, status=AgentStatus.CANCELLED, completed_at=datetime.now(datetime.UTC))
|
||||
await state_manager.update_execution_status(execution_id, status=AgentStatus.CANCELLED, completed_at=datetime.now(timezone.utc))
|
||||
|
||||
logger.info(f"Cancelled agent execution: {execution_id}")
|
||||
return {"message": "Execution cancelled successfully"}
|
||||
@@ -425,7 +425,7 @@ async def get_execution_logs(
|
||||
@router.get("/test")
|
||||
async def test_endpoint() -> dict[str, str]:
|
||||
"""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(timezone.utc).isoformat()}
|
||||
|
||||
|
||||
@router.post("/networks", response_model=dict, status_code=201)
|
||||
@@ -445,7 +445,7 @@ async def create_agent_network(
|
||||
raise HTTPException(status_code=400, detail="Agent list is required")
|
||||
|
||||
# Create network record (simplified for now)
|
||||
network_id = f"network_{datetime.now(datetime.UTC).strftime('%Y%m%d_%H%M%S')}"
|
||||
network_id = f"network_{datetime.now(timezone.utc).strftime('%Y%m%d_%H%M%S')}"
|
||||
|
||||
network_response = {
|
||||
"id": network_id,
|
||||
@@ -454,7 +454,7 @@ async def create_agent_network(
|
||||
"agents": network_data["agents"],
|
||||
"coordination_strategy": network_data.get("coordination", "centralized"),
|
||||
"status": "active",
|
||||
"created_at": datetime.now(datetime.UTC).isoformat(),
|
||||
"created_at": datetime.now(timezone.utc).isoformat(),
|
||||
"owner_id": current_user,
|
||||
}
|
||||
|
||||
@@ -488,11 +488,11 @@ async def get_execution_receipt(
|
||||
{
|
||||
"coordinator_id": "coordinator_1",
|
||||
"signature": "0xmock_attestation_1",
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
],
|
||||
"minted_amount": 1000,
|
||||
"recorded_at": datetime.now(datetime.UTC).isoformat(),
|
||||
"recorded_at": datetime.now(timezone.utc).isoformat(),
|
||||
"verified": True,
|
||||
"block_hash": "0xmock_block_hash",
|
||||
"transaction_hash": "0xmock_tx_hash",
|
||||
|
||||
@@ -125,7 +125,7 @@ async def update_security_policy(
|
||||
if hasattr(policy, field):
|
||||
setattr(policy, field, value)
|
||||
|
||||
policy.updated_at = datetime.now(datetime.UTC)
|
||||
policy.updated_at = datetime.now(timezone.utc)
|
||||
session.commit()
|
||||
session.refresh(policy)
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ Marketplace Analytics API Endpoints
|
||||
REST API for analytics, insights, reporting, and dashboards
|
||||
"""
|
||||
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
@@ -552,7 +552,7 @@ async def get_key_performance_indicators(
|
||||
|
||||
try:
|
||||
# Get latest metrics for KPIs
|
||||
end_time = datetime.now(datetime.UTC)
|
||||
end_time = datetime.now(timezone.utc)
|
||||
|
||||
if period_type == AnalyticsPeriod.DAILY:
|
||||
start_time = end_time - timedelta(days=1)
|
||||
|
||||
@@ -5,14 +5,14 @@ Bounty Management API
|
||||
REST API for AI agent bounty system with ZK-proof verification
|
||||
"""
|
||||
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException
|
||||
from pydantic import BaseModel, Field, validator
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..app_logging import get_logger
|
||||
from aitbc import get_logger
|
||||
from ..auth import get_current_user
|
||||
from ..domain.bounty import (
|
||||
Bounty,
|
||||
@@ -38,7 +38,7 @@ class BountyCreateRequest(BaseModel):
|
||||
performance_criteria: Dict[str, Any] = Field(default_factory=dict)
|
||||
min_accuracy: float = Field(default=90.0, ge=0, le=100)
|
||||
max_response_time: Optional[int] = Field(default=None, gt=0)
|
||||
deadline: datetime = Field(..., gt=datetime.now(datetime.UTC))
|
||||
deadline: datetime = Field(..., gt=datetime.now(timezone.utc))
|
||||
max_submissions: int = Field(default=100, gt=0, le=1000)
|
||||
requires_zk_proof: bool = Field(default=True)
|
||||
auto_verify_threshold: float = Field(default=95.0, ge=0, le=100)
|
||||
@@ -48,9 +48,9 @@ class BountyCreateRequest(BaseModel):
|
||||
|
||||
@validator('deadline')
|
||||
def validate_deadline(cls, v: datetime) -> datetime:
|
||||
if v <= datetime.now(datetime.UTC):
|
||||
if v <= datetime.now(timezone.utc):
|
||||
raise ValueError('Deadline must be in the future')
|
||||
if v > datetime.now(datetime.UTC) + timedelta(days=365):
|
||||
if v > datetime.now(timezone.utc) + timedelta(days=365):
|
||||
raise ValueError('Deadline cannot be more than 1 year in the future')
|
||||
return v
|
||||
|
||||
@@ -281,7 +281,7 @@ async def submit_bounty_solution(
|
||||
if bounty.status != BountyStatus.ACTIVE:
|
||||
raise HTTPException(status_code=400, detail="Bounty is not active")
|
||||
|
||||
if datetime.now(datetime.UTC) > bounty.deadline:
|
||||
if datetime.now(timezone.utc) > bounty.deadline:
|
||||
raise HTTPException(status_code=400, detail="Bounty deadline has passed")
|
||||
|
||||
# Create submission
|
||||
@@ -519,7 +519,7 @@ async def expire_bounty(
|
||||
if bounty.status != BountyStatus.ACTIVE:
|
||||
raise HTTPException(status_code=400, detail="Bounty is not active")
|
||||
|
||||
if datetime.now(datetime.UTC) <= bounty.deadline:
|
||||
if datetime.now(timezone.utc) <= bounty.deadline:
|
||||
raise HTTPException(status_code=400, detail="Bounty deadline has not passed")
|
||||
|
||||
# Expire bounty
|
||||
|
||||
@@ -7,7 +7,7 @@ Certification and Partnership API Endpoints
|
||||
REST API for agent certification, partnership programs, and badge system
|
||||
"""
|
||||
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
@@ -626,7 +626,7 @@ async def check_automatic_badges(
|
||||
"agent_id": agent_id,
|
||||
"badges_awarded": awarded_badges,
|
||||
"total_awarded": len(awarded_badges),
|
||||
"checked_at": datetime.now(datetime.UTC).isoformat()
|
||||
"checked_at": datetime.now(timezone.utc).isoformat()
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request, status
|
||||
@@ -265,7 +265,7 @@ async def create_agent_network(network_data: dict) -> dict:
|
||||
raise HTTPException(status_code=400, detail="Agent list is required")
|
||||
|
||||
# Create network record (simplified for now)
|
||||
network_id = f"network_{datetime.now(datetime.UTC).strftime('%Y%m%d_%H%M%S')}"
|
||||
network_id = f"network_{datetime.now(timezone.utc).strftime('%Y%m%d_%H%M%S')}"
|
||||
|
||||
network_response = {
|
||||
"id": network_id,
|
||||
@@ -274,7 +274,7 @@ async def create_agent_network(network_data: dict) -> dict:
|
||||
"agents": network_data["agents"],
|
||||
"coordination_strategy": network_data.get("coordination", "centralized"),
|
||||
"status": "active",
|
||||
"created_at": datetime.now(datetime.UTC).isoformat(),
|
||||
"created_at": datetime.now(timezone.utc).isoformat(),
|
||||
"owner_id": "temp_user",
|
||||
}
|
||||
|
||||
@@ -302,11 +302,11 @@ async def get_execution_receipt(execution_id: str) -> dict:
|
||||
{
|
||||
"coordinator_id": "coordinator_1",
|
||||
"signature": "0xmock_attestation_1",
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
],
|
||||
"minted_amount": 1000,
|
||||
"recorded_at": datetime.now(datetime.UTC).isoformat(),
|
||||
"recorded_at": datetime.now(timezone.utc).isoformat(),
|
||||
"verified": True,
|
||||
"block_hash": "0xmock_block_hash",
|
||||
"transaction_hash": "0xmock_tx_hash",
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
API endpoints for confidential transactions
|
||||
"""
|
||||
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
from aitbc import get_logger
|
||||
@@ -83,13 +83,13 @@ async def create_confidential_transaction(request: ConfidentialTransactionCreate
|
||||
"""Create a new confidential transaction with optional encryption"""
|
||||
try:
|
||||
# Generate transaction ID
|
||||
transaction_id = f"ctx-{datetime.now(datetime.UTC).timestamp()}"
|
||||
transaction_id = f"ctx-{datetime.now(timezone.utc).timestamp()}"
|
||||
|
||||
# Create base transaction
|
||||
transaction = ConfidentialTransaction(
|
||||
transaction_id=transaction_id,
|
||||
job_id=request.job_id,
|
||||
timestamp=datetime.now(datetime.UTC),
|
||||
timestamp=datetime.now(timezone.utc),
|
||||
status="created",
|
||||
amount=request.amount,
|
||||
pricing=request.pricing,
|
||||
@@ -178,7 +178,7 @@ async def access_confidential_data(
|
||||
transaction = ConfidentialTransaction(
|
||||
transaction_id=transaction_id,
|
||||
job_id="test-job",
|
||||
timestamp=datetime.now(datetime.UTC),
|
||||
timestamp=datetime.now(timezone.utc),
|
||||
status="completed",
|
||||
confidential=True,
|
||||
participants=["client-456", "miner-789"],
|
||||
@@ -205,7 +205,7 @@ async def access_confidential_data(
|
||||
return ConfidentialAccessResponse(
|
||||
success=True,
|
||||
data={"amount": "1000", "pricing": {"rate": "0.1"}},
|
||||
access_id=f"access-{datetime.now(datetime.UTC).timestamp()}",
|
||||
access_id=f"access-{datetime.now(timezone.utc).timestamp()}",
|
||||
)
|
||||
|
||||
# Decrypt data
|
||||
@@ -230,7 +230,7 @@ async def access_confidential_data(
|
||||
)
|
||||
|
||||
return ConfidentialAccessResponse(
|
||||
success=True, data=decrypted_data, access_id=f"access-{datetime.now(datetime.UTC).timestamp()}"
|
||||
success=True, data=decrypted_data, access_id=f"access-{datetime.now(timezone.utc).timestamp()}"
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
@@ -254,7 +254,7 @@ async def audit_access_confidential_data(
|
||||
transaction = ConfidentialTransaction(
|
||||
transaction_id=transaction_id,
|
||||
job_id="test-job",
|
||||
timestamp=datetime.now(datetime.UTC),
|
||||
timestamp=datetime.now(timezone.utc),
|
||||
status="completed",
|
||||
confidential=True,
|
||||
)
|
||||
@@ -283,7 +283,7 @@ async def audit_access_confidential_data(
|
||||
)
|
||||
|
||||
return ConfidentialAccessResponse(
|
||||
success=True, data=decrypted_data, access_id=f"audit-{datetime.now(datetime.UTC).timestamp()}"
|
||||
success=True, data=decrypted_data, access_id=f"audit-{datetime.now(timezone.utc).timestamp()}"
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
@@ -313,7 +313,7 @@ async def register_encryption_key(request: KeyRegistrationRequest, api_key: str
|
||||
success=True,
|
||||
participant_id=request.participant_id,
|
||||
key_version=1, # Would get from storage
|
||||
registered_at=datetime.now(datetime.UTC),
|
||||
registered_at=datetime.now(timezone.utc),
|
||||
error=None,
|
||||
)
|
||||
except:
|
||||
@@ -333,7 +333,7 @@ async def register_encryption_key(request: KeyRegistrationRequest, api_key: str
|
||||
except KeyManagementError as e:
|
||||
logger.error(f"Key registration failed: {e}")
|
||||
return KeyRegistrationResponse(
|
||||
success=False, participant_id=request.participant_id, key_version=0, registered_at=datetime.now(datetime.UTC), error=str(e)
|
||||
success=False, participant_id=request.participant_id, key_version=0, registered_at=datetime.now(timezone.utc), error=str(e)
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to register key: {e}")
|
||||
|
||||
@@ -3,7 +3,7 @@ Cross-Chain Integration API Router
|
||||
REST API endpoints for enhanced multi-chain wallet adapter, cross-chain bridge service, and transaction manager
|
||||
"""
|
||||
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
@@ -217,7 +217,7 @@ async def verify_signature(
|
||||
"message": message,
|
||||
"address": address,
|
||||
"chain_id": chain_id,
|
||||
"verified_at": datetime.now(datetime.UTC).isoformat(),
|
||||
"verified_at": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
@@ -606,7 +606,7 @@ async def get_cross_chain_health(session: Session = Depends(get_session)) -> dic
|
||||
"transaction_success_rate": tx_stats["success_rate"],
|
||||
"average_processing_time": tx_stats["average_processing_time_minutes"],
|
||||
"active_liquidity_pools": len(await bridge_service.get_liquidity_pools()),
|
||||
"last_updated": datetime.now(datetime.UTC).isoformat(),
|
||||
"last_updated": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
@@ -675,7 +675,7 @@ async def get_cross_chain_config(session: Session = Depends(get_session)) -> dic
|
||||
"transaction_priorities": transaction_priorities,
|
||||
"routing_strategies": routing_strategies,
|
||||
"security_levels": [level.value for level in SecurityLevel],
|
||||
"last_updated": datetime.now(datetime.UTC).isoformat(),
|
||||
"last_updated": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
|
||||
@@ -3,7 +3,7 @@ Developer Platform API Router
|
||||
REST API endpoints for the developer ecosystem including bounties, certifications, and regional hubs
|
||||
"""
|
||||
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
@@ -440,7 +440,7 @@ async def verify_certification(certification_id: str, session: Session = Depends
|
||||
"issued_by": certification.issued_by,
|
||||
"granted_at": certification.granted_at.isoformat(),
|
||||
"is_valid": True,
|
||||
"verification_timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"verification_timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
except HTTPException:
|
||||
@@ -746,7 +746,7 @@ async def get_platform_overview(
|
||||
"regions_covered": 12, # Mock data
|
||||
},
|
||||
"staking": {"total_staked": 1000000.0, "active_stakers": 500, "average_apy": 7.5}, # Mock data
|
||||
"generated_at": datetime.now(datetime.UTC).isoformat(),
|
||||
"generated_at": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
@@ -785,7 +785,7 @@ async def get_platform_health(session: Session = Depends(get_session)) -> dict[s
|
||||
"pending_submissions": 8, # Mock data
|
||||
"system_uptime": "99.9%",
|
||||
},
|
||||
"last_updated": datetime.now(datetime.UTC).isoformat(),
|
||||
"last_updated": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
|
||||
@@ -5,7 +5,7 @@ Dynamic Pricing API Router
|
||||
Provides RESTful endpoints for dynamic pricing management
|
||||
"""
|
||||
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
@@ -147,7 +147,7 @@ async def get_price_forecast(
|
||||
accuracy_score=(
|
||||
sum(point.confidence for point in forecast_points) / len(forecast_points) if forecast_points else 0.0
|
||||
),
|
||||
generated_at=datetime.now(datetime.UTC).isoformat(),
|
||||
generated_at=datetime.now(timezone.utc).isoformat(),
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
@@ -197,7 +197,7 @@ async def set_pricing_strategy(
|
||||
provider_id=provider_id,
|
||||
strategy=request.strategy,
|
||||
constraints=request.constraints,
|
||||
set_at=datetime.now(datetime.UTC).isoformat(),
|
||||
set_at=datetime.now(timezone.utc).isoformat(),
|
||||
status="active",
|
||||
)
|
||||
|
||||
@@ -239,7 +239,7 @@ async def get_pricing_strategy(
|
||||
provider_id=provider_id,
|
||||
strategy=strategy.value,
|
||||
constraints=constraints_dict,
|
||||
set_at=datetime.now(datetime.UTC).isoformat(),
|
||||
set_at=datetime.now(timezone.utc).isoformat(),
|
||||
status="active",
|
||||
)
|
||||
|
||||
@@ -531,7 +531,7 @@ async def get_price_history(
|
||||
)
|
||||
|
||||
# Filter history by period
|
||||
cutoff_time = datetime.now(datetime.UTC) - timedelta(days=days)
|
||||
cutoff_time = datetime.now(timezone.utc) - timedelta(days=days)
|
||||
filtered_history = [point for point in engine.pricing_history[resource_id] if point.timestamp >= cutoff_time]
|
||||
|
||||
# Calculate statistics
|
||||
@@ -637,7 +637,7 @@ async def bulk_pricing_update(
|
||||
success_count=success_count,
|
||||
error_count=error_count,
|
||||
results=results,
|
||||
processed_at=datetime.now(datetime.UTC).isoformat(),
|
||||
processed_at=datetime.now(timezone.utc).isoformat(),
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
@@ -691,7 +691,7 @@ async def pricing_health_check(
|
||||
|
||||
return {
|
||||
"status": overall_status,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"services": {
|
||||
"pricing_engine": {
|
||||
"status": engine_status,
|
||||
@@ -710,4 +710,4 @@ async def pricing_health_check(
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Dynamic pricing health check failed: {e}")
|
||||
return {"status": "unhealthy", "timestamp": datetime.now(datetime.UTC).isoformat(), "error": "Health check failed"}
|
||||
return {"status": "unhealthy", "timestamp": datetime.now(timezone.utc).isoformat(), "error": "Health check failed"}
|
||||
|
||||
@@ -5,14 +5,14 @@ Ecosystem Metrics Dashboard API
|
||||
REST API for developer ecosystem metrics and analytics
|
||||
"""
|
||||
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..app_logging import get_logger
|
||||
from aitbc import get_logger
|
||||
from ..auth import get_current_user
|
||||
from ..domain.bounty import AgentMetrics, BountyStats, EcosystemMetrics
|
||||
from ..services.ecosystem_service import EcosystemService
|
||||
@@ -345,7 +345,7 @@ async def get_ecosystem_alerts(
|
||||
"alerts": alerts,
|
||||
"severity": severity,
|
||||
"count": len(alerts),
|
||||
"last_updated": datetime.now(datetime.UTC)
|
||||
"last_updated": datetime.now(timezone.utc)
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
@@ -422,7 +422,7 @@ async def get_real_time_metrics(
|
||||
real_time_data = await ecosystem_service.get_real_time_metrics()
|
||||
|
||||
return {
|
||||
"timestamp": datetime.now(datetime.UTC),
|
||||
"timestamp": datetime.now(timezone.utc),
|
||||
"metrics": real_time_data,
|
||||
"update_frequency": "60s" # Update frequency in seconds
|
||||
}
|
||||
@@ -442,7 +442,7 @@ async def get_kpi_dashboard(
|
||||
|
||||
return {
|
||||
"kpis": kpi_data,
|
||||
"last_updated": datetime.now(datetime.UTC),
|
||||
"last_updated": datetime.now(timezone.utc),
|
||||
"refresh_interval": 300 # 5 minutes
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ Bitcoin Exchange Router for AITBC
|
||||
|
||||
import time
|
||||
import uuid
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, BackgroundTasks, HTTPException, Request
|
||||
@@ -214,7 +214,7 @@ async def monitor_payment(payment_id: str) -> None:
|
||||
@router.get("/agents/test")
|
||||
async def test_agent_endpoint() -> dict[str, str]:
|
||||
"""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(timezone.utc).isoformat()}
|
||||
|
||||
|
||||
@router.post("/agents/networks", response_model=dict, status_code=201)
|
||||
@@ -230,7 +230,7 @@ async def create_agent_network(network_data: dict) -> dict[str, Any]:
|
||||
raise HTTPException(status_code=400, detail="Agent list is required")
|
||||
|
||||
# Create network record (simplified for now)
|
||||
network_id = f"network_{datetime.now(datetime.UTC).strftime('%Y%m%d_%H%M%S')}"
|
||||
network_id = f"network_{datetime.now(timezone.utc).strftime('%Y%m%d_%H%M%S')}"
|
||||
|
||||
network_response = {
|
||||
"id": network_id,
|
||||
@@ -239,7 +239,7 @@ async def create_agent_network(network_data: dict) -> dict[str, Any]:
|
||||
"agents": network_data["agents"],
|
||||
"coordination_strategy": network_data.get("coordination", "centralized"),
|
||||
"status": "active",
|
||||
"created_at": datetime.now(datetime.UTC).isoformat(),
|
||||
"created_at": datetime.now(timezone.utc).isoformat(),
|
||||
"owner_id": "temp_user",
|
||||
}
|
||||
|
||||
@@ -269,11 +269,11 @@ async def get_execution_receipt(execution_id: str) -> dict[str, Any]:
|
||||
{
|
||||
"coordinator_id": "coordinator_1",
|
||||
"signature": "0xmock_attestation_1",
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
],
|
||||
"minted_amount": 1000,
|
||||
"recorded_at": datetime.now(datetime.UTC).isoformat(),
|
||||
"recorded_at": datetime.now(timezone.utc).isoformat(),
|
||||
"verified": True,
|
||||
"block_hash": "0xmock_block_hash",
|
||||
"transaction_hash": "0xmock_tx_hash",
|
||||
|
||||
@@ -3,7 +3,7 @@ Global Marketplace API Router
|
||||
REST API endpoints for global marketplace operations, multi-region support, and cross-chain integration
|
||||
"""
|
||||
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Query
|
||||
@@ -585,7 +585,7 @@ async def get_global_marketplace_health(
|
||||
recent_transactions = (
|
||||
session.execute(
|
||||
select(func.count(GlobalMarketplaceTransaction.id)).where(
|
||||
GlobalMarketplaceTransaction.created_at >= datetime.now(datetime.UTC) - timedelta(hours=24)
|
||||
GlobalMarketplaceTransaction.created_at >= datetime.now(timezone.utc) - timedelta(hours=24)
|
||||
)
|
||||
).scalar()
|
||||
or 0
|
||||
@@ -608,7 +608,7 @@ async def get_global_marketplace_health(
|
||||
"recent_24h": recent_transactions,
|
||||
"activity_rate": transaction_activity,
|
||||
},
|
||||
"last_updated": datetime.now(datetime.UTC).isoformat(),
|
||||
"last_updated": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
|
||||
@@ -3,7 +3,7 @@ Global Marketplace Integration API Router
|
||||
REST API endpoints for integrated global marketplace with cross-chain capabilities
|
||||
"""
|
||||
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
@@ -350,7 +350,7 @@ async def get_marketplace_integration_analytics(
|
||||
"active_regions": len(active_regions),
|
||||
"supported_chains": len(supported_chains),
|
||||
"integration_config": integration_service.integration_config,
|
||||
"last_updated": datetime.now(datetime.UTC).isoformat(),
|
||||
"last_updated": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
@@ -394,7 +394,7 @@ async def get_integration_status(
|
||||
"auto_bridge_execution": config["auto_bridge_execution"],
|
||||
"multi_chain_wallet_support": config["multi_chain_wallet_support"],
|
||||
},
|
||||
"last_updated": datetime.now(datetime.UTC).isoformat(),
|
||||
"last_updated": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
@@ -463,7 +463,7 @@ async def get_integration_config(
|
||||
}
|
||||
for priority in TransactionPriority
|
||||
},
|
||||
"last_updated": datetime.now(datetime.UTC).isoformat(),
|
||||
"last_updated": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
@@ -492,7 +492,7 @@ async def update_integration_config(
|
||||
return {
|
||||
"updated_config": integration_service.integration_config,
|
||||
"updated_keys": list(config_updates.keys()),
|
||||
"updated_at": datetime.now(datetime.UTC).isoformat(),
|
||||
"updated_at": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
except ValueError as e:
|
||||
@@ -554,7 +554,7 @@ async def get_integration_health(
|
||||
if health_status["issues"]:
|
||||
health_status["overall_status"] = "degraded"
|
||||
|
||||
health_status["last_updated"] = datetime.now(datetime.UTC).isoformat()
|
||||
health_status["last_updated"] = datetime.now(timezone.utc).isoformat()
|
||||
|
||||
return health_status
|
||||
|
||||
@@ -571,7 +571,7 @@ async def run_integration_diagnostics(
|
||||
"""Run integration diagnostics"""
|
||||
|
||||
try:
|
||||
diagnostics = {"diagnostic_type": diagnostic_type, "started_at": datetime.now(datetime.UTC).isoformat(), "results": {}}
|
||||
diagnostics = {"diagnostic_type": diagnostic_type, "started_at": datetime.now(timezone.utc).isoformat(), "results": {}}
|
||||
|
||||
if diagnostic_type == "full" or diagnostic_type == "services":
|
||||
# Test services
|
||||
@@ -617,9 +617,9 @@ async def run_integration_diagnostics(
|
||||
"configuration": integration_service.integration_config,
|
||||
}
|
||||
|
||||
diagnostics["completed_at"] = datetime.now(datetime.UTC).isoformat()
|
||||
diagnostics["completed_at"] = datetime.now(timezone.utc).isoformat()
|
||||
diagnostics["duration_seconds"] = (
|
||||
datetime.now(datetime.UTC) - datetime.fromisoformat(diagnostics["started_at"])
|
||||
datetime.now(timezone.utc) - datetime.fromisoformat(diagnostics["started_at"])
|
||||
).total_seconds()
|
||||
|
||||
return diagnostics
|
||||
|
||||
@@ -3,7 +3,7 @@ Enhanced Governance API Router
|
||||
REST API endpoints for multi-jurisdictional DAO governance, regional councils, treasury management, and staking
|
||||
"""
|
||||
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
@@ -433,7 +433,7 @@ async def check_compliance_status(
|
||||
"jurisdiction": jurisdiction,
|
||||
"is_compliant": True,
|
||||
"compliance_level": "full",
|
||||
"last_check": datetime.now(datetime.UTC).isoformat(),
|
||||
"last_check": datetime.now(timezone.utc).isoformat(),
|
||||
"requirements_met": {
|
||||
"kyc_verified": True,
|
||||
"aml_screened": True,
|
||||
@@ -441,7 +441,7 @@ async def check_compliance_status(
|
||||
"minimum_stake_met": True,
|
||||
},
|
||||
"restrictions": [],
|
||||
"next_review_date": (datetime.now(datetime.UTC) + timedelta(days=365)).isoformat(),
|
||||
"next_review_date": (datetime.now(timezone.utc) + timedelta(days=365)).isoformat(),
|
||||
}
|
||||
|
||||
return compliance_status
|
||||
@@ -490,7 +490,7 @@ async def get_governance_system_health(
|
||||
"treasury_balance": analytics["treasury"]["total_allocations"],
|
||||
"staking_pools": analytics["staking"]["active_pools"],
|
||||
},
|
||||
"last_updated": datetime.now(datetime.UTC).isoformat(),
|
||||
"last_updated": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
return health_data
|
||||
@@ -539,7 +539,7 @@ async def get_governance_platform_status(
|
||||
"treasury_utilization": f"{analytics['treasury']['utilization_rate']}%",
|
||||
"staking_apy": f"{analytics['staking']['average_apy']}%",
|
||||
},
|
||||
"last_updated": datetime.now(datetime.UTC).isoformat(),
|
||||
"last_updated": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
return status_data
|
||||
|
||||
@@ -7,7 +7,7 @@ Provides health monitoring for CUDA-optimized multi-modal processing
|
||||
|
||||
import subprocess
|
||||
import sys
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
import psutil
|
||||
@@ -37,7 +37,7 @@ async def gpu_multimodal_health(session: Annotated[Session, Depends(get_session)
|
||||
"status": "healthy" if gpu_info["available"] else "degraded",
|
||||
"service": "gpu-multimodal",
|
||||
"port": 8010,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"python_version": f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}",
|
||||
# System metrics
|
||||
"system": {
|
||||
@@ -86,7 +86,7 @@ async def gpu_multimodal_health(session: Annotated[Session, Depends(get_session)
|
||||
"status": "unhealthy",
|
||||
"service": "gpu-multimodal",
|
||||
"port": 8010,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"error": "Health check failed",
|
||||
}
|
||||
|
||||
@@ -145,7 +145,7 @@ async def gpu_multimodal_deep_health(session: Annotated[Session, Depends(get_ses
|
||||
"status": "healthy" if gpu_info["available"] else "degraded",
|
||||
"service": "gpu-multimodal",
|
||||
"port": 8010,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"gpu_info": gpu_info,
|
||||
"cuda_tests": cuda_tests,
|
||||
"overall_health": (
|
||||
@@ -161,7 +161,7 @@ async def gpu_multimodal_deep_health(session: Annotated[Session, Depends(get_ses
|
||||
"status": "unhealthy",
|
||||
"service": "gpu-multimodal",
|
||||
"port": 8010,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"error": "Deep health check failed",
|
||||
}
|
||||
|
||||
|
||||
@@ -6,14 +6,14 @@ Provides health monitoring for royalties, licensing, verification, and analytics
|
||||
"""
|
||||
|
||||
import sys
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
import psutil
|
||||
from fastapi import APIRouter, Depends
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..app_logging import get_logger
|
||||
from aitbc import get_logger
|
||||
from ..services.marketplace_enhanced import EnhancedMarketplaceService
|
||||
from ..storage import get_session
|
||||
|
||||
@@ -41,7 +41,7 @@ async def marketplace_enhanced_health(session: Annotated[Session, Depends(get_se
|
||||
"status": "healthy",
|
||||
"service": "marketplace-enhanced",
|
||||
"port": 8002,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"python_version": f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}",
|
||||
# System metrics
|
||||
"system": {
|
||||
@@ -98,7 +98,7 @@ async def marketplace_enhanced_health(session: Annotated[Session, Depends(get_se
|
||||
"status": "unhealthy",
|
||||
"service": "marketplace-enhanced",
|
||||
"port": 8002,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"error": "Health check failed",
|
||||
}
|
||||
|
||||
@@ -173,7 +173,7 @@ async def marketplace_enhanced_deep_health(session: Annotated[Session, Depends(g
|
||||
"status": "healthy",
|
||||
"service": "marketplace-enhanced",
|
||||
"port": 8002,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"feature_tests": feature_tests,
|
||||
"overall_health": "pass" if all(test.get("status") == "pass" for test in feature_tests.values()) else "degraded",
|
||||
}
|
||||
@@ -184,6 +184,6 @@ async def marketplace_enhanced_deep_health(session: Annotated[Session, Depends(g
|
||||
"status": "unhealthy",
|
||||
"service": "marketplace-enhanced",
|
||||
"port": 8002,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"error": "Deep health check failed",
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ GPU marketplace endpoints backed by persistent SQLModel tables.
|
||||
"""
|
||||
|
||||
import statistics
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
@@ -157,7 +157,7 @@ async def register_gpu(request: dict[str, Any], session: Annotated[Session, Depe
|
||||
|
||||
# Create GPU registry record
|
||||
import uuid
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
|
||||
gpu_id = f"gpu_{uuid.uuid4().hex[:8]}"
|
||||
|
||||
@@ -180,7 +180,7 @@ async def register_gpu(request: dict[str, Any], session: Annotated[Session, Depe
|
||||
capabilities=[],
|
||||
average_rating=0.0,
|
||||
total_reviews=0,
|
||||
created_at=datetime.now(datetime.UTC)
|
||||
created_at=datetime.now(timezone.utc)
|
||||
)
|
||||
|
||||
session.add(gpu_record)
|
||||
@@ -259,9 +259,9 @@ async def buy_gpu(
|
||||
)
|
||||
|
||||
# Create booking for the purchase
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
|
||||
start_time = datetime.now(datetime.UTC)
|
||||
start_time = datetime.now(timezone.utc)
|
||||
end_time = start_time + timedelta(hours=request.duration_hours)
|
||||
|
||||
# Calculate total cost
|
||||
@@ -411,7 +411,7 @@ async def sell_gpu(
|
||||
"listing_price": request.listing_price,
|
||||
"status": "listed",
|
||||
"description": request.description,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat() + "Z",
|
||||
"timestamp": datetime.now(timezone.utc).isoformat() + "Z",
|
||||
}
|
||||
|
||||
|
||||
@@ -442,7 +442,7 @@ async def book_gpu(
|
||||
status_code=http_status.HTTP_400_BAD_REQUEST, detail="Booking duration cannot exceed 8760 hours (1 year)"
|
||||
)
|
||||
|
||||
start_time = datetime.now(datetime.UTC)
|
||||
start_time = datetime.now(timezone.utc)
|
||||
end_time = start_time + timedelta(hours=request.duration_hours)
|
||||
|
||||
# Validate booking end time is in the future
|
||||
@@ -593,7 +593,7 @@ async def submit_ollama_task(
|
||||
)
|
||||
|
||||
task_id = f"task_{uuid4().hex[:10]}"
|
||||
submitted_at = datetime.now(datetime.UTC).isoformat() + "Z"
|
||||
submitted_at = datetime.now(timezone.utc).isoformat() + "Z"
|
||||
|
||||
return {
|
||||
"task_id": task_id,
|
||||
@@ -619,7 +619,7 @@ async def send_payment(
|
||||
)
|
||||
|
||||
tx_id = f"tx_{uuid4().hex[:10]}"
|
||||
processed_at = datetime.now(datetime.UTC).isoformat() + "Z"
|
||||
processed_at = datetime.now(timezone.utc).isoformat() + "Z"
|
||||
|
||||
return {
|
||||
"tx_id": tx_id,
|
||||
@@ -920,7 +920,7 @@ async def get_pricing(
|
||||
},
|
||||
"individual_gpu_pricing": dynamic_prices,
|
||||
"market_analysis": market_analysis,
|
||||
"pricing_timestamp": datetime.now(datetime.UTC).isoformat() + "Z",
|
||||
"pricing_timestamp": datetime.now(timezone.utc).isoformat() + "Z",
|
||||
}
|
||||
|
||||
|
||||
@@ -935,5 +935,5 @@ async def bid_gpu(request: dict[str, Any], session: Session = Depends(get_sessio
|
||||
"gpu_id": request.get("gpu_id"),
|
||||
"bid_amount": request.get("bid_amount"),
|
||||
"duration_hours": request.get("duration_hours"),
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat() + "Z",
|
||||
"timestamp": datetime.now(timezone.utc).isoformat() + "Z",
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from typing import Annotated, Any
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request, Response, status
|
||||
@@ -87,7 +87,7 @@ async def submit_result(
|
||||
metrics = dict(req.metrics or {})
|
||||
duration_ms = metrics.get("duration_ms")
|
||||
if duration_ms is None and job.requested_at:
|
||||
duration_ms = int((datetime.now(datetime.UTC) - job.requested_at).total_seconds() * 1000)
|
||||
duration_ms = int((datetime.now(timezone.utc) - job.requested_at).total_seconds() * 1000)
|
||||
metrics["duration_ms"] = duration_ms
|
||||
|
||||
receipt = receipt_service.create_receipt(job, miner_id, req.result, metrics)
|
||||
|
||||
@@ -6,7 +6,7 @@ Provides health monitoring for specialized modality optimization strategies
|
||||
"""
|
||||
|
||||
import sys
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
import psutil
|
||||
@@ -33,7 +33,7 @@ async def modality_optimization_health(session: Annotated[Session, Depends(get_s
|
||||
"status": "healthy",
|
||||
"service": "modality-optimization",
|
||||
"port": 8004,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"python_version": f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}",
|
||||
# System metrics
|
||||
"system": {
|
||||
@@ -86,7 +86,7 @@ async def modality_optimization_health(session: Annotated[Session, Depends(get_s
|
||||
"status": "unhealthy",
|
||||
"service": "modality-optimization",
|
||||
"port": 8004,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"error": "Health check failed",
|
||||
}
|
||||
|
||||
@@ -148,7 +148,7 @@ async def modality_optimization_deep_health(session: Annotated[Session, Depends(
|
||||
"status": "healthy",
|
||||
"service": "modality-optimization",
|
||||
"port": 8004,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"optimization_tests": optimization_tests,
|
||||
"overall_health": (
|
||||
"pass" if all(test.get("status") == "pass" for test in optimization_tests.values()) else "degraded"
|
||||
@@ -161,6 +161,6 @@ async def modality_optimization_deep_health(session: Annotated[Session, Depends(
|
||||
"status": "unhealthy",
|
||||
"service": "modality-optimization",
|
||||
"port": 8004,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"error": "Deep health check failed",
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ Provides a unified dashboard for all 6 enhanced services
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter
|
||||
@@ -75,7 +75,7 @@ async def monitoring_dashboard() -> dict[str, Any]:
|
||||
overall_metrics = calculate_overall_metrics(health_data)
|
||||
|
||||
dashboard_data = {
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"overall_status": overall_metrics["overall_status"],
|
||||
"services": health_data,
|
||||
"metrics": overall_metrics,
|
||||
@@ -84,7 +84,7 @@ async def monitoring_dashboard() -> dict[str, Any]:
|
||||
"healthy_services": len([s for s in health_data.values() if s.get("status") == "healthy"]),
|
||||
"degraded_services": len([s for s in health_data.values() if s.get("status") == "degraded"]),
|
||||
"unhealthy_services": len([s for s in health_data.values() if s.get("status") == "unhealthy"]),
|
||||
"last_updated": datetime.now(datetime.UTC).strftime("%Y-%m-%d %H:%M:%S UTC"),
|
||||
"last_updated": datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC"),
|
||||
},
|
||||
}
|
||||
|
||||
@@ -98,7 +98,7 @@ async def monitoring_dashboard() -> dict[str, Any]:
|
||||
logger.error(f"Failed to generate monitoring dashboard: {e}")
|
||||
return {
|
||||
"error": "Failed to generate dashboard",
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"services": SERVICES,
|
||||
"overall_status": "error",
|
||||
"summary": {
|
||||
@@ -106,7 +106,7 @@ async def monitoring_dashboard() -> dict[str, Any]:
|
||||
"healthy_services": 0,
|
||||
"degraded_services": 0,
|
||||
"unhealthy_services": len(SERVICES),
|
||||
"last_updated": datetime.now(datetime.UTC).strftime("%Y-%m-%d %H:%M:%S UTC"),
|
||||
"last_updated": datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC"),
|
||||
},
|
||||
}
|
||||
|
||||
@@ -119,7 +119,7 @@ async def services_summary() -> dict[str, Any]:
|
||||
try:
|
||||
health_data = await collect_all_health_data()
|
||||
|
||||
summary = {"timestamp": datetime.now(datetime.UTC).isoformat(), "services": {}}
|
||||
summary = {"timestamp": datetime.now(timezone.utc).isoformat(), "services": {}}
|
||||
|
||||
for service_id, service_info in SERVICES.items():
|
||||
health = health_data.get(service_id, {})
|
||||
@@ -136,7 +136,7 @@ async def services_summary() -> dict[str, Any]:
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to generate services summary: {e}")
|
||||
return {"error": "Failed to generate summary", "timestamp": datetime.now(datetime.UTC).isoformat()}
|
||||
return {"error": "Failed to generate summary", "timestamp": datetime.now(timezone.utc).isoformat()}
|
||||
|
||||
|
||||
@router.get("/dashboard/metrics", tags=["monitoring"], summary="System Metrics")
|
||||
@@ -156,7 +156,7 @@ async def system_metrics() -> dict[str, Any]:
|
||||
network = psutil.net_io_counters()
|
||||
|
||||
metrics = {
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"system": {
|
||||
"cpu_percent": cpu_percent,
|
||||
"cpu_count": psutil.cpu_count(),
|
||||
@@ -184,7 +184,7 @@ async def system_metrics() -> dict[str, Any]:
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to collect system metrics: {e}")
|
||||
return {"error": "Failed to collect metrics", "timestamp": datetime.now(datetime.UTC).isoformat()}
|
||||
return {"error": "Failed to collect metrics", "timestamp": datetime.now(timezone.utc).isoformat()}
|
||||
|
||||
|
||||
async def collect_all_health_data() -> dict[str, Any]:
|
||||
@@ -206,7 +206,7 @@ async def collect_all_health_data() -> dict[str, Any]:
|
||||
health_data[service_id] = {
|
||||
"status": "unhealthy",
|
||||
"error": str(result),
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
else:
|
||||
health_data[service_id] = result
|
||||
@@ -225,7 +225,7 @@ async def check_service_health(service_name: str, service_config: dict[str, Any]
|
||||
return {
|
||||
"status": "healthy",
|
||||
"response_time": 0.1, # Placeholder - would be measured
|
||||
"last_check": datetime.now(datetime.UTC).isoformat(),
|
||||
"last_check": datetime.now(timezone.utc).isoformat(),
|
||||
"details": response,
|
||||
}
|
||||
except NetworkError as e:
|
||||
@@ -233,11 +233,11 @@ async def check_service_health(service_name: str, service_config: dict[str, Any]
|
||||
return {
|
||||
"status": "unhealthy",
|
||||
"error": str(e),
|
||||
"last_check": datetime.now(datetime.UTC).isoformat(),
|
||||
"last_check": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
return {"status": "unhealthy", "error": "connection refused", "timestamp": datetime.now(datetime.UTC).isoformat()}
|
||||
return {"status": "unhealthy", "error": "connection refused", "timestamp": datetime.now(timezone.utc).isoformat()}
|
||||
except Exception as e:
|
||||
return {"status": "unhealthy", "error": str(e), "timestamp": datetime.now(datetime.UTC).isoformat()}
|
||||
return {"status": "unhealthy", "error": str(e), "timestamp": datetime.now(timezone.utc).isoformat()}
|
||||
|
||||
|
||||
def calculate_overall_metrics(health_data: dict[str, Any]) -> dict[str, Any]:
|
||||
|
||||
@@ -6,7 +6,7 @@ Provides health monitoring for multi-modal processing capabilities
|
||||
"""
|
||||
|
||||
import sys
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
import psutil
|
||||
@@ -38,7 +38,7 @@ async def multimodal_health(session: Annotated[Session, Depends(get_session)]) -
|
||||
"status": "healthy",
|
||||
"service": "multimodal-agent",
|
||||
"port": 8002,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"python_version": f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}",
|
||||
# System metrics
|
||||
"system": {
|
||||
@@ -81,7 +81,7 @@ async def multimodal_health(session: Annotated[Session, Depends(get_session)]) -
|
||||
"status": "unhealthy",
|
||||
"service": "multimodal-agent",
|
||||
"port": 8002,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"error": "Health check failed",
|
||||
}
|
||||
|
||||
@@ -129,7 +129,7 @@ async def multimodal_deep_health(session: Annotated[Session, Depends(get_session
|
||||
"status": "healthy",
|
||||
"service": "multimodal-agent",
|
||||
"port": 8002,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"modality_tests": modality_tests,
|
||||
"overall_health": "pass" if all(test.get("status") == "pass" for test in modality_tests.values()) else "degraded",
|
||||
}
|
||||
@@ -140,6 +140,6 @@ async def multimodal_deep_health(session: Annotated[Session, Depends(get_session
|
||||
"status": "unhealthy",
|
||||
"service": "multimodal-agent",
|
||||
"port": 8002,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"error": "Deep health check failed",
|
||||
}
|
||||
|
||||
@@ -44,13 +44,13 @@ async def detailed_health() -> dict[str, Any]:
|
||||
try:
|
||||
import psutil
|
||||
import logging
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
|
||||
return {
|
||||
"status": "healthy",
|
||||
"service": "openclaw-enhanced",
|
||||
"port": 8014,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"python_version": "3.13.5",
|
||||
"system": {
|
||||
"cpu_percent": psutil.cpu_percent(),
|
||||
|
||||
@@ -6,7 +6,7 @@ Provides health monitoring for agent orchestration, edge computing, and ecosyste
|
||||
"""
|
||||
|
||||
import sys
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
import psutil
|
||||
@@ -43,7 +43,7 @@ async def openclaw_enhanced_health(session: Annotated[Session, Depends(get_sessi
|
||||
"status": "healthy" if edge_status["available"] else "degraded",
|
||||
"service": "openclaw-enhanced",
|
||||
"port": 8007,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"python_version": f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}",
|
||||
# System metrics
|
||||
"system": {
|
||||
@@ -95,7 +95,7 @@ async def openclaw_enhanced_health(session: Annotated[Session, Depends(get_sessi
|
||||
"status": "unhealthy",
|
||||
"service": "openclaw-enhanced",
|
||||
"port": 8007,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"error": "Health check failed",
|
||||
}
|
||||
|
||||
@@ -162,7 +162,7 @@ async def openclaw_enhanced_deep_health(session: Annotated[Session, Depends(get_
|
||||
"status": "healthy" if edge_status["available"] else "degraded",
|
||||
"service": "openclaw-enhanced",
|
||||
"port": 8007,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"feature_tests": feature_tests,
|
||||
"edge_computing": edge_status,
|
||||
"overall_health": (
|
||||
@@ -178,7 +178,7 @@ async def openclaw_enhanced_deep_health(session: Annotated[Session, Depends(get_
|
||||
"status": "unhealthy",
|
||||
"service": "openclaw-enhanced",
|
||||
"port": 8007,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"error": "Deep health check failed",
|
||||
}
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ Partner Router - Third-party integration management
|
||||
|
||||
import hashlib
|
||||
import secrets
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
@@ -91,7 +91,7 @@ async def register_partner(partner: PartnerRegister, session: Annotated[Session,
|
||||
"api_key": api_key,
|
||||
"api_secret_hash": hashlib.sha256(api_secret.encode()).hexdigest(),
|
||||
"rate_limit": rate_limits.get(partner.integration_type, rate_limits["other"]),
|
||||
"created_at": datetime.now(datetime.UTC),
|
||||
"created_at": datetime.now(timezone.utc),
|
||||
"status": "active",
|
||||
}
|
||||
|
||||
@@ -162,7 +162,7 @@ async def create_webhook(
|
||||
"events": webhook.events,
|
||||
"secret": webhook.secret,
|
||||
"status": "active",
|
||||
"created_at": datetime.now(datetime.UTC),
|
||||
"created_at": datetime.now(timezone.utc),
|
||||
}
|
||||
|
||||
return WebhookResponse(
|
||||
|
||||
@@ -7,7 +7,7 @@ Reputation Management API Endpoints
|
||||
REST API for agent reputation, trust scores, and economic profiles
|
||||
"""
|
||||
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
@@ -272,7 +272,7 @@ async def get_trust_score_breakdown(
|
||||
security_score=security_score,
|
||||
economic_score=economic_score,
|
||||
reputation_level=reputation_level.value,
|
||||
calculated_at=datetime.now(datetime.UTC).isoformat()
|
||||
calculated_at=datetime.now(timezone.utc).isoformat()
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
@@ -348,7 +348,7 @@ async def get_reputation_metrics(
|
||||
]
|
||||
|
||||
# Recent activity (last 24 hours)
|
||||
recent_cutoff = datetime.now(datetime.UTC) - timedelta(days=1)
|
||||
recent_cutoff = datetime.now(timezone.utc) - timedelta(days=1)
|
||||
recent_events = session.execute(
|
||||
select(func.count(ReputationEvent.id)).where(
|
||||
ReputationEvent.occurred_at >= recent_cutoff
|
||||
@@ -474,7 +474,7 @@ async def update_specialization(
|
||||
raise HTTPException(status_code=404, detail="Reputation profile not found")
|
||||
|
||||
reputation.specialization_tags = specialization_tags
|
||||
reputation.updated_at = datetime.now(datetime.UTC)
|
||||
reputation.updated_at = datetime.now(timezone.utc)
|
||||
|
||||
session.commit()
|
||||
session.refresh(reputation)
|
||||
@@ -510,7 +510,7 @@ async def update_region(
|
||||
raise HTTPException(status_code=404, detail="Reputation profile not found")
|
||||
|
||||
reputation.geographic_region = region
|
||||
reputation.updated_at = datetime.now(datetime.UTC)
|
||||
reputation.updated_at = datetime.now(timezone.utc)
|
||||
|
||||
session.commit()
|
||||
session.refresh(reputation)
|
||||
@@ -568,7 +568,7 @@ async def get_cross_chain_reputation(
|
||||
"last_updated": reputation.updated_at.isoformat()
|
||||
}
|
||||
},
|
||||
"last_updated": datetime.now(datetime.UTC).isoformat()
|
||||
"last_updated": datetime.now(timezone.utc).isoformat()
|
||||
}
|
||||
|
||||
except HTTPException:
|
||||
@@ -601,7 +601,7 @@ async def sync_cross_chain_reputation(
|
||||
"agent_id": agent_id,
|
||||
"sync_status": "completed",
|
||||
"chains_synced": [1],
|
||||
"sync_timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"sync_timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"message": "Cross-chain reputation synchronized successfully"
|
||||
}
|
||||
|
||||
@@ -651,7 +651,7 @@ async def get_cross_chain_leaderboard(
|
||||
"total_count": len(agents),
|
||||
"limit": limit,
|
||||
"min_score": min_score,
|
||||
"last_updated": datetime.now(datetime.UTC).isoformat()
|
||||
"last_updated": datetime.now(timezone.utc).isoformat()
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
@@ -691,7 +691,7 @@ async def submit_cross_chain_event(
|
||||
new_score = max(0, min(1000, old_score + (impact * 1000)))
|
||||
|
||||
reputation.trust_score = new_score
|
||||
reputation.updated_at = datetime.now(datetime.UTC)
|
||||
reputation.updated_at = datetime.now(timezone.utc)
|
||||
|
||||
# Update reputation level if needed
|
||||
if new_score >= 900:
|
||||
@@ -708,13 +708,13 @@ async def submit_cross_chain_event(
|
||||
session.commit()
|
||||
|
||||
return {
|
||||
"event_id": f"event_{datetime.now(datetime.UTC).strftime('%Y%m%d%H%M%S')}",
|
||||
"event_id": f"event_{datetime.now(timezone.utc).strftime('%Y%m%d%H%M%S')}",
|
||||
"agent_id": agent_id,
|
||||
"event_type": event_data['event_type'],
|
||||
"impact_score": impact,
|
||||
"old_score": old_score / 1000.0,
|
||||
"new_score": new_score / 1000.0,
|
||||
"processed_at": datetime.now(datetime.UTC).isoformat()
|
||||
"processed_at": datetime.now(timezone.utc).isoformat()
|
||||
}
|
||||
|
||||
except HTTPException:
|
||||
@@ -785,7 +785,7 @@ async def get_cross_chain_analytics(
|
||||
"average_consistency_score": 1.0,
|
||||
"chain_diversity_score": 0.0 # No cross-chain diversity yet
|
||||
},
|
||||
"generated_at": datetime.now(datetime.UTC).isoformat()
|
||||
"generated_at": datetime.now(timezone.utc).isoformat()
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
|
||||
@@ -7,7 +7,7 @@ Reward System API Endpoints
|
||||
REST API for agent rewards, incentives, and performance-based earnings
|
||||
"""
|
||||
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
@@ -368,13 +368,13 @@ async def get_reward_leaderboard(
|
||||
try:
|
||||
# Calculate date range based on period
|
||||
if period == "daily":
|
||||
start_date = datetime.now(datetime.UTC) - timedelta(days=1)
|
||||
start_date = datetime.now(timezone.utc) - timedelta(days=1)
|
||||
elif period == "weekly":
|
||||
start_date = datetime.now(datetime.UTC) - timedelta(days=7)
|
||||
start_date = datetime.now(timezone.utc) - timedelta(days=7)
|
||||
elif period == "monthly":
|
||||
start_date = datetime.now(datetime.UTC) - timedelta(days=30)
|
||||
start_date = datetime.now(timezone.utc) - timedelta(days=30)
|
||||
else:
|
||||
start_date = datetime.now(datetime.UTC) - timedelta(days=7)
|
||||
start_date = datetime.now(timezone.utc) - timedelta(days=7)
|
||||
|
||||
# Query reward profiles
|
||||
query = select(AgentRewardProfile).where(
|
||||
|
||||
@@ -5,14 +5,14 @@ Staking Management API
|
||||
REST API for AI agent staking system with reputation-based yield farming
|
||||
"""
|
||||
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException
|
||||
from pydantic import BaseModel, Field, validator
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..app_logging import get_logger
|
||||
from aitbc import get_logger
|
||||
from ..auth import get_current_user
|
||||
from ..domain.bounty import AgentMetrics, AgentStake, EcosystemMetrics, PerformanceTier, StakeStatus, StakingPool
|
||||
from ..services.blockchain_service import BlockchainService
|
||||
@@ -303,7 +303,7 @@ async def unbond_stake(
|
||||
if stake.status != StakeStatus.ACTIVE:
|
||||
raise HTTPException(status_code=400, detail="Stake is not active")
|
||||
|
||||
if datetime.now(datetime.UTC) < stake.end_time:
|
||||
if datetime.now(timezone.utc) < stake.end_time:
|
||||
raise HTTPException(status_code=400, detail="Lock period has not ended")
|
||||
|
||||
# Initiate unbonding
|
||||
|
||||
@@ -7,7 +7,7 @@ P2P Trading Protocol API Endpoints
|
||||
REST API for agent-to-agent trading, matching, negotiation, and settlement
|
||||
"""
|
||||
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
@@ -634,9 +634,9 @@ async def get_trading_analytics(
|
||||
end_dt = datetime.fromisoformat(end_date)
|
||||
|
||||
if not start_dt:
|
||||
start_dt = datetime.now(datetime.UTC) - timedelta(days=30)
|
||||
start_dt = datetime.now(timezone.utc) - timedelta(days=30)
|
||||
if not end_dt:
|
||||
end_dt = datetime.now(datetime.UTC)
|
||||
end_dt = datetime.now(timezone.utc)
|
||||
|
||||
# Get analytics data (mock implementation)
|
||||
# In real implementation, this would query TradingAnalytics table
|
||||
|
||||
@@ -9,7 +9,7 @@ User Management Router for AITBC
|
||||
import hashlib
|
||||
import time
|
||||
import uuid
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
@@ -70,8 +70,8 @@ async def register_user(user_data: UserCreate, session: Annotated[Session, Depen
|
||||
id=str(uuid.uuid4()),
|
||||
email=user_data.email,
|
||||
username=user_data.username,
|
||||
created_at=datetime.now(datetime.UTC),
|
||||
last_login=datetime.now(datetime.UTC),
|
||||
created_at=datetime.now(timezone.utc),
|
||||
last_login=datetime.now(timezone.utc),
|
||||
)
|
||||
|
||||
session.add(user)
|
||||
@@ -79,7 +79,7 @@ async def register_user(user_data: UserCreate, session: Annotated[Session, Depen
|
||||
session.refresh(user)
|
||||
|
||||
# Create wallet for user
|
||||
wallet = Wallet(user_id=user.id, address=f"aitbc_{user.id[:8]}", balance=0.0, created_at=datetime.now(datetime.UTC))
|
||||
wallet = Wallet(user_id=user.id, address=f"aitbc_{user.id[:8]}", balance=0.0, created_at=datetime.now(timezone.utc))
|
||||
|
||||
session.add(wallet)
|
||||
session.commit()
|
||||
@@ -112,8 +112,8 @@ async def login_user(login_data: UserLogin, session: Annotated[Session, Depends(
|
||||
id=str(uuid.uuid4()),
|
||||
email=f"{login_data.wallet_address}@aitbc.local",
|
||||
username=f"user_{login_data.wallet_address[-8:]}_{str(uuid.uuid4())[:8]}",
|
||||
created_at=datetime.now(datetime.UTC),
|
||||
last_login=datetime.now(datetime.UTC),
|
||||
created_at=datetime.now(timezone.utc),
|
||||
last_login=datetime.now(timezone.utc),
|
||||
)
|
||||
|
||||
session.add(user)
|
||||
@@ -121,14 +121,14 @@ async def login_user(login_data: UserLogin, session: Annotated[Session, Depends(
|
||||
session.refresh(user)
|
||||
|
||||
# Create wallet
|
||||
wallet = Wallet(user_id=user.id, address=login_data.wallet_address, balance=0.0, created_at=datetime.now(datetime.UTC))
|
||||
wallet = Wallet(user_id=user.id, address=login_data.wallet_address, balance=0.0, created_at=datetime.now(timezone.utc))
|
||||
|
||||
session.add(wallet)
|
||||
session.commit()
|
||||
else:
|
||||
# Update last login
|
||||
user = session.execute(select(User).where(User.id == wallet.user_id)).first()
|
||||
user.last_login = datetime.now(datetime.UTC)
|
||||
user.last_login = datetime.now(timezone.utc)
|
||||
session.commit()
|
||||
|
||||
# Create session token
|
||||
|
||||
@@ -8,7 +8,7 @@ ZK Applications Router - Privacy-preserving features for AITBC
|
||||
|
||||
import hashlib
|
||||
import secrets
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
@@ -67,7 +67,7 @@ async def create_identity_commitment(
|
||||
commitment_input = f"{user.email}:{salt}"
|
||||
commitment = hashlib.sha256(commitment_input.encode()).hexdigest()
|
||||
|
||||
return {"commitment": commitment, "salt": salt, "user_id": user.user_id, "created_at": datetime.now(datetime.UTC).isoformat()}
|
||||
return {"commitment": commitment, "salt": salt, "user_id": user.user_id, "created_at": datetime.now(timezone.utc).isoformat()}
|
||||
|
||||
|
||||
@router.post("/zk/membership/verify")
|
||||
@@ -104,7 +104,7 @@ async def verify_group_membership(
|
||||
"group_id": request.group_id,
|
||||
"verified": True,
|
||||
"nullifier": request.nullifier,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
|
||||
@@ -127,7 +127,7 @@ async def submit_private_bid(request: PrivateBidRequest, session: Annotated[Sess
|
||||
"auction_id": request.auction_id,
|
||||
"commitment": request.bid_commitment,
|
||||
"status": "submitted",
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
|
||||
@@ -172,7 +172,7 @@ async def verify_computation_proof(
|
||||
"result_hash": request.result_hash,
|
||||
"public_inputs": request.public_inputs,
|
||||
"verification_key": "demo_vk_12345",
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
return verification_result
|
||||
@@ -197,7 +197,7 @@ async def create_private_receipt(
|
||||
"user_address": user_address,
|
||||
"commitment": commitment,
|
||||
"privacy_level": privacy_level,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"verified": True,
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
Access control service for confidential transactions
|
||||
"""
|
||||
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
|
||||
@@ -216,7 +216,7 @@ class AccessController:
|
||||
|
||||
def _is_business_hours(self) -> bool:
|
||||
"""Check if current time is within business hours"""
|
||||
now = datetime.now(datetime.UTC)
|
||||
now = datetime.now(timezone.utc)
|
||||
|
||||
# Monday-Friday, 9 AM - 5 PM UTC
|
||||
if now.weekday() >= 5: # Weekend
|
||||
@@ -229,7 +229,7 @@ class AccessController:
|
||||
|
||||
def _check_retention_period(self, transaction: dict, role: str | None) -> bool:
|
||||
"""Check if data is within retention period for role"""
|
||||
transaction_date = transaction.get("timestamp", datetime.now(datetime.UTC))
|
||||
transaction_date = transaction.get("timestamp", datetime.now(timezone.utc))
|
||||
|
||||
# Different retention periods for different roles
|
||||
if role == "regulator":
|
||||
@@ -243,7 +243,7 @@ class AccessController:
|
||||
|
||||
expiry_date = transaction_date + timedelta(days=retention_days)
|
||||
|
||||
return datetime.now(datetime.UTC) <= expiry_date
|
||||
return datetime.now(timezone.utc) <= expiry_date
|
||||
|
||||
def _get_participant_info(self, participant_id: str) -> dict | None:
|
||||
"""Get participant information"""
|
||||
@@ -274,8 +274,8 @@ class AccessController:
|
||||
"transaction_miner_id": "miner-789",
|
||||
"miner_id": "miner-789",
|
||||
"purpose": "settlement",
|
||||
"created_at": datetime.now(datetime.UTC).isoformat(),
|
||||
"expires_at": (datetime.now(datetime.UTC) + timedelta(hours=1)).isoformat(),
|
||||
"created_at": datetime.now(timezone.utc).isoformat(),
|
||||
"expires_at": (datetime.now(timezone.utc) + timedelta(hours=1)).isoformat(),
|
||||
"metadata": {"job_id": "job-123", "amount": "1000", "currency": "AITBC"},
|
||||
}
|
||||
if transaction_id.startswith("ctx-"):
|
||||
@@ -286,8 +286,8 @@ class AccessController:
|
||||
"transaction_miner_id": "miner-456",
|
||||
"miner_id": "miner-456",
|
||||
"purpose": "settlement",
|
||||
"created_at": datetime.now(datetime.UTC).isoformat(),
|
||||
"expires_at": (datetime.now(datetime.UTC) + timedelta(hours=1)).isoformat(),
|
||||
"created_at": datetime.now(timezone.utc).isoformat(),
|
||||
"expires_at": (datetime.now(timezone.utc) + timedelta(hours=1)).isoformat(),
|
||||
"metadata": {"job_id": "job-456", "amount": "1000", "currency": "AITBC"},
|
||||
}
|
||||
else:
|
||||
@@ -301,7 +301,7 @@ class AccessController:
|
||||
"""Get cached access result"""
|
||||
if cache_key in self._access_cache:
|
||||
cached = self._access_cache[cache_key]
|
||||
if datetime.now(datetime.UTC) - cached["timestamp"] < self._cache_ttl:
|
||||
if datetime.now(timezone.utc) - cached["timestamp"] < self._cache_ttl:
|
||||
return cached
|
||||
else:
|
||||
del self._access_cache[cache_key]
|
||||
@@ -309,20 +309,20 @@ class AccessController:
|
||||
|
||||
def _cache_result(self, cache_key: str, allowed: bool):
|
||||
"""Cache access result"""
|
||||
self._access_cache[cache_key] = {"allowed": allowed, "timestamp": datetime.now(datetime.UTC)}
|
||||
self._access_cache[cache_key] = {"allowed": allowed, "timestamp": datetime.now(timezone.utc)}
|
||||
|
||||
def create_access_policy(
|
||||
self, name: str, participants: list[str], conditions: dict[str, Any], access_level: AccessLevel
|
||||
) -> str:
|
||||
"""Create a new access policy"""
|
||||
policy_id = f"policy_{datetime.now(datetime.UTC).timestamp()}"
|
||||
policy_id = f"policy_{datetime.now(timezone.utc).timestamp()}"
|
||||
|
||||
policy = {
|
||||
"participants": participants,
|
||||
"conditions": conditions,
|
||||
"access_level": access_level,
|
||||
"time_restrictions": conditions.get("time_restrictions"),
|
||||
"created_at": datetime.now(datetime.UTC).isoformat(),
|
||||
"created_at": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
self.policy_store.add_policy(policy_id, policy)
|
||||
|
||||
@@ -11,7 +11,7 @@ Reinforcement learning frameworks for agent self-improvement
|
||||
from aitbc import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
|
||||
@@ -380,7 +380,7 @@ class AdaptiveLearningService:
|
||||
"action_space_size": len(environment.action_space),
|
||||
"safety_constraints": len(environment.safety_constraints),
|
||||
"max_episodes": environment.max_episodes,
|
||||
"created_at": datetime.now(datetime.UTC).isoformat(),
|
||||
"created_at": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
@@ -403,7 +403,7 @@ class AdaptiveLearningService:
|
||||
"discount_factor": agent.discount_factor,
|
||||
"exploration_rate": agent.exploration_rate,
|
||||
"status": "created",
|
||||
"created_at": datetime.now(datetime.UTC).isoformat(),
|
||||
"created_at": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
@@ -427,7 +427,7 @@ class AdaptiveLearningService:
|
||||
self.training_sessions[session_id] = {
|
||||
"agent_id": agent_id,
|
||||
"environment_id": environment_id,
|
||||
"start_time": datetime.now(datetime.UTC),
|
||||
"start_time": datetime.now(timezone.utc),
|
||||
"config": training_config,
|
||||
"status": "running",
|
||||
}
|
||||
@@ -438,7 +438,7 @@ class AdaptiveLearningService:
|
||||
|
||||
# Update session
|
||||
self.training_sessions[session_id].update(
|
||||
{"status": "completed", "end_time": datetime.now(datetime.UTC), "results": training_results}
|
||||
{"status": "completed", "end_time": datetime.now(timezone.utc), "results": training_results}
|
||||
)
|
||||
|
||||
return {
|
||||
@@ -626,7 +626,7 @@ class AdaptiveLearningService:
|
||||
"performance_metrics": agent.performance_metrics,
|
||||
"current_exploration_rate": agent.exploration_rate,
|
||||
"policy_size": len(agent.q_table) if hasattr(agent, "q_table") else "neural_network",
|
||||
"last_updated": datetime.now(datetime.UTC).isoformat(),
|
||||
"last_updated": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
async def evaluate_agent(self, agent_id: str, environment_id: str, evaluation_config: dict[str, Any]) -> dict[str, Any]:
|
||||
@@ -678,7 +678,7 @@ class AdaptiveLearningService:
|
||||
"min_reward": float(min(evaluation_rewards)),
|
||||
"average_episode_length": float(np.mean(evaluation_lengths)),
|
||||
"success_rate": sum(1 for r in evaluation_rewards if r > 0) / len(evaluation_rewards),
|
||||
"evaluation_timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"evaluation_timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
async def create_reward_function(self, reward_id: str, reward_type: RewardType, config: dict[str, Any]) -> dict[str, Any]:
|
||||
@@ -690,7 +690,7 @@ class AdaptiveLearningService:
|
||||
"config": config,
|
||||
"parameters": config.get("parameters", {}),
|
||||
"weights": config.get("weights", {}),
|
||||
"created_at": datetime.now(datetime.UTC).isoformat(),
|
||||
"created_at": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
self.reward_functions[reward_id] = reward_function
|
||||
|
||||
@@ -7,7 +7,7 @@ Port: 8009
|
||||
"""
|
||||
|
||||
import uuid
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
@@ -120,7 +120,7 @@ async def health_check():
|
||||
"""Health check endpoint"""
|
||||
return {
|
||||
"status": "healthy",
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"gpu_available": torch.cuda.is_available(),
|
||||
"services": {"rl_engine": "operational", "fusion_engine": "operational", "advanced_learning": "operational"},
|
||||
}
|
||||
@@ -193,7 +193,7 @@ async def process_multi_modal_fusion(request: MultiModalFusionRequest):
|
||||
"""Process multi-modal fusion"""
|
||||
|
||||
try:
|
||||
start_time = datetime.now(datetime.UTC)
|
||||
start_time = datetime.now(timezone.utc)
|
||||
|
||||
# Simulate database session
|
||||
|
||||
@@ -213,13 +213,13 @@ async def process_multi_modal_fusion(request: MultiModalFusionRequest):
|
||||
modal_data=request.modal_data, performance_requirements=request.fusion_config or {}
|
||||
)
|
||||
|
||||
processing_time = (datetime.now(datetime.UTC) - start_time).total_seconds() * 1000
|
||||
processing_time = (datetime.now(timezone.utc) - start_time).total_seconds() * 1000
|
||||
|
||||
return {
|
||||
"fusion_result": result,
|
||||
"processing_time_ms": processing_time,
|
||||
"strategy_used": request.fusion_strategy,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
@@ -243,7 +243,7 @@ async def optimize_gpu_processing(request: GPUOptimizationRequest):
|
||||
modality_features=request.modality_features, attention_config=request.attention_config
|
||||
)
|
||||
|
||||
return {"optimization_result": result, "timestamp": datetime.now(datetime.UTC).isoformat()}
|
||||
return {"optimization_result": result, "timestamp": datetime.now(timezone.utc).isoformat()}
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"GPU optimization failed: {e}")
|
||||
@@ -255,7 +255,7 @@ async def advanced_ai_processing(request: AdvancedAIRequest):
|
||||
"""Unified advanced AI processing endpoint"""
|
||||
|
||||
try:
|
||||
datetime.now(datetime.UTC)
|
||||
datetime.now(timezone.utc)
|
||||
|
||||
if request.request_type == "rl_training":
|
||||
# Convert to RL training request
|
||||
@@ -335,7 +335,7 @@ async def get_performance_metrics():
|
||||
}
|
||||
|
||||
return {
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"gpu_metrics": gpu_metrics,
|
||||
"service_metrics": service_metrics,
|
||||
"system_health": "operational",
|
||||
|
||||
@@ -7,7 +7,7 @@ Real-time analytics dashboard, market insights, and performance metrics
|
||||
import asyncio
|
||||
from collections import defaultdict, deque
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ from aitbc import get_logger
|
||||
logger = get_logger(__name__)
|
||||
import json
|
||||
from dataclasses import asdict, dataclass
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
|
||||
@@ -231,8 +231,8 @@ class AdvancedLearningService:
|
||||
performance_metrics={},
|
||||
training_data_size=0,
|
||||
validation_data_size=0,
|
||||
created_at=datetime.now(datetime.UTC),
|
||||
last_updated=datetime.now(datetime.UTC),
|
||||
created_at=datetime.now(timezone.utc),
|
||||
last_updated=datetime.now(timezone.utc),
|
||||
status=LearningStatus.INITIALIZING,
|
||||
)
|
||||
|
||||
@@ -251,7 +251,7 @@ class AdvancedLearningService:
|
||||
computation_efficiency=0.0,
|
||||
learning_rate=self.default_learning_rate,
|
||||
convergence_speed=0.0,
|
||||
last_evaluation=datetime.now(datetime.UTC),
|
||||
last_evaluation=datetime.now(timezone.utc),
|
||||
)
|
||||
|
||||
logger.info(f"Model created: {model_id} for agent {agent_id}")
|
||||
@@ -298,7 +298,7 @@ class AdvancedLearningService:
|
||||
model_id=model_id,
|
||||
agent_id=model.agent_id,
|
||||
learning_type=model.learning_type,
|
||||
start_time=datetime.now(datetime.UTC),
|
||||
start_time=datetime.now(timezone.utc),
|
||||
end_time=None,
|
||||
status=LearningStatus.INITIALIZING,
|
||||
training_data=training_data,
|
||||
@@ -316,7 +316,7 @@ class AdvancedLearningService:
|
||||
|
||||
# Update model status
|
||||
model.status = LearningStatus.TRAINING
|
||||
model.last_updated = datetime.now(datetime.UTC)
|
||||
model.last_updated = datetime.now(timezone.utc)
|
||||
|
||||
# Start training
|
||||
asyncio.create_task(self._execute_learning_session(session_id))
|
||||
@@ -349,7 +349,7 @@ class AdvancedLearningService:
|
||||
model_id=model.id,
|
||||
agent_id=agent_id,
|
||||
learning_type=LearningType.META_LEARNING,
|
||||
start_time=datetime.now(datetime.UTC),
|
||||
start_time=datetime.now(timezone.utc),
|
||||
end_time=None,
|
||||
status=LearningStatus.TRAINING,
|
||||
training_data=meta_data["training"],
|
||||
@@ -400,7 +400,7 @@ class AdvancedLearningService:
|
||||
model_id=model_id,
|
||||
agent_id="federated",
|
||||
learning_type=LearningType.FEDERATED,
|
||||
start_time=datetime.now(datetime.UTC),
|
||||
start_time=datetime.now(timezone.utc),
|
||||
end_time=None,
|
||||
status=LearningStatus.TRAINING,
|
||||
training_data=[],
|
||||
@@ -443,16 +443,16 @@ class AdvancedLearningService:
|
||||
if model.status != LearningStatus.ACTIVE:
|
||||
raise ValueError(f"Model {model_id} not active")
|
||||
|
||||
start_time = datetime.now(datetime.UTC)
|
||||
start_time = datetime.now(timezone.utc)
|
||||
|
||||
# Simulate inference
|
||||
prediction = await self._simulate_inference(model, input_data)
|
||||
|
||||
# Update analytics
|
||||
inference_time = (datetime.now(datetime.UTC) - start_time).total_seconds()
|
||||
inference_time = (datetime.now(timezone.utc) - start_time).total_seconds()
|
||||
analytics = self.learning_analytics[model_id]
|
||||
analytics.total_inference_time += inference_time
|
||||
analytics.last_evaluation = datetime.now(datetime.UTC)
|
||||
analytics.last_evaluation = datetime.now(timezone.utc)
|
||||
|
||||
logger.info(f"Prediction made with model {model_id}")
|
||||
return prediction
|
||||
@@ -480,7 +480,7 @@ class AdvancedLearningService:
|
||||
|
||||
# Update model performance
|
||||
model.accuracy = adaptation_results.get("accuracy", model.accuracy)
|
||||
model.last_updated = datetime.now(datetime.UTC)
|
||||
model.last_updated = datetime.now(timezone.utc)
|
||||
|
||||
# Update analytics
|
||||
analytics = self.learning_analytics[model_id]
|
||||
@@ -573,7 +573,7 @@ class AdvancedLearningService:
|
||||
# Update model
|
||||
model.accuracy = optimization_results.get("accuracy", model.accuracy)
|
||||
model.inference_time = optimization_results.get("inference_time", model.inference_time)
|
||||
model.last_updated = datetime.now(datetime.UTC)
|
||||
model.last_updated = datetime.now(timezone.utc)
|
||||
|
||||
logger.info(f"Model optimized: {model_id}")
|
||||
return True
|
||||
@@ -625,12 +625,12 @@ class AdvancedLearningService:
|
||||
model.recall = np.random.uniform(0.7, 0.95)
|
||||
model.f1_score = np.random.uniform(0.7, 0.95)
|
||||
model.loss = session.results.get(f"epoch_{session.iterations}", {}).get("loss", 0.1)
|
||||
model.training_time = (datetime.now(datetime.UTC) - session.start_time).total_seconds()
|
||||
model.training_time = (datetime.now(timezone.utc) - session.start_time).total_seconds()
|
||||
model.inference_time = np.random.uniform(0.01, 0.1)
|
||||
model.status = LearningStatus.ACTIVE
|
||||
model.last_updated = datetime.now(datetime.UTC)
|
||||
model.last_updated = datetime.now(timezone.utc)
|
||||
|
||||
session.end_time = datetime.now(datetime.UTC)
|
||||
session.end_time = datetime.now(timezone.utc)
|
||||
session.status = LearningStatus.COMPLETED
|
||||
|
||||
# Update analytics
|
||||
@@ -673,9 +673,9 @@ class AdvancedLearningService:
|
||||
# Update model with meta-learning results
|
||||
model.accuracy = np.random.uniform(0.8, 0.98)
|
||||
model.status = LearningStatus.ACTIVE
|
||||
model.last_updated = datetime.now(datetime.UTC)
|
||||
model.last_updated = datetime.now(timezone.utc)
|
||||
|
||||
session.end_time = datetime.now(datetime.UTC)
|
||||
session.end_time = datetime.now(timezone.utc)
|
||||
session.status = LearningStatus.COMPLETED
|
||||
|
||||
logger.info(f"Meta-learning completed: {session_id}")
|
||||
@@ -713,9 +713,9 @@ class AdvancedLearningService:
|
||||
# Update model
|
||||
model.accuracy = np.random.uniform(0.75, 0.92)
|
||||
model.status = LearningStatus.ACTIVE
|
||||
model.last_updated = datetime.now(datetime.UTC)
|
||||
model.last_updated = datetime.now(timezone.utc)
|
||||
|
||||
session.end_time = datetime.now(datetime.UTC)
|
||||
session.end_time = datetime.now(timezone.utc)
|
||||
session.status = LearningStatus.COMPLETED
|
||||
|
||||
logger.info(f"Federated learning completed: {session_id}")
|
||||
@@ -811,7 +811,7 @@ class AdvancedLearningService:
|
||||
|
||||
while True:
|
||||
try:
|
||||
current_time = datetime.now(datetime.UTC)
|
||||
current_time = datetime.now(timezone.utc)
|
||||
|
||||
for session_id, session in self.learning_sessions.items():
|
||||
if session.status == LearningStatus.TRAINING:
|
||||
@@ -862,7 +862,7 @@ class AdvancedLearningService:
|
||||
|
||||
while True:
|
||||
try:
|
||||
current_time = datetime.now(datetime.UTC)
|
||||
current_time = datetime.now(timezone.utc)
|
||||
inactive_sessions = []
|
||||
|
||||
for session_id, session in self.learning_sessions.items():
|
||||
@@ -905,7 +905,7 @@ class AdvancedLearningService:
|
||||
"models": {k: asdict(v) for k, v in self.models.items()},
|
||||
"sessions": {k: asdict(v) for k, v in self.learning_sessions.items()},
|
||||
"analytics": {k: asdict(v) for k, v in self.learning_analytics.items()},
|
||||
"export_timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"export_timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
if format.lower() == "json":
|
||||
|
||||
@@ -5,7 +5,7 @@ Phase 5.1: Advanced AI Capabilities Enhancement
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
@@ -616,7 +616,7 @@ class AdvancedReinforcementLearningEngine:
|
||||
rl_config.success_rate_history = training_results["success_rate_history"]
|
||||
rl_config.convergence_episode = training_results["convergence_episode"]
|
||||
rl_config.status = "ready"
|
||||
rl_config.trained_at = datetime.now(datetime.UTC)
|
||||
rl_config.trained_at = datetime.now(timezone.utc)
|
||||
rl_config.training_progress = 1.0
|
||||
|
||||
session.commit()
|
||||
@@ -1329,7 +1329,7 @@ class MarketplaceStrategyOptimizer:
|
||||
rl_config.deployment_performance = deployment_performance
|
||||
rl_config.deployment_count += 1
|
||||
rl_config.status = "deployed"
|
||||
rl_config.deployed_at = datetime.now(datetime.UTC)
|
||||
rl_config.deployed_at = datetime.now(timezone.utc)
|
||||
|
||||
session.commit()
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ logger = get_logger(__name__)
|
||||
import hashlib
|
||||
import json
|
||||
from dataclasses import asdict, dataclass, field
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
|
||||
@@ -199,7 +199,7 @@ class AgentCommunicationService:
|
||||
messages_sent=0,
|
||||
messages_received=0,
|
||||
active_channels=0,
|
||||
last_activity=datetime.now(datetime.UTC),
|
||||
last_activity=datetime.now(timezone.utc),
|
||||
average_response_time=0.0,
|
||||
delivery_rate=0.0,
|
||||
)
|
||||
@@ -346,11 +346,11 @@ class AgentCommunicationService:
|
||||
encryption_key=encryption_key,
|
||||
encryption_type=encryption_type,
|
||||
size=len(content_bytes),
|
||||
timestamp=datetime.now(datetime.UTC),
|
||||
timestamp=datetime.now(timezone.utc),
|
||||
status=MessageStatus.PENDING,
|
||||
price=price,
|
||||
metadata=metadata or {},
|
||||
expires_at=datetime.now(datetime.UTC) + timedelta(seconds=self.message_timeout),
|
||||
expires_at=datetime.now(timezone.utc) + timedelta(seconds=self.message_timeout),
|
||||
reply_to=reply_to,
|
||||
thread_id=thread_id,
|
||||
)
|
||||
@@ -395,7 +395,7 @@ class AgentCommunicationService:
|
||||
raise ValueError(f"Message {message_id} not pending")
|
||||
|
||||
message.status = MessageStatus.DELIVERED
|
||||
message.delivery_timestamp = datetime.now(datetime.UTC)
|
||||
message.delivery_timestamp = datetime.now(timezone.utc)
|
||||
|
||||
# Update stats
|
||||
await self._update_message_stats(message.sender, message.recipient, "delivered")
|
||||
@@ -426,7 +426,7 @@ class AgentCommunicationService:
|
||||
|
||||
# Mark as read
|
||||
message.status = MessageStatus.READ
|
||||
message.read_timestamp = datetime.now(datetime.UTC)
|
||||
message.read_timestamp = datetime.now(timezone.utc)
|
||||
|
||||
# Update stats
|
||||
await self._update_message_stats(message.sender, message.recipient, "read")
|
||||
@@ -495,8 +495,8 @@ class AgentCommunicationService:
|
||||
agent2=agent2,
|
||||
channel_type=channel_type,
|
||||
is_active=True,
|
||||
created_timestamp=datetime.now(datetime.UTC),
|
||||
last_activity=datetime.now(datetime.UTC),
|
||||
created_timestamp=datetime.now(timezone.utc),
|
||||
last_activity=datetime.now(timezone.utc),
|
||||
message_count=0,
|
||||
participants=[agent1, agent2],
|
||||
encryption_enabled=encryption_enabled,
|
||||
@@ -814,17 +814,17 @@ class AgentCommunicationService:
|
||||
if sender in self.communication_stats:
|
||||
self.communication_stats[sender].total_messages += 1
|
||||
self.communication_stats[sender].messages_sent += 1
|
||||
self.communication_stats[sender].last_activity = datetime.now(datetime.UTC)
|
||||
self.communication_stats[sender].last_activity = datetime.now(timezone.utc)
|
||||
|
||||
elif action == "delivered":
|
||||
if recipient in self.communication_stats:
|
||||
self.communication_stats[recipient].total_messages += 1
|
||||
self.communication_stats[recipient].messages_received += 1
|
||||
self.communication_stats[recipient].last_activity = datetime.now(datetime.UTC)
|
||||
self.communication_stats[recipient].last_activity = datetime.now(timezone.utc)
|
||||
|
||||
elif action == "read":
|
||||
if recipient in self.communication_stats:
|
||||
self.communication_stats[recipient].last_activity = datetime.now(datetime.UTC)
|
||||
self.communication_stats[recipient].last_activity = datetime.now(timezone.utc)
|
||||
|
||||
async def _process_message_queue(self):
|
||||
"""Process message queue for delivery"""
|
||||
@@ -848,7 +848,7 @@ class AgentCommunicationService:
|
||||
|
||||
while True:
|
||||
try:
|
||||
current_time = datetime.now(datetime.UTC)
|
||||
current_time = datetime.now(timezone.utc)
|
||||
expired_messages = []
|
||||
|
||||
for message_id, message in self.messages.items():
|
||||
@@ -875,7 +875,7 @@ class AgentCommunicationService:
|
||||
|
||||
while True:
|
||||
try:
|
||||
current_time = datetime.now(datetime.UTC)
|
||||
current_time = datetime.now(timezone.utc)
|
||||
inactive_channels = []
|
||||
|
||||
for channel_id, channel in self.channels.items():
|
||||
@@ -958,7 +958,7 @@ class AgentCommunicationService:
|
||||
"messages": {k: asdict(v) for k, v in self.messages.items()},
|
||||
"channels": {k: asdict(v) for k, v in self.channels.items()},
|
||||
"templates": {k: asdict(v) for k, v in self.message_templates.items()},
|
||||
"export_timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"export_timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
if format.lower() == "json":
|
||||
|
||||
@@ -6,7 +6,7 @@ Integrates agent orchestration with existing ML ZK proof system and provides dep
|
||||
from aitbc import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
@@ -104,8 +104,8 @@ class AgentDeploymentConfig(SQLModel, table=True):
|
||||
last_health_check: datetime | None = Field(default=None)
|
||||
|
||||
# Metadata
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
class AgentDeploymentInstance(SQLModel, table=True):
|
||||
@@ -149,8 +149,8 @@ class AgentDeploymentInstance(SQLModel, table=True):
|
||||
health_check_history: list[dict[str, Any]] = Field(default_factory=list, sa_column=Column(JSON))
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
class AgentIntegrationManager:
|
||||
@@ -380,7 +380,7 @@ class AgentDeploymentManager:
|
||||
|
||||
# Update deployment status
|
||||
config.status = DeploymentStatus.DEPLOYING
|
||||
config.deployment_time = datetime.now(datetime.UTC)
|
||||
config.deployment_time = datetime.now(timezone.utc)
|
||||
self.session.commit()
|
||||
|
||||
deployment_result = {
|
||||
@@ -469,7 +469,7 @@ class AgentDeploymentManager:
|
||||
instance.status = DeploymentStatus.DEPLOYED
|
||||
instance.health_status = "healthy"
|
||||
instance.endpoint_url = f"http://localhost:{instance.port}"
|
||||
instance.last_health_check = datetime.now(datetime.UTC)
|
||||
instance.last_health_check = datetime.now(timezone.utc)
|
||||
|
||||
self.session.commit()
|
||||
|
||||
@@ -554,11 +554,11 @@ class AgentDeploymentManager:
|
||||
|
||||
# Update instance health status
|
||||
instance.health_status = health_status
|
||||
instance.last_health_check = datetime.now(datetime.UTC)
|
||||
instance.last_health_check = datetime.now(timezone.utc)
|
||||
|
||||
# Add to health check history
|
||||
health_check_record = {
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"status": health_status,
|
||||
"response_time": response_time,
|
||||
}
|
||||
@@ -582,7 +582,7 @@ class AgentDeploymentManager:
|
||||
|
||||
# Mark as unhealthy
|
||||
instance.health_status = "unhealthy"
|
||||
instance.last_health_check = datetime.now(datetime.UTC)
|
||||
instance.last_health_check = datetime.now(timezone.utc)
|
||||
instance.consecutive_failures += 1
|
||||
self.session.commit()
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ from aitbc import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
|
||||
@@ -58,7 +58,7 @@ class AgentCapability:
|
||||
performance_score: float # 0-1
|
||||
cost_per_hour: float
|
||||
reliability_score: float # 0-1
|
||||
last_updated: datetime = field(default_factory=datetime.now(datetime.UTC))
|
||||
last_updated: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -102,7 +102,7 @@ class OrchestrationPlan:
|
||||
resource_requirements: dict[ResourceType, int]
|
||||
estimated_cost: float
|
||||
confidence_score: float
|
||||
created_at: datetime = field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
class AgentOrchestrator:
|
||||
@@ -360,7 +360,7 @@ class AgentOrchestrator:
|
||||
|
||||
# Process each execution stage
|
||||
for stage_idx, stage_sub_tasks in enumerate(decomposition.execution_plan):
|
||||
stage_start = datetime.now(datetime.UTC) + timedelta(hours=stage_idx * 2) # Estimate 2 hours per stage
|
||||
stage_start = datetime.now(timezone.utc) + timedelta(hours=stage_idx * 2) # Estimate 2 hours per stage
|
||||
|
||||
for sub_task_id in stage_sub_tasks:
|
||||
# Find sub-task
|
||||
@@ -368,7 +368,7 @@ class AgentOrchestrator:
|
||||
|
||||
# Create assignment (will be filled during execution)
|
||||
assignment = AgentAssignment(
|
||||
sub_task_id=sub_task_id, agent_id="", assigned_at=datetime.now(datetime.UTC) # Will be assigned during execution
|
||||
sub_task_id=sub_task_id, agent_id="", assigned_at=datetime.now(timezone.utc) # Will be assigned during execution
|
||||
)
|
||||
assignments.append(assignment)
|
||||
|
||||
@@ -469,7 +469,7 @@ class AgentOrchestrator:
|
||||
sub_task_id=sub_task_id,
|
||||
resource_type=ResourceType.GPU,
|
||||
allocated_amount=1,
|
||||
allocated_at=datetime.now(datetime.UTC),
|
||||
allocated_at=datetime.now(timezone.utc),
|
||||
expected_duration=requirements.estimated_duration,
|
||||
)
|
||||
allocations.append(gpu_allocation)
|
||||
@@ -480,7 +480,7 @@ class AgentOrchestrator:
|
||||
sub_task_id=sub_task_id,
|
||||
resource_type=ResourceType.MEMORY,
|
||||
allocated_amount=requirements.memory_requirement,
|
||||
allocated_at=datetime.now(datetime.UTC),
|
||||
allocated_at=datetime.now(timezone.utc),
|
||||
expected_duration=requirements.estimated_duration,
|
||||
)
|
||||
allocations.append(memory_allocation)
|
||||
@@ -568,7 +568,7 @@ class AgentOrchestrator:
|
||||
# For now, assume agents are healthy if they have recent updates
|
||||
|
||||
capability = self.agent_capabilities[agent_id]
|
||||
time_since_update = datetime.now(datetime.UTC) - capability.last_updated
|
||||
time_since_update = datetime.now(timezone.utc) - capability.last_updated
|
||||
|
||||
if time_since_update > timedelta(minutes=5):
|
||||
if self.agent_status[agent_id] != AgentStatus.OFFLINE:
|
||||
@@ -619,7 +619,7 @@ class AgentOrchestrator:
|
||||
|
||||
# Adjust for deadline
|
||||
if deadline:
|
||||
time_to_deadline = (deadline - datetime.now(datetime.UTC)).total_seconds() / 3600
|
||||
time_to_deadline = (deadline - datetime.now(timezone.utc)).total_seconds() / 3600
|
||||
if time_to_deadline < decomposition.estimated_total_duration:
|
||||
confidence *= 0.6
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ Implements meta-learning, resource optimization, and performance enhancement for
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
@@ -109,7 +109,7 @@ class MetaLearningEngine:
|
||||
model.training_time = training_results["training_time"]
|
||||
model.computational_cost = training_results["computational_cost"]
|
||||
model.status = "ready"
|
||||
model.trained_at = datetime.now(datetime.UTC)
|
||||
model.trained_at = datetime.now(timezone.utc)
|
||||
|
||||
session.commit()
|
||||
|
||||
@@ -351,7 +351,7 @@ class ResourceManager:
|
||||
network_bandwidth=optimized_allocation[ResourceType.NETWORK],
|
||||
optimization_target=optimization_target,
|
||||
status="allocated",
|
||||
allocated_at=datetime.now(datetime.UTC),
|
||||
allocated_at=datetime.now(timezone.utc),
|
||||
)
|
||||
|
||||
session.add(allocation)
|
||||
@@ -601,7 +601,7 @@ class PerformanceOptimizer:
|
||||
optimization.convergence_achieved = optimization_results["converged"]
|
||||
optimization.optimization_applied = True
|
||||
optimization.status = "completed"
|
||||
optimization.completed_at = datetime.now(datetime.UTC)
|
||||
optimization.completed_at = datetime.now(timezone.utc)
|
||||
|
||||
session.commit()
|
||||
|
||||
@@ -619,7 +619,7 @@ class PerformanceOptimizer:
|
||||
) -> dict[str, Any]:
|
||||
"""Run comprehensive optimization process"""
|
||||
|
||||
start_time = datetime.now(datetime.UTC)
|
||||
start_time = datetime.now(timezone.utc)
|
||||
|
||||
# Step 1: Analyze current performance
|
||||
analysis_results = self.analyze_current_performance(current_performance, target_metric)
|
||||
@@ -636,7 +636,7 @@ class PerformanceOptimizer:
|
||||
# Step 5: Calculate improvements
|
||||
improvements = self.calculate_improvements(current_performance, applied_performance)
|
||||
|
||||
end_time = datetime.now(datetime.UTC)
|
||||
end_time = datetime.now(timezone.utc)
|
||||
duration = (end_time - start_time).total_seconds()
|
||||
|
||||
return {
|
||||
@@ -865,7 +865,7 @@ class AgentPerformanceService:
|
||||
expertise_levels={},
|
||||
performance_history=[],
|
||||
benchmark_scores={},
|
||||
created_at=datetime.now(datetime.UTC),
|
||||
created_at=datetime.now(timezone.utc),
|
||||
)
|
||||
|
||||
self.session.add(profile)
|
||||
@@ -892,7 +892,7 @@ class AgentPerformanceService:
|
||||
profile.performance_metrics.update(new_metrics)
|
||||
|
||||
# Add to performance history
|
||||
history_entry = {"timestamp": datetime.now(datetime.UTC).isoformat(), "metrics": new_metrics, "context": task_context or {}}
|
||||
history_entry = {"timestamp": datetime.now(timezone.utc).isoformat(), "metrics": new_metrics, "context": task_context or {}}
|
||||
profile.performance_history.append(history_entry)
|
||||
|
||||
# Calculate overall score
|
||||
@@ -901,8 +901,8 @@ class AgentPerformanceService:
|
||||
# Update trends
|
||||
profile.improvement_trends = self.calculate_improvement_trends(profile.performance_history)
|
||||
|
||||
profile.updated_at = datetime.now(datetime.UTC)
|
||||
profile.last_assessed = datetime.now(datetime.UTC)
|
||||
profile.updated_at = datetime.now(timezone.utc)
|
||||
profile.last_assessed = datetime.now(timezone.utc)
|
||||
|
||||
self.session.commit()
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ Provides portfolio creation, rebalancing, risk assessment, and trading strategy
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
|
||||
from aitbc import get_logger
|
||||
from fastapi import HTTPException
|
||||
@@ -86,8 +86,8 @@ class AgentPortfolioManager:
|
||||
initial_capital=portfolio_data.initial_capital,
|
||||
risk_tolerance=portfolio_data.risk_tolerance,
|
||||
is_active=True,
|
||||
created_at=datetime.now(datetime.UTC),
|
||||
last_rebalance=datetime.now(datetime.UTC),
|
||||
created_at=datetime.now(timezone.utc),
|
||||
last_rebalance=datetime.now(timezone.utc),
|
||||
)
|
||||
|
||||
self.session.add(portfolio)
|
||||
@@ -154,7 +154,7 @@ class AgentPortfolioManager:
|
||||
price=trade_result.price,
|
||||
status=TradeStatus.EXECUTED,
|
||||
transaction_hash=trade_result.transaction_hash,
|
||||
executed_at=datetime.now(datetime.UTC),
|
||||
executed_at=datetime.now(timezone.utc),
|
||||
)
|
||||
|
||||
self.session.add(trade)
|
||||
@@ -213,7 +213,7 @@ class AgentPortfolioManager:
|
||||
continue
|
||||
|
||||
# Update portfolio rebalance timestamp
|
||||
portfolio.last_rebalance = datetime.now(datetime.UTC)
|
||||
portfolio.last_rebalance = datetime.now(timezone.utc)
|
||||
self.session.commit()
|
||||
|
||||
logger.info(f"Rebalanced portfolio {portfolio.id} with {len(executed_trades)} trades")
|
||||
@@ -250,10 +250,10 @@ class AgentPortfolioManager:
|
||||
existing_metrics.sharpe_ratio = risk_metrics.sharpe_ratio
|
||||
existing_metrics.var_95 = risk_metrics.var_95
|
||||
existing_metrics.risk_level = risk_metrics.risk_level
|
||||
existing_metrics.updated_at = datetime.now(datetime.UTC)
|
||||
existing_metrics.updated_at = datetime.now(timezone.utc)
|
||||
else:
|
||||
risk_metrics.portfolio_id = portfolio.id
|
||||
risk_metrics.updated_at = datetime.now(datetime.UTC)
|
||||
risk_metrics.updated_at = datetime.now(timezone.utc)
|
||||
self.session.add(risk_metrics)
|
||||
|
||||
# Update portfolio risk score
|
||||
@@ -301,7 +301,7 @@ class AgentPortfolioManager:
|
||||
max_drawdown=strategy_data.max_drawdown,
|
||||
rebalance_frequency=strategy_data.rebalance_frequency,
|
||||
is_active=True,
|
||||
created_at=datetime.now(datetime.UTC),
|
||||
created_at=datetime.now(timezone.utc),
|
||||
)
|
||||
|
||||
self.session.add(strategy)
|
||||
@@ -343,7 +343,7 @@ class AgentPortfolioManager:
|
||||
target_allocation=allocation,
|
||||
current_allocation=0.0,
|
||||
balance=0,
|
||||
created_at=datetime.now(datetime.UTC),
|
||||
created_at=datetime.now(timezone.utc),
|
||||
)
|
||||
self.session.add(asset)
|
||||
|
||||
@@ -412,7 +412,7 @@ class AgentPortfolioManager:
|
||||
|
||||
if sell_asset:
|
||||
sell_asset.balance -= trade.sell_amount
|
||||
sell_asset.updated_at = datetime.now(datetime.UTC)
|
||||
sell_asset.updated_at = datetime.now(timezone.utc)
|
||||
|
||||
# Update buy asset
|
||||
buy_asset = self.session.execute(
|
||||
@@ -423,7 +423,7 @@ class AgentPortfolioManager:
|
||||
|
||||
if buy_asset:
|
||||
buy_asset.balance += trade.buy_amount
|
||||
buy_asset.updated_at = datetime.now(datetime.UTC)
|
||||
buy_asset.updated_at = datetime.now(timezone.utc)
|
||||
else:
|
||||
# Create new asset if it doesn't exist
|
||||
new_asset = PortfolioAsset(
|
||||
@@ -432,7 +432,7 @@ class AgentPortfolioManager:
|
||||
target_allocation=0.0,
|
||||
current_allocation=0.0,
|
||||
balance=trade.buy_amount,
|
||||
created_at=datetime.now(datetime.UTC),
|
||||
created_at=datetime.now(timezone.utc),
|
||||
)
|
||||
self.session.add(new_asset)
|
||||
|
||||
@@ -449,10 +449,10 @@ class AgentPortfolioManager:
|
||||
price = await self.price_service.get_price(asset.token_symbol)
|
||||
asset_value = asset.balance * price
|
||||
asset.current_allocation = (asset_value / portfolio_value) * 100
|
||||
asset.updated_at = datetime.now(datetime.UTC)
|
||||
asset.updated_at = datetime.now(timezone.utc)
|
||||
|
||||
portfolio.total_value = portfolio_value
|
||||
portfolio.updated_at = datetime.now(datetime.UTC)
|
||||
portfolio.updated_at = datetime.now(timezone.utc)
|
||||
|
||||
async def _calculate_portfolio_value(self, portfolio: AgentPortfolio) -> float:
|
||||
"""Calculate total portfolio value"""
|
||||
@@ -475,7 +475,7 @@ class AgentPortfolioManager:
|
||||
if not strategy:
|
||||
return False
|
||||
|
||||
time_since_rebalance = datetime.now(datetime.UTC) - portfolio.last_rebalance
|
||||
time_since_rebalance = datetime.now(timezone.utc) - portfolio.last_rebalance
|
||||
if time_since_rebalance > timedelta(seconds=strategy.rebalance_frequency):
|
||||
return True
|
||||
|
||||
@@ -548,7 +548,7 @@ class AgentPortfolioManager:
|
||||
"current_value": current_value,
|
||||
"initial_value": initial_value,
|
||||
"total_trades": len(trades),
|
||||
"last_updated": datetime.now(datetime.UTC).isoformat(),
|
||||
"last_updated": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ import json
|
||||
from aitbc import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
@@ -57,7 +57,7 @@ class AgentAuditLog(SQLModel, table=True):
|
||||
|
||||
# Event information
|
||||
event_type: AuditEventType = Field(index=True)
|
||||
timestamp: datetime = Field(default_factory=datetime.now(datetime.UTC), index=True)
|
||||
timestamp: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True)
|
||||
|
||||
# Entity references
|
||||
workflow_id: str | None = Field(index=True)
|
||||
@@ -85,7 +85,7 @@ class AgentAuditLog(SQLModel, table=True):
|
||||
signature_valid: bool | None = Field(default=None)
|
||||
|
||||
# Metadata
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
class AgentSecurityPolicy(SQLModel, table=True):
|
||||
@@ -124,8 +124,8 @@ class AgentSecurityPolicy(SQLModel, table=True):
|
||||
|
||||
# Status
|
||||
is_active: bool = Field(default=True)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
class AgentTrustScore(SQLModel, table=True):
|
||||
@@ -164,8 +164,8 @@ class AgentTrustScore(SQLModel, table=True):
|
||||
violation_history: list[dict[str, Any]] = Field(default_factory=list, sa_column=Column(JSON))
|
||||
|
||||
# Metadata
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
class AgentSandboxConfig(SQLModel, table=True):
|
||||
@@ -208,8 +208,8 @@ class AgentSandboxConfig(SQLModel, table=True):
|
||||
|
||||
# Status
|
||||
is_active: bool = Field(default=True)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
class AgentAuditor:
|
||||
@@ -425,13 +425,13 @@ class AgentTrustManager:
|
||||
|
||||
if security_violation:
|
||||
trust_score.security_violations += 1
|
||||
trust_score.last_violation = datetime.now(datetime.UTC)
|
||||
trust_score.violation_history.append({"timestamp": datetime.now(datetime.UTC).isoformat(), "type": "security_violation"})
|
||||
trust_score.last_violation = datetime.now(timezone.utc)
|
||||
trust_score.violation_history.append({"timestamp": datetime.now(timezone.utc).isoformat(), "type": "security_violation"})
|
||||
|
||||
if policy_violation:
|
||||
trust_score.policy_violations += 1
|
||||
trust_score.last_violation = datetime.now(datetime.UTC)
|
||||
trust_score.violation_history.append({"timestamp": datetime.now(datetime.UTC).isoformat(), "type": "policy_violation"})
|
||||
trust_score.last_violation = datetime.now(timezone.utc)
|
||||
trust_score.violation_history.append({"timestamp": datetime.now(timezone.utc).isoformat(), "type": "policy_violation"})
|
||||
|
||||
# Calculate scores
|
||||
trust_score.trust_score = self._calculate_trust_score(trust_score)
|
||||
@@ -449,8 +449,8 @@ class AgentTrustManager:
|
||||
trust_score.average_execution_time * (trust_score.total_executions - 1) + execution_time
|
||||
) / trust_score.total_executions
|
||||
|
||||
trust_score.last_execution = datetime.now(datetime.UTC)
|
||||
trust_score.updated_at = datetime.now(datetime.UTC)
|
||||
trust_score.last_execution = datetime.now(timezone.utc)
|
||||
trust_score.updated_at = datetime.now(timezone.utc)
|
||||
|
||||
self.session.commit()
|
||||
self.session.refresh(trust_score)
|
||||
@@ -477,7 +477,7 @@ class AgentTrustManager:
|
||||
|
||||
# Recency bonus (recent successful executions)
|
||||
if trust_score.last_execution:
|
||||
days_since_last = (datetime.now(datetime.UTC) - trust_score.last_execution).days
|
||||
days_since_last = (datetime.now(timezone.utc) - trust_score.last_execution).days
|
||||
if days_since_last < 7:
|
||||
base_score += 5 # Recent activity bonus
|
||||
elif days_since_last > 30:
|
||||
@@ -735,7 +735,7 @@ class AgentSandboxManager:
|
||||
if sandbox:
|
||||
# Mark as inactive
|
||||
sandbox.is_active = False
|
||||
sandbox.updated_at = datetime.now(datetime.UTC)
|
||||
sandbox.updated_at = datetime.now(timezone.utc)
|
||||
self.session.commit()
|
||||
|
||||
# Sandbox cleanup requires integration with:
|
||||
|
||||
@@ -4,7 +4,7 @@ Implements core orchestration logic and state management for AI agent workflows
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from typing import Any
|
||||
|
||||
from aitbc import get_logger
|
||||
@@ -60,7 +60,7 @@ class AgentStateManager:
|
||||
stmt = (
|
||||
update(AgentExecution)
|
||||
.where(AgentExecution.id == execution_id)
|
||||
.values(status=status, updated_at=datetime.now(datetime.UTC), **kwargs)
|
||||
.values(status=status, updated_at=datetime.now(timezone.utc), **kwargs)
|
||||
)
|
||||
|
||||
self.session.execute(stmt)
|
||||
@@ -101,7 +101,7 @@ class AgentStateManager:
|
||||
stmt = (
|
||||
update(AgentStepExecution)
|
||||
.where(AgentStepExecution.id == step_execution_id)
|
||||
.values(updated_at=datetime.now(datetime.UTC), **kwargs)
|
||||
.values(updated_at=datetime.now(timezone.utc), **kwargs)
|
||||
)
|
||||
|
||||
self.session.execute(stmt)
|
||||
@@ -148,7 +148,7 @@ class AgentVerifier:
|
||||
|
||||
async def _basic_verify_step(self, step_execution: AgentStepExecution) -> dict[str, Any]:
|
||||
"""Basic verification of step execution"""
|
||||
start_time = datetime.now(datetime.UTC)
|
||||
start_time = datetime.now(timezone.utc)
|
||||
|
||||
# Basic checks: execution completed, has output, no errors
|
||||
verified = (
|
||||
@@ -157,7 +157,7 @@ class AgentVerifier:
|
||||
and step_execution.error_message is None
|
||||
)
|
||||
|
||||
verification_time = (datetime.now(datetime.UTC) - start_time).total_seconds()
|
||||
verification_time = (datetime.now(timezone.utc) - start_time).total_seconds()
|
||||
|
||||
return {
|
||||
"verified": verified,
|
||||
@@ -169,7 +169,7 @@ class AgentVerifier:
|
||||
|
||||
async def _full_verify_step(self, step_execution: AgentStepExecution) -> dict[str, Any]:
|
||||
"""Full verification with additional checks"""
|
||||
start_time = datetime.now(datetime.UTC)
|
||||
start_time = datetime.now(timezone.utc)
|
||||
|
||||
# Basic verification first
|
||||
basic_result = await self._basic_verify_step(step_execution)
|
||||
@@ -190,7 +190,7 @@ class AgentVerifier:
|
||||
if step_execution.memory_usage and step_execution.memory_usage < 8192: # < 8GB
|
||||
additional_checks.append("reasonable_memory_usage")
|
||||
|
||||
verification_time = (datetime.now(datetime.UTC) - start_time).total_seconds()
|
||||
verification_time = (datetime.now(timezone.utc) - start_time).total_seconds()
|
||||
|
||||
return {
|
||||
"verified": basic_result["verified"],
|
||||
@@ -209,7 +209,7 @@ class AgentVerifier:
|
||||
2. Verify proof against public parameters
|
||||
3. Return verification result with proof hash
|
||||
"""
|
||||
datetime.now(datetime.UTC)
|
||||
datetime.now(timezone.utc)
|
||||
|
||||
# For now, fall back to full verification
|
||||
# ZK proof generation and verification requires specialized cryptographic libraries
|
||||
@@ -245,7 +245,7 @@ class AIAgentOrchestrator:
|
||||
try:
|
||||
# Start execution
|
||||
await self.state_manager.update_execution_status(
|
||||
execution.id, status=AgentStatus.RUNNING, started_at=datetime.now(datetime.UTC), total_steps=len(workflow.steps)
|
||||
execution.id, status=AgentStatus.RUNNING, started_at=datetime.now(timezone.utc), total_steps=len(workflow.steps)
|
||||
)
|
||||
|
||||
# Execute steps asynchronously
|
||||
@@ -340,7 +340,7 @@ class AIAgentOrchestrator:
|
||||
try:
|
||||
# Update step status to running
|
||||
await self.state_manager.update_step_execution(
|
||||
step_execution.id, status=AgentStatus.RUNNING, started_at=datetime.now(datetime.UTC), input_data=inputs
|
||||
step_execution.id, status=AgentStatus.RUNNING, started_at=datetime.now(timezone.utc), input_data=inputs
|
||||
)
|
||||
|
||||
# Execute the step based on type
|
||||
@@ -357,7 +357,7 @@ class AIAgentOrchestrator:
|
||||
await self.state_manager.update_step_execution(
|
||||
step_execution.id,
|
||||
status=AgentStatus.COMPLETED,
|
||||
completed_at=datetime.now(datetime.UTC),
|
||||
completed_at=datetime.now(timezone.utc),
|
||||
output_data=result.get("output"),
|
||||
execution_time=result.get("execution_time", 0.0),
|
||||
gpu_accelerated=result.get("gpu_accelerated", False),
|
||||
@@ -379,7 +379,7 @@ class AIAgentOrchestrator:
|
||||
except Exception as e:
|
||||
# Mark step as failed
|
||||
await self.state_manager.update_step_execution(
|
||||
step_execution.id, status=AgentStatus.FAILED, completed_at=datetime.now(datetime.UTC), error_message=str(e)
|
||||
step_execution.id, status=AgentStatus.FAILED, completed_at=datetime.now(timezone.utc), error_message=str(e)
|
||||
)
|
||||
raise
|
||||
|
||||
@@ -393,12 +393,12 @@ class AIAgentOrchestrator:
|
||||
4. Output postprocessing
|
||||
Currently using simulated inference for testing purposes.
|
||||
"""
|
||||
start_time = datetime.now(datetime.UTC)
|
||||
start_time = datetime.now(timezone.utc)
|
||||
|
||||
# Simulate processing time
|
||||
await asyncio.sleep(0.1)
|
||||
|
||||
execution_time = (datetime.now(datetime.UTC) - start_time).total_seconds()
|
||||
execution_time = (datetime.now(timezone.utc) - start_time).total_seconds()
|
||||
|
||||
return {
|
||||
"output": {"prediction": "simulated_result", "confidence": 0.95},
|
||||
@@ -417,12 +417,12 @@ class AIAgentOrchestrator:
|
||||
4. Model checkpointing and validation
|
||||
Currently using simulated training for testing purposes.
|
||||
"""
|
||||
start_time = datetime.now(datetime.UTC)
|
||||
start_time = datetime.now(timezone.utc)
|
||||
|
||||
# Simulate training time
|
||||
await asyncio.sleep(0.5)
|
||||
|
||||
execution_time = (datetime.now(datetime.UTC) - start_time).total_seconds()
|
||||
execution_time = (datetime.now(timezone.utc) - start_time).total_seconds()
|
||||
|
||||
return {
|
||||
"output": {"model_updated": True, "training_loss": 0.123},
|
||||
@@ -434,12 +434,12 @@ class AIAgentOrchestrator:
|
||||
async def _execute_data_processing_step(self, step: AgentStep, inputs: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Execute data processing step"""
|
||||
|
||||
start_time = datetime.now(datetime.UTC)
|
||||
start_time = datetime.now(timezone.utc)
|
||||
|
||||
# Simulate processing time
|
||||
await asyncio.sleep(0.05)
|
||||
|
||||
execution_time = (datetime.now(datetime.UTC) - start_time).total_seconds()
|
||||
execution_time = (datetime.now(timezone.utc) - start_time).total_seconds()
|
||||
|
||||
return {
|
||||
"output": {"processed_records": 1000, "data_validated": True},
|
||||
@@ -451,12 +451,12 @@ class AIAgentOrchestrator:
|
||||
async def _execute_custom_step(self, step: AgentStep, inputs: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Execute custom step"""
|
||||
|
||||
start_time = datetime.now(datetime.UTC)
|
||||
start_time = datetime.now(timezone.utc)
|
||||
|
||||
# Simulate custom processing
|
||||
await asyncio.sleep(0.2)
|
||||
|
||||
execution_time = (datetime.now(datetime.UTC) - start_time).total_seconds()
|
||||
execution_time = (datetime.now(timezone.utc) - start_time).total_seconds()
|
||||
|
||||
return {
|
||||
"output": {"custom_result": "completed", "metadata": inputs},
|
||||
@@ -494,7 +494,7 @@ class AIAgentOrchestrator:
|
||||
async def _complete_execution(self, execution_id: str, step_results: dict[str, Any]) -> None:
|
||||
"""Mark execution as completed"""
|
||||
|
||||
completed_at = datetime.now(datetime.UTC)
|
||||
completed_at = datetime.now(timezone.utc)
|
||||
execution = await self.state_manager.get_execution(execution_id)
|
||||
|
||||
total_execution_time = (completed_at - execution.started_at).total_seconds() if execution.started_at else 0.0
|
||||
@@ -511,7 +511,7 @@ class AIAgentOrchestrator:
|
||||
"""Handle execution failure"""
|
||||
|
||||
await self.state_manager.update_execution_status(
|
||||
execution_id, status=AgentStatus.FAILED, completed_at=datetime.now(datetime.UTC), error_message=str(error)
|
||||
execution_id, status=AgentStatus.FAILED, completed_at=datetime.now(timezone.utc), error_message=str(error)
|
||||
)
|
||||
|
||||
def _estimate_completion(self, execution: AgentExecution) -> datetime | None:
|
||||
|
||||
@@ -11,7 +11,7 @@ logger = get_logger(__name__)
|
||||
import hashlib
|
||||
import json
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
|
||||
@@ -113,7 +113,7 @@ class ServiceRequest:
|
||||
payment: float = 0.0
|
||||
rating: int = 0
|
||||
review: str = ""
|
||||
created_at: datetime = field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
results_hash: str | None = None
|
||||
priority: str = "normal" # low, normal, high, urgent
|
||||
complexity: str = "medium" # simple, medium, complex
|
||||
@@ -265,8 +265,8 @@ class AgentServiceMarketplace:
|
||||
completed_jobs=0,
|
||||
average_rating=0.0,
|
||||
rating_count=0,
|
||||
listed_at=datetime.now(datetime.UTC),
|
||||
last_updated=datetime.now(datetime.UTC),
|
||||
listed_at=datetime.now(timezone.utc),
|
||||
last_updated=datetime.now(timezone.utc),
|
||||
tags=tags,
|
||||
capabilities=capabilities,
|
||||
requirements=requirements,
|
||||
@@ -332,10 +332,10 @@ class AgentServiceMarketplace:
|
||||
if budget < service.base_price:
|
||||
raise ValueError(f"Budget below service price: {service.base_price}")
|
||||
|
||||
if deadline <= datetime.now(datetime.UTC):
|
||||
if deadline <= datetime.now(timezone.utc):
|
||||
raise ValueError("Invalid deadline")
|
||||
|
||||
if deadline > datetime.now(datetime.UTC) + timedelta(days=365):
|
||||
if deadline > datetime.now(timezone.utc) + timedelta(days=365):
|
||||
raise ValueError("Deadline too far in future")
|
||||
|
||||
# Generate request ID
|
||||
@@ -390,13 +390,13 @@ class AgentServiceMarketplace:
|
||||
if service.agent_id != agent_id:
|
||||
raise ValueError("Not service provider")
|
||||
|
||||
if datetime.now(datetime.UTC) > request.deadline:
|
||||
if datetime.now(timezone.utc) > request.deadline:
|
||||
raise ValueError("Request expired")
|
||||
|
||||
# Update request
|
||||
request.status = RequestStatus.ACCEPTED
|
||||
request.assigned_agent = agent_id
|
||||
request.accepted_at = datetime.now(datetime.UTC)
|
||||
request.accepted_at = datetime.now(timezone.utc)
|
||||
|
||||
# Calculate dynamic price
|
||||
final_price = await self._calculate_dynamic_price(request.service_id, request.budget)
|
||||
@@ -425,12 +425,12 @@ class AgentServiceMarketplace:
|
||||
if request.assigned_agent != agent_id:
|
||||
raise ValueError("Not assigned agent")
|
||||
|
||||
if datetime.now(datetime.UTC) > request.deadline:
|
||||
if datetime.now(timezone.utc) > request.deadline:
|
||||
raise ValueError("Request expired")
|
||||
|
||||
# Update request
|
||||
request.status = RequestStatus.COMPLETED
|
||||
request.completed_at = datetime.now(datetime.UTC)
|
||||
request.completed_at = datetime.now(timezone.utc)
|
||||
request.results_hash = hashlib.sha256(json.dumps(results, sort_keys=True).encode()).hexdigest()
|
||||
|
||||
# Calculate payment
|
||||
@@ -441,7 +441,7 @@ class AgentServiceMarketplace:
|
||||
# Update service stats
|
||||
service.total_earnings += agent_payment
|
||||
service.completed_jobs += 1
|
||||
service.last_updated = datetime.now(datetime.UTC)
|
||||
service.last_updated = datetime.now(timezone.utc)
|
||||
|
||||
# Update category
|
||||
if service.service_type.value in self.categories:
|
||||
@@ -479,7 +479,7 @@ class AgentServiceMarketplace:
|
||||
if rating < 1 or rating > 5:
|
||||
raise ValueError("Invalid rating")
|
||||
|
||||
if datetime.now(datetime.UTC) > request.deadline + timedelta(days=30):
|
||||
if datetime.now(timezone.utc) > request.deadline + timedelta(days=30):
|
||||
raise ValueError("Rating period expired")
|
||||
|
||||
# Update request
|
||||
@@ -539,7 +539,7 @@ class AgentServiceMarketplace:
|
||||
total_earnings=0.0,
|
||||
reputation=founder_reputation,
|
||||
status=GuildStatus.ACTIVE,
|
||||
created_at=datetime.now(datetime.UTC),
|
||||
created_at=datetime.now(timezone.utc),
|
||||
requirements=requirements,
|
||||
benefits=benefits,
|
||||
guild_rules=guild_rules,
|
||||
@@ -547,7 +547,7 @@ class AgentServiceMarketplace:
|
||||
|
||||
# Add founder as member
|
||||
guild.members[founder_id] = {
|
||||
"joined_at": datetime.now(datetime.UTC),
|
||||
"joined_at": datetime.now(timezone.utc),
|
||||
"reputation": founder_reputation,
|
||||
"role": "founder",
|
||||
"contributions": 0,
|
||||
@@ -592,7 +592,7 @@ class AgentServiceMarketplace:
|
||||
|
||||
# Add member
|
||||
guild.members[agent_id] = {
|
||||
"joined_at": datetime.now(datetime.UTC),
|
||||
"joined_at": datetime.now(timezone.utc),
|
||||
"reputation": agent_reputation,
|
||||
"role": "member",
|
||||
"contributions": 0,
|
||||
@@ -842,7 +842,7 @@ class AgentServiceMarketplace:
|
||||
|
||||
while True:
|
||||
try:
|
||||
current_time = datetime.now(datetime.UTC)
|
||||
current_time = datetime.now(timezone.utc)
|
||||
|
||||
for request in self.service_requests.values():
|
||||
if request.status == RequestStatus.PENDING and current_time > request.deadline:
|
||||
|
||||
@@ -8,7 +8,7 @@ import asyncio
|
||||
import random
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ Provides liquidity pool management, token swapping, and dynamic fee adjustment.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
|
||||
from aitbc import get_logger
|
||||
from fastapi import HTTPException
|
||||
@@ -83,7 +83,7 @@ class AMMService:
|
||||
reserve_a=0.0,
|
||||
reserve_b=0.0,
|
||||
is_active=True,
|
||||
created_at=datetime.now(datetime.UTC),
|
||||
created_at=datetime.now(timezone.utc),
|
||||
created_by=creator_address,
|
||||
)
|
||||
|
||||
@@ -138,7 +138,7 @@ class AMMService:
|
||||
pool.reserve_a += liquidity_request.amount_a
|
||||
pool.reserve_b += liquidity_request.amount_b
|
||||
pool.total_liquidity += liquidity_result.liquidity_received
|
||||
pool.updated_at = datetime.now(datetime.UTC)
|
||||
pool.updated_at = datetime.now(timezone.utc)
|
||||
|
||||
# Update or create liquidity position
|
||||
position = self.session.execute(
|
||||
@@ -150,15 +150,15 @@ class AMMService:
|
||||
if position:
|
||||
position.liquidity_amount += liquidity_result.liquidity_received
|
||||
position.shares_owned = (position.liquidity_amount / pool.total_liquidity) * 100
|
||||
position.last_deposit = datetime.now(datetime.UTC)
|
||||
position.last_deposit = datetime.now(timezone.utc)
|
||||
else:
|
||||
position = LiquidityPosition(
|
||||
pool_id=pool.id,
|
||||
provider_address=provider_address,
|
||||
liquidity_amount=liquidity_result.liquidity_received,
|
||||
shares_owned=(liquidity_result.liquidity_received / pool.total_liquidity) * 100,
|
||||
last_deposit=datetime.now(datetime.UTC),
|
||||
created_at=datetime.now(datetime.UTC),
|
||||
last_deposit=datetime.now(timezone.utc),
|
||||
created_at=datetime.now(timezone.utc),
|
||||
)
|
||||
self.session.add(position)
|
||||
|
||||
@@ -213,12 +213,12 @@ class AMMService:
|
||||
pool.reserve_a -= removal_result.amount_a
|
||||
pool.reserve_b -= removal_result.amount_b
|
||||
pool.total_liquidity -= liquidity_request.liquidity_amount
|
||||
pool.updated_at = datetime.now(datetime.UTC)
|
||||
pool.updated_at = datetime.now(timezone.utc)
|
||||
|
||||
# Update liquidity position
|
||||
position.liquidity_amount -= liquidity_request.liquidity_amount
|
||||
position.shares_owned = (position.liquidity_amount / pool.total_liquidity) * 100 if pool.total_liquidity > 0 else 0
|
||||
position.last_withdrawal = datetime.now(datetime.UTC)
|
||||
position.last_withdrawal = datetime.now(timezone.utc)
|
||||
|
||||
# Remove position if empty
|
||||
if position.liquidity_amount == 0:
|
||||
@@ -285,7 +285,7 @@ class AMMService:
|
||||
pool.reserve_b += swap_request.amount_in
|
||||
pool.reserve_a -= swap_result.amount_out
|
||||
|
||||
pool.updated_at = datetime.now(datetime.UTC)
|
||||
pool.updated_at = datetime.now(timezone.utc)
|
||||
|
||||
# Record swap transaction
|
||||
swap_transaction = SwapTransaction(
|
||||
@@ -298,7 +298,7 @@ class AMMService:
|
||||
price=swap_result.price,
|
||||
fee_amount=swap_result.fee_amount,
|
||||
transaction_hash=swap_result.transaction_hash,
|
||||
executed_at=datetime.now(datetime.UTC),
|
||||
executed_at=datetime.now(timezone.utc),
|
||||
)
|
||||
|
||||
self.session.add(swap_transaction)
|
||||
@@ -339,7 +339,7 @@ class AMMService:
|
||||
|
||||
# Update pool in database
|
||||
pool.fee_percentage = new_fee
|
||||
pool.updated_at = datetime.now(datetime.UTC)
|
||||
pool.updated_at = datetime.now(timezone.utc)
|
||||
self.session.commit()
|
||||
|
||||
# Create fee structure response
|
||||
@@ -348,7 +348,7 @@ class AMMService:
|
||||
base_fee_percentage=base_fee,
|
||||
current_fee_percentage=new_fee,
|
||||
volatility_adjustment=volatility_multiplier - 1.0,
|
||||
adjusted_at=datetime.now(datetime.UTC),
|
||||
adjusted_at=datetime.now(timezone.utc),
|
||||
)
|
||||
|
||||
logger.info(f"Adjusted fee for pool {pool_id} to {new_fee:.3f}%")
|
||||
@@ -384,7 +384,7 @@ class AMMService:
|
||||
if existing_program:
|
||||
existing_program.daily_reward_amount = daily_reward
|
||||
existing_program.incentive_multiplier = incentive_multiplier
|
||||
existing_program.updated_at = datetime.now(datetime.UTC)
|
||||
existing_program.updated_at = datetime.now(timezone.utc)
|
||||
program = existing_program
|
||||
else:
|
||||
program = IncentiveProgram(
|
||||
@@ -393,7 +393,7 @@ class AMMService:
|
||||
incentive_multiplier=incentive_multiplier,
|
||||
duration_days=self.incentive_duration_days,
|
||||
is_active=True,
|
||||
created_at=datetime.now(datetime.UTC),
|
||||
created_at=datetime.now(timezone.utc),
|
||||
)
|
||||
self.session.add(program)
|
||||
|
||||
@@ -511,7 +511,7 @@ class AMMService:
|
||||
return ValidationResult(is_valid=False, error_message="Insufficient liquidity in pool")
|
||||
|
||||
# Check deadline
|
||||
if datetime.now(datetime.UTC) > swap_request.deadline:
|
||||
if datetime.now(timezone.utc) > swap_request.deadline:
|
||||
return ValidationResult(is_valid=False, error_message="Transaction deadline expired")
|
||||
|
||||
# Check minimum amount
|
||||
@@ -562,7 +562,7 @@ class AMMService:
|
||||
total_value_locked=0.0,
|
||||
apr=0.0,
|
||||
utilization_rate=0.0,
|
||||
updated_at=datetime.now(datetime.UTC),
|
||||
updated_at=datetime.now(timezone.utc),
|
||||
)
|
||||
|
||||
self.session.add(metrics)
|
||||
@@ -601,7 +601,7 @@ class AMMService:
|
||||
metrics.total_value_locked = tvl
|
||||
metrics.apr = apr
|
||||
metrics.utilization_rate = utilization_rate
|
||||
metrics.updated_at = datetime.now(datetime.UTC)
|
||||
metrics.updated_at = datetime.now(timezone.utc)
|
||||
|
||||
self.session.commit()
|
||||
|
||||
@@ -615,7 +615,7 @@ class AMMService:
|
||||
metrics = self.session.execute(select(PoolMetrics).where(PoolMetrics.pool_id == pool.id)).first()
|
||||
|
||||
# Calculate 24h volume and fees
|
||||
twenty_four_hours_ago = datetime.now(datetime.UTC) - timedelta(hours=24)
|
||||
twenty_four_hours_ago = datetime.now(timezone.utc) - timedelta(hours=24)
|
||||
|
||||
recent_swaps = self.session.execute(
|
||||
select(SwapTransaction).where(
|
||||
|
||||
@@ -3,7 +3,7 @@ Marketplace Analytics Service
|
||||
Implements comprehensive analytics, insights, and reporting for the marketplace
|
||||
"""
|
||||
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
@@ -119,7 +119,7 @@ class DataCollector:
|
||||
change_percentage=change_percentage,
|
||||
unit="AITBC",
|
||||
category="financial",
|
||||
recorded_at=datetime.now(datetime.UTC),
|
||||
recorded_at=datetime.now(timezone.utc),
|
||||
period_start=start_time,
|
||||
period_end=end_time,
|
||||
breakdown={
|
||||
@@ -166,7 +166,7 @@ class DataCollector:
|
||||
change_percentage=change_percentage,
|
||||
unit="agents",
|
||||
category="agents",
|
||||
recorded_at=datetime.now(datetime.UTC),
|
||||
recorded_at=datetime.now(timezone.utc),
|
||||
period_start=start_time,
|
||||
period_end=end_time,
|
||||
breakdown={
|
||||
@@ -216,7 +216,7 @@ class DataCollector:
|
||||
change_percentage=change_percentage,
|
||||
unit="AITBC",
|
||||
category="pricing",
|
||||
recorded_at=datetime.now(datetime.UTC),
|
||||
recorded_at=datetime.now(timezone.utc),
|
||||
period_start=start_time,
|
||||
period_end=end_time,
|
||||
breakdown={
|
||||
@@ -267,7 +267,7 @@ class DataCollector:
|
||||
change_percentage=change_percentage,
|
||||
unit="%",
|
||||
category="performance",
|
||||
recorded_at=datetime.now(datetime.UTC),
|
||||
recorded_at=datetime.now(timezone.utc),
|
||||
period_start=start_time,
|
||||
period_end=end_time,
|
||||
breakdown={
|
||||
@@ -318,7 +318,7 @@ class DataCollector:
|
||||
change_percentage=change_percentage,
|
||||
unit="ratio",
|
||||
category="market",
|
||||
recorded_at=datetime.now(datetime.UTC),
|
||||
recorded_at=datetime.now(timezone.utc),
|
||||
period_start=start_time,
|
||||
period_end=end_time,
|
||||
breakdown={
|
||||
@@ -823,7 +823,7 @@ class MarketplaceAnalytics:
|
||||
"""Collect comprehensive market data"""
|
||||
|
||||
# Calculate time range
|
||||
end_time = datetime.now(datetime.UTC)
|
||||
end_time = datetime.now(timezone.utc)
|
||||
|
||||
if period_type == AnalyticsPeriod.DAILY:
|
||||
start_time = end_time - timedelta(days=1)
|
||||
@@ -863,7 +863,7 @@ class MarketplaceAnalytics:
|
||||
period_type = period_map.get(time_period, AnalyticsPeriod.DAILY)
|
||||
|
||||
# Calculate time range
|
||||
end_time = datetime.now(datetime.UTC)
|
||||
end_time = datetime.now(timezone.utc)
|
||||
|
||||
if period_type == AnalyticsPeriod.DAILY:
|
||||
start_time = end_time - timedelta(days=1)
|
||||
@@ -925,7 +925,7 @@ class MarketplaceAnalytics:
|
||||
"""Get comprehensive market overview"""
|
||||
|
||||
# Get latest daily metrics
|
||||
end_time = datetime.now(datetime.UTC)
|
||||
end_time = datetime.now(timezone.utc)
|
||||
start_time = end_time - timedelta(days=1)
|
||||
|
||||
metrics = self.session.execute(
|
||||
@@ -957,7 +957,7 @@ class MarketplaceAnalytics:
|
||||
).all()
|
||||
|
||||
return {
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"period": "last_24_hours",
|
||||
"metrics": {
|
||||
metric.metric_name: {
|
||||
|
||||
@@ -8,7 +8,7 @@ from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import secrets
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
|
||||
from aitbc import get_logger
|
||||
from fastapi import HTTPException
|
||||
@@ -44,7 +44,7 @@ class AtomicSwapService:
|
||||
# Standard HTLC uses SHA256 of the secret
|
||||
hashlock = "0x" + hashlib.sha256(secret.encode()).hexdigest()
|
||||
|
||||
now = datetime.now(datetime.UTC)
|
||||
now = datetime.now(timezone.utc)
|
||||
source_timelock = int((now + timedelta(hours=request.source_timelock_hours)).timestamp())
|
||||
target_timelock = int((now + timedelta(hours=request.target_timelock_hours)).timestamp())
|
||||
|
||||
@@ -97,7 +97,7 @@ class AtomicSwapService:
|
||||
|
||||
order.status = SwapStatus.INITIATED
|
||||
order.source_initiate_tx = request.tx_hash
|
||||
order.updated_at = datetime.now(datetime.UTC)
|
||||
order.updated_at = datetime.now(timezone.utc)
|
||||
|
||||
self.session.commit()
|
||||
self.session.refresh(order)
|
||||
@@ -116,7 +116,7 @@ class AtomicSwapService:
|
||||
|
||||
order.status = SwapStatus.PARTICIPATING
|
||||
order.target_participate_tx = request.tx_hash
|
||||
order.updated_at = datetime.now(datetime.UTC)
|
||||
order.updated_at = datetime.now(timezone.utc)
|
||||
|
||||
self.session.commit()
|
||||
self.session.refresh(order)
|
||||
@@ -141,7 +141,7 @@ class AtomicSwapService:
|
||||
order.status = SwapStatus.COMPLETED
|
||||
order.target_complete_tx = request.tx_hash
|
||||
# Secret is now publicly known on the blockchain
|
||||
order.updated_at = datetime.now(datetime.UTC)
|
||||
order.updated_at = datetime.now(timezone.utc)
|
||||
|
||||
self.session.commit()
|
||||
self.session.refresh(order)
|
||||
@@ -155,7 +155,7 @@ class AtomicSwapService:
|
||||
if not order:
|
||||
raise HTTPException(status_code=404, detail="Swap order not found")
|
||||
|
||||
now = int(datetime.now(datetime.UTC).timestamp())
|
||||
now = int(datetime.now(timezone.utc).timestamp())
|
||||
|
||||
if order.status == SwapStatus.INITIATED and now < order.source_timelock:
|
||||
raise HTTPException(status_code=400, detail="Source timelock has not expired yet")
|
||||
@@ -165,7 +165,7 @@ class AtomicSwapService:
|
||||
|
||||
order.status = SwapStatus.REFUNDED
|
||||
order.refund_tx = request.tx_hash
|
||||
order.updated_at = datetime.now(datetime.UTC)
|
||||
order.updated_at = datetime.now(timezone.utc)
|
||||
|
||||
self.session.commit()
|
||||
self.session.refresh(order)
|
||||
|
||||
@@ -8,7 +8,7 @@ import hashlib
|
||||
import json
|
||||
import os
|
||||
from dataclasses import asdict, dataclass
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
@@ -95,7 +95,7 @@ class AuditLogger:
|
||||
"""Log access to confidential data (synchronous for tests)."""
|
||||
event = AuditEvent(
|
||||
event_id=self._generate_event_id(),
|
||||
timestamp=datetime.now(datetime.UTC),
|
||||
timestamp=datetime.now(timezone.utc),
|
||||
event_type="access",
|
||||
participant_id=participant_id,
|
||||
transaction_id=transaction_id,
|
||||
@@ -127,7 +127,7 @@ class AuditLogger:
|
||||
"""Log key management operations (synchronous for tests)."""
|
||||
event = AuditEvent(
|
||||
event_id=self._generate_event_id(),
|
||||
timestamp=datetime.now(datetime.UTC),
|
||||
timestamp=datetime.now(timezone.utc),
|
||||
event_type="key_operation",
|
||||
participant_id=participant_id,
|
||||
transaction_id=None,
|
||||
@@ -165,7 +165,7 @@ class AuditLogger:
|
||||
"""Log access policy changes"""
|
||||
event = AuditEvent(
|
||||
event_id=self._generate_event_id(),
|
||||
timestamp=datetime.now(datetime.UTC),
|
||||
timestamp=datetime.now(timezone.utc),
|
||||
event_type="policy_change",
|
||||
participant_id=participant_id,
|
||||
transaction_id=None,
|
||||
@@ -262,7 +262,7 @@ class AuditLogger:
|
||||
def verify_integrity(self, start_date: datetime | None = None) -> dict[str, Any]:
|
||||
"""Verify integrity of audit logs"""
|
||||
if start_date is None:
|
||||
start_date = datetime.now(datetime.UTC) - timedelta(days=30)
|
||||
start_date = datetime.now(timezone.utc) - timedelta(days=30)
|
||||
|
||||
results = {
|
||||
"verified_files": 0,
|
||||
@@ -316,7 +316,7 @@ class AuditLogger:
|
||||
"start_time": start_time.isoformat(),
|
||||
"end_time": end_time.isoformat(),
|
||||
"event_count": len(events),
|
||||
"exported_at": datetime.now(datetime.UTC).isoformat(),
|
||||
"exported_at": datetime.now(timezone.utc).isoformat(),
|
||||
"include_signatures": include_signatures,
|
||||
},
|
||||
"events": [],
|
||||
@@ -429,7 +429,7 @@ class AuditLogger:
|
||||
|
||||
def _rotate_if_needed(self):
|
||||
"""Rotate log file if needed"""
|
||||
now = datetime.now(datetime.UTC)
|
||||
now = datetime.now(timezone.utc)
|
||||
today = now.date()
|
||||
|
||||
# Check if we need a new file
|
||||
@@ -449,7 +449,7 @@ class AuditLogger:
|
||||
# Write header with metadata
|
||||
if not self.current_file.exists():
|
||||
header = {
|
||||
"created_at": datetime.now(datetime.UTC).isoformat(),
|
||||
"created_at": datetime.now(timezone.utc).isoformat(),
|
||||
"version": "1.0",
|
||||
"format": "jsonl",
|
||||
"previous_hash": self.chain_hash,
|
||||
@@ -460,7 +460,7 @@ class AuditLogger:
|
||||
|
||||
def _generate_event_id(self) -> str:
|
||||
"""Generate unique event ID"""
|
||||
return f"evt_{datetime.now(datetime.UTC).timestamp()}_{os.urandom(4).hex()}"
|
||||
return f"evt_{datetime.now(timezone.utc).timestamp()}_{os.urandom(4).hex()}"
|
||||
|
||||
def _sign_event(self, event: AuditEvent) -> str:
|
||||
"""Sign event for tamper-evidence"""
|
||||
|
||||
@@ -9,7 +9,7 @@ from aitbc import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
from dataclasses import asdict, dataclass
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
|
||||
@@ -206,7 +206,7 @@ class BidStrategyEngine:
|
||||
"urgency_preference": preferences.get("urgency_preference", 0.5),
|
||||
"max_wait_time": preferences.get("max_wait_time", 3600), # 1 hour
|
||||
"min_success_probability": preferences.get("min_success_probability", 0.7),
|
||||
"updated_at": datetime.now(datetime.UTC).isoformat(),
|
||||
"updated_at": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
logger.info(f"Updated preferences for agent {agent_id}")
|
||||
@@ -231,7 +231,7 @@ class BidStrategyEngine:
|
||||
"volatility_trend": volatility_trend,
|
||||
"future_prediction": asdict(future_conditions),
|
||||
"recommendations": await self._generate_market_recommendations(market_conditions),
|
||||
"analysis_timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"analysis_timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
async def _select_optimal_strategy(
|
||||
@@ -330,7 +330,7 @@ class BidStrategyEngine:
|
||||
# Time factor (urgency based on deadline)
|
||||
time_factor = 1.0
|
||||
if task_requirements.deadline:
|
||||
time_remaining = (task_requirements.deadline - datetime.now(datetime.UTC)).total_seconds() / 3600
|
||||
time_remaining = (task_requirements.deadline - datetime.now(timezone.utc)).total_seconds() / 3600
|
||||
if time_remaining < 2: # Less than 2 hours
|
||||
time_factor = 1.5
|
||||
elif time_remaining < 6: # Less than 6 hours
|
||||
@@ -418,7 +418,7 @@ class BidStrategyEngine:
|
||||
# Time factor
|
||||
time_factor = 1.0
|
||||
if task_requirements.deadline:
|
||||
time_remaining = (task_requirements.deadline - datetime.now(datetime.UTC)).total_seconds() / 3600
|
||||
time_remaining = (task_requirements.deadline - datetime.now(timezone.utc)).total_seconds() / 3600
|
||||
if time_remaining < 2:
|
||||
time_factor = 0.7
|
||||
elif time_remaining < 6:
|
||||
@@ -579,7 +579,7 @@ class BidStrategyEngine:
|
||||
price_volatility=0.12,
|
||||
demand_level=0.68,
|
||||
supply_level=0.72,
|
||||
timestamp=datetime.now(datetime.UTC),
|
||||
timestamp=datetime.now(timezone.utc),
|
||||
)
|
||||
|
||||
async def _load_market_history(self):
|
||||
@@ -706,7 +706,7 @@ class BidStrategyEngine:
|
||||
price_volatility=current.price_volatility,
|
||||
demand_level=current.demand_level,
|
||||
supply_level=current.supply_level,
|
||||
timestamp=datetime.now(datetime.UTC) + timedelta(hours=hours_ahead),
|
||||
timestamp=datetime.now(timezone.utc) + timedelta(hours=hours_ahead),
|
||||
)
|
||||
|
||||
# Apply trend adjustments
|
||||
|
||||
@@ -3,7 +3,7 @@ Bounty Management Service
|
||||
Business logic for AI agent bounty system with ZK-proof verification
|
||||
"""
|
||||
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import and_, func, or_, select
|
||||
@@ -175,7 +175,7 @@ class BountyService:
|
||||
if bounty.status != BountyStatus.ACTIVE:
|
||||
raise ValueError("Bounty is not active")
|
||||
|
||||
if datetime.now(datetime.UTC) > bounty.deadline:
|
||||
if datetime.now(timezone.utc) > bounty.deadline:
|
||||
raise ValueError("Bounty deadline has passed")
|
||||
|
||||
if bounty.submission_count >= bounty.max_submissions:
|
||||
@@ -257,7 +257,7 @@ class BountyService:
|
||||
|
||||
# Update submission
|
||||
submission.status = SubmissionStatus.VERIFIED if verified else SubmissionStatus.REJECTED
|
||||
submission.verification_time = datetime.now(datetime.UTC)
|
||||
submission.verification_time = datetime.now(timezone.utc)
|
||||
submission.verifier_address = verifier_address
|
||||
|
||||
# If verified, check if it meets bounty requirements
|
||||
@@ -297,13 +297,13 @@ class BountyService:
|
||||
if submission.status != SubmissionStatus.VERIFIED:
|
||||
raise ValueError("Can only dispute verified submissions")
|
||||
|
||||
if datetime.now(datetime.UTC) - submission.verification_time > timedelta(days=1):
|
||||
if datetime.now(timezone.utc) - submission.verification_time > timedelta(days=1):
|
||||
raise ValueError("Dispute window expired")
|
||||
|
||||
# Update submission
|
||||
submission.status = SubmissionStatus.DISPUTED
|
||||
submission.dispute_reason = dispute_reason
|
||||
submission.dispute_time = datetime.now(datetime.UTC)
|
||||
submission.dispute_time = datetime.now(timezone.utc)
|
||||
|
||||
# Update bounty status
|
||||
bounty = await self.get_bounty(bounty_id)
|
||||
@@ -369,13 +369,13 @@ class BountyService:
|
||||
try:
|
||||
# Calculate time period
|
||||
if period == "daily":
|
||||
start_date = datetime.now(datetime.UTC) - timedelta(days=1)
|
||||
start_date = datetime.now(timezone.utc) - timedelta(days=1)
|
||||
elif period == "weekly":
|
||||
start_date = datetime.now(datetime.UTC) - timedelta(weeks=1)
|
||||
start_date = datetime.now(timezone.utc) - timedelta(weeks=1)
|
||||
elif period == "monthly":
|
||||
start_date = datetime.now(datetime.UTC) - timedelta(days=30)
|
||||
start_date = datetime.now(timezone.utc) - timedelta(days=30)
|
||||
else:
|
||||
start_date = datetime.now(datetime.UTC) - timedelta(weeks=1)
|
||||
start_date = datetime.now(timezone.utc) - timedelta(weeks=1)
|
||||
|
||||
# Get top performers
|
||||
stmt = (
|
||||
@@ -419,13 +419,13 @@ class BountyService:
|
||||
try:
|
||||
# Calculate time period
|
||||
if period == "daily":
|
||||
start_date = datetime.now(datetime.UTC) - timedelta(days=1)
|
||||
start_date = datetime.now(timezone.utc) - timedelta(days=1)
|
||||
elif period == "weekly":
|
||||
start_date = datetime.now(datetime.UTC) - timedelta(weeks=1)
|
||||
start_date = datetime.now(timezone.utc) - timedelta(weeks=1)
|
||||
elif period == "monthly":
|
||||
start_date = datetime.now(datetime.UTC) - timedelta(days=30)
|
||||
start_date = datetime.now(timezone.utc) - timedelta(days=30)
|
||||
else:
|
||||
start_date = datetime.now(datetime.UTC) - timedelta(days=30)
|
||||
start_date = datetime.now(timezone.utc) - timedelta(days=30)
|
||||
|
||||
# Get statistics
|
||||
total_stmt = select(func.count(Bounty.bounty_id)).where(Bounty.creation_time >= start_date)
|
||||
@@ -484,7 +484,7 @@ class BountyService:
|
||||
|
||||
stats = BountyStats(
|
||||
period_start=start_date,
|
||||
period_end=datetime.now(datetime.UTC),
|
||||
period_end=datetime.now(timezone.utc),
|
||||
period_type=period,
|
||||
total_bounties=total_bounties,
|
||||
active_bounties=active_bounties,
|
||||
@@ -570,7 +570,7 @@ class BountyService:
|
||||
if bounty.status != BountyStatus.ACTIVE:
|
||||
raise ValueError("Bounty is not active")
|
||||
|
||||
if datetime.now(datetime.UTC) <= bounty.deadline:
|
||||
if datetime.now(timezone.utc) <= bounty.deadline:
|
||||
raise ValueError("Deadline has not passed")
|
||||
|
||||
bounty.status = BountyStatus.EXPIRED
|
||||
|
||||
@@ -5,7 +5,7 @@ Implements certification framework, partnership programs, and badge system
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
@@ -111,7 +111,7 @@ class CertificationSystem:
|
||||
certification_id = f"cert_{uuid4().hex[:8]}"
|
||||
verification_hash = self.generate_verification_hash(agent_id, level, certification_id)
|
||||
|
||||
expires_at = datetime.now(datetime.UTC) + timedelta(days=level_config["validity_days"])
|
||||
expires_at = datetime.now(timezone.utc) + timedelta(days=level_config["validity_days"])
|
||||
|
||||
certification = AgentCertification(
|
||||
certification_id=certification_id,
|
||||
@@ -130,7 +130,7 @@ class CertificationSystem:
|
||||
audit_log=[
|
||||
{
|
||||
"action": "issued",
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"performed_by": issued_by,
|
||||
"details": f"Certification issued at {level.value} level",
|
||||
}
|
||||
@@ -200,7 +200,7 @@ class CertificationSystem:
|
||||
AgentCertification.agent_id == agent_id,
|
||||
AgentCertification.certification_level == target_level,
|
||||
AgentCertification.status == CertificationStatus.ACTIVE,
|
||||
AgentCertification.expires_at > datetime.now(datetime.UTC),
|
||||
AgentCertification.expires_at > datetime.now(timezone.utc),
|
||||
)
|
||||
)
|
||||
).first()
|
||||
@@ -512,7 +512,7 @@ class CertificationSystem:
|
||||
"agent_id": agent_id,
|
||||
"level": level.value,
|
||||
"certification_id": certification_id,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"nonce": uuid4().hex,
|
||||
}
|
||||
|
||||
@@ -567,9 +567,9 @@ class CertificationSystem:
|
||||
return False, f"Renewal requirements not met: {'; '.join(errors)}"
|
||||
|
||||
# Update certification
|
||||
certification.expires_at = datetime.now(datetime.UTC) + timedelta(days=level_config["validity_days"])
|
||||
certification.expires_at = datetime.now(timezone.utc) + timedelta(days=level_config["validity_days"])
|
||||
certification.renewal_count += 1
|
||||
certification.last_renewed_at = datetime.now(datetime.UTC)
|
||||
certification.last_renewed_at = datetime.now(timezone.utc)
|
||||
certification.verification_hash = self.generate_verification_hash(
|
||||
certification.agent_id, certification.certification_level, certification.certification_id
|
||||
)
|
||||
@@ -578,7 +578,7 @@ class CertificationSystem:
|
||||
certification.audit_log.append(
|
||||
{
|
||||
"action": "renewed",
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"performed_by": renewed_by,
|
||||
"details": f"Certification renewed for {level_config['validity_days']} days",
|
||||
}
|
||||
@@ -664,7 +664,7 @@ class PartnershipManager:
|
||||
commission_structure=kwargs.get("commission_structure", type_config.get("commission_structure", {})),
|
||||
performance_metrics=kwargs.get("performance_metrics", ["sales_volume", "customer_satisfaction"]),
|
||||
max_participants=kwargs.get("max_participants"),
|
||||
launched_at=datetime.now(datetime.UTC) if kwargs.get("launch_immediately", False) else None,
|
||||
launched_at=datetime.now(timezone.utc) if kwargs.get("launch_immediately", False) else None,
|
||||
)
|
||||
|
||||
session.add(program)
|
||||
@@ -714,7 +714,7 @@ class PartnershipManager:
|
||||
program_id=program_id,
|
||||
partnership_type=program.program_type,
|
||||
current_tier="basic",
|
||||
applied_at=datetime.now(datetime.UTC),
|
||||
applied_at=datetime.now(timezone.utc),
|
||||
status="pending_approval",
|
||||
partnership_metadata={"application_data": application_data, "eligibility_results": eligibility_results},
|
||||
)
|
||||
@@ -1101,7 +1101,7 @@ class BadgeSystem:
|
||||
display_properties=criteria.get("display_properties", {}),
|
||||
is_limited=criteria.get("is_limited", False),
|
||||
max_awards=criteria.get("max_awards"),
|
||||
available_from=datetime.now(datetime.UTC),
|
||||
available_from=datetime.now(timezone.utc),
|
||||
available_until=criteria.get("available_until"),
|
||||
)
|
||||
|
||||
@@ -1213,7 +1213,7 @@ class BadgeSystem:
|
||||
"context": {
|
||||
"badge_name": badge.badge_name,
|
||||
"badge_type": badge.badge_type.value,
|
||||
"verification_date": datetime.now(datetime.UTC).isoformat(),
|
||||
"verification_date": datetime.now(timezone.utc).isoformat(),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ Community and Developer Ecosystem Services
|
||||
Services for managing OpenClaw developer tools, SDKs, and third-party solutions
|
||||
"""
|
||||
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
from aitbc import get_logger
|
||||
@@ -49,7 +49,7 @@ class DeveloperEcosystemService:
|
||||
# Mocking SDK release data
|
||||
return {
|
||||
"latest_version": "v1.2.0",
|
||||
"release_date": datetime.now(datetime.UTC).isoformat(),
|
||||
"release_date": datetime.now(timezone.utc).isoformat(),
|
||||
"supported_languages": ["python", "typescript", "rust"],
|
||||
"download_urls": {"python": "pip install aitbc-agent-sdk", "typescript": "npm install @aitbc/agent-sdk"},
|
||||
"features": [
|
||||
@@ -106,7 +106,7 @@ class ThirdPartySolutionService:
|
||||
# Auto-publish if free, otherwise manual review required
|
||||
if solution.price_model == "free":
|
||||
solution.status = SolutionStatus.PUBLISHED
|
||||
solution.published_at = datetime.now(datetime.UTC)
|
||||
solution.published_at = datetime.now(timezone.utc)
|
||||
|
||||
self.session.add(solution)
|
||||
self.session.commit()
|
||||
@@ -278,7 +278,7 @@ class CommunityPlatformService:
|
||||
theme=data.get("theme", ""),
|
||||
sponsor=data.get("sponsor", "AITBC Foundation"),
|
||||
prize_pool=data.get("prize_pool", 0.0),
|
||||
registration_start=datetime.fromisoformat(data.get("registration_start", datetime.now(datetime.UTC).isoformat())),
|
||||
registration_start=datetime.fromisoformat(data.get("registration_start", datetime.now(timezone.utc).isoformat())),
|
||||
registration_end=datetime.fromisoformat(data.get("registration_end")),
|
||||
event_start=datetime.fromisoformat(data.get("event_start")),
|
||||
event_end=datetime.fromisoformat(data.get("event_end")),
|
||||
|
||||
@@ -4,7 +4,7 @@ GDPR, CCPA, SOC 2, and regulatory compliance automation
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
@@ -69,8 +69,8 @@ class ComplianceRule:
|
||||
requirements: dict[str, Any]
|
||||
validation_logic: str
|
||||
severity: str = "medium"
|
||||
created_at: datetime = field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -101,7 +101,7 @@ class ComplianceAudit:
|
||||
findings: list[dict[str, Any]]
|
||||
recommendations: list[str]
|
||||
auditor: str
|
||||
audit_date: datetime = field(default_factory=datetime.now(datetime.UTC))
|
||||
audit_date: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
next_review_date: datetime | None = None
|
||||
|
||||
|
||||
@@ -129,7 +129,7 @@ class GDPRCompliance:
|
||||
return False
|
||||
|
||||
# Check if consent has expired
|
||||
if consent.expires_at and datetime.now(datetime.UTC) > consent.expires_at:
|
||||
if consent.expires_at and datetime.now(timezone.utc) > consent.expires_at:
|
||||
return False
|
||||
|
||||
# Check if consent has been withdrawn
|
||||
@@ -165,11 +165,11 @@ class GDPRCompliance:
|
||||
consent_id = str(uuid4())
|
||||
|
||||
status = ConsentStatus.GRANTED if granted else ConsentStatus.DENIED
|
||||
granted_at = datetime.now(datetime.UTC) if granted else None
|
||||
granted_at = datetime.now(timezone.utc) if granted else None
|
||||
expires_at = None
|
||||
|
||||
if granted and expires_days:
|
||||
expires_at = datetime.now(datetime.UTC) + timedelta(days=expires_days)
|
||||
expires_at = datetime.now(timezone.utc) + timedelta(days=expires_days)
|
||||
|
||||
consent = ConsentRecord(
|
||||
consent_id=consent_id,
|
||||
@@ -198,7 +198,7 @@ class GDPRCompliance:
|
||||
for consent in consents:
|
||||
if consent.consent_id == consent_id:
|
||||
consent.status = ConsentStatus.WITHDRAWN
|
||||
consent.withdrawn_at = datetime.now(datetime.UTC)
|
||||
consent.withdrawn_at = datetime.now(timezone.utc)
|
||||
|
||||
self.logger.info(f"Consent withdrawn: {consent_id}")
|
||||
return True
|
||||
@@ -216,8 +216,8 @@ class GDPRCompliance:
|
||||
"user_id": user_id,
|
||||
"details": details,
|
||||
"status": "pending",
|
||||
"created_at": datetime.now(datetime.UTC),
|
||||
"due_date": datetime.now(datetime.UTC) + timedelta(days=30), # GDPR 30-day deadline
|
||||
"created_at": datetime.now(timezone.utc),
|
||||
"due_date": datetime.now(timezone.utc) + timedelta(days=30), # GDPR 30-day deadline
|
||||
}
|
||||
|
||||
self.data_subject_requests[request_id] = request_data
|
||||
@@ -267,8 +267,8 @@ class GDPRCompliance:
|
||||
"notification_id": notification_id,
|
||||
"breach_data": breach_data,
|
||||
"notification_required": await self.check_data_breach_notification(breach_data),
|
||||
"created_at": datetime.now(datetime.UTC),
|
||||
"deadline": datetime.now(datetime.UTC) + timedelta(hours=72), # 72-hour deadline
|
||||
"created_at": datetime.now(timezone.utc),
|
||||
"deadline": datetime.now(timezone.utc) + timedelta(hours=72), # 72-hour deadline
|
||||
"status": "pending",
|
||||
}
|
||||
|
||||
@@ -301,7 +301,7 @@ class SOC2Compliance:
|
||||
"evidence_requirements": control_config.get("evidence_requirements", []),
|
||||
"testing_procedures": control_config.get("testing_procedures", []),
|
||||
"status": "implemented",
|
||||
"implemented_at": datetime.now(datetime.UTC),
|
||||
"implemented_at": datetime.now(timezone.utc),
|
||||
"last_tested": None,
|
||||
"test_results": [],
|
||||
}
|
||||
@@ -328,10 +328,10 @@ class SOC2Compliance:
|
||||
|
||||
# Record test result
|
||||
control["test_results"].append(
|
||||
{"test_id": str(uuid4()), "timestamp": datetime.now(datetime.UTC), "result": test_result, "tester": "automated"}
|
||||
{"test_id": str(uuid4()), "timestamp": datetime.now(timezone.utc), "result": test_result, "tester": "automated"}
|
||||
)
|
||||
|
||||
control["last_tested"] = datetime.now(datetime.UTC)
|
||||
control["last_tested"] = datetime.now(timezone.utc)
|
||||
|
||||
return test_result
|
||||
|
||||
@@ -456,7 +456,7 @@ class SOC2Compliance:
|
||||
"passed_controls": passed_controls,
|
||||
"compliance_score": compliance_score,
|
||||
"compliance_status": "compliant" if compliance_score >= 0.9 else "non_compliant",
|
||||
"report_date": datetime.now(datetime.UTC).isoformat(),
|
||||
"report_date": datetime.now(timezone.utc).isoformat(),
|
||||
"controls": self.security_controls,
|
||||
}
|
||||
|
||||
@@ -515,8 +515,8 @@ class AMLKYCCompliance:
|
||||
"risk_level": risk_level,
|
||||
"status": status,
|
||||
"risk_factors": risk_factors,
|
||||
"checked_at": datetime.now(datetime.UTC),
|
||||
"next_review": datetime.now(datetime.UTC) + timedelta(days=365),
|
||||
"checked_at": datetime.now(timezone.utc),
|
||||
"next_review": datetime.now(timezone.utc) + timedelta(days=365),
|
||||
}
|
||||
|
||||
self.customer_records[customer_id] = kyc_result
|
||||
@@ -594,7 +594,7 @@ class AMLKYCCompliance:
|
||||
"customer_id": customer_id,
|
||||
"risk_score": risk_score,
|
||||
"suspicious": suspicious,
|
||||
"monitored_at": datetime.now(datetime.UTC),
|
||||
"monitored_at": datetime.now(timezone.utc),
|
||||
}
|
||||
|
||||
if suspicious:
|
||||
@@ -654,7 +654,7 @@ class AMLKYCCompliance:
|
||||
"risk_score": risk_score,
|
||||
"customer_risk_level": customer_risk_level,
|
||||
"transaction_details": transaction_data,
|
||||
"created_at": datetime.now(datetime.UTC),
|
||||
"created_at": datetime.now(timezone.utc),
|
||||
"status": "pending_review",
|
||||
"reported_to_authorities": False,
|
||||
}
|
||||
@@ -686,7 +686,7 @@ class AMLKYCCompliance:
|
||||
"suspicious_transactions": suspicious_transactions,
|
||||
"pending_sars": pending_sars,
|
||||
"suspicious_rate": (suspicious_transactions / total_transactions) if total_transactions > 0 else 0,
|
||||
"report_date": datetime.now(datetime.UTC).isoformat(),
|
||||
"report_date": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
|
||||
@@ -828,7 +828,7 @@ class EnterpriseComplianceEngine:
|
||||
"consent_valid": consent_valid,
|
||||
"retention_compliant": retention_compliant,
|
||||
"protection_compliant": protection_compliant,
|
||||
"checked_at": datetime.now(datetime.UTC).isoformat(),
|
||||
"checked_at": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
async def _check_soc2_compliance(self, entity_data: dict[str, Any]) -> dict[str, Any]:
|
||||
@@ -876,7 +876,7 @@ class EnterpriseComplianceEngine:
|
||||
retention_days = entity_data.get("retention_days", 2555) # 7 years default
|
||||
expiry_date = created_at + timedelta(days=retention_days)
|
||||
|
||||
return datetime.now(datetime.UTC) <= expiry_date
|
||||
return datetime.now(timezone.utc) <= expiry_date
|
||||
|
||||
return True
|
||||
|
||||
@@ -907,7 +907,7 @@ class EnterpriseComplianceEngine:
|
||||
"overall_compliance_score": overall_score,
|
||||
"frameworks": {"GDPR": gdpr_compliance, "SOC 2": soc2_compliance, "AML/KYC": aml_compliance},
|
||||
"total_rules": len(self.compliance_rules),
|
||||
"last_updated": datetime.now(datetime.UTC).isoformat(),
|
||||
"last_updated": datetime.now(timezone.utc).isoformat(),
|
||||
"status": "compliant" if overall_score >= 80 else "needs_attention",
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
Confidential Transaction Service - Wrapper for existing confidential functionality
|
||||
"""
|
||||
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
from ..models.confidential import ConfidentialTransaction
|
||||
@@ -40,7 +40,7 @@ class ConfidentialTransactionService:
|
||||
recipient=recipient,
|
||||
encrypted_payload=encrypted_data,
|
||||
viewing_key=viewing_key,
|
||||
created_at=datetime.now(datetime.UTC),
|
||||
created_at=datetime.now(timezone.utc),
|
||||
)
|
||||
|
||||
def decrypt_transaction(self, transaction: ConfidentialTransaction, viewing_key: str) -> dict[str, Any]:
|
||||
|
||||
@@ -7,7 +7,7 @@ Enables bridging of assets between different blockchain networks.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
|
||||
from aitbc import get_logger
|
||||
from fastapi import HTTPException
|
||||
@@ -119,8 +119,8 @@ class CrossChainBridgeService:
|
||||
total_amount=total_amount,
|
||||
status=BridgeRequestStatus.PENDING,
|
||||
zk_proof=zk_proof.proof,
|
||||
created_at=datetime.now(datetime.UTC),
|
||||
expires_at=datetime.now(datetime.UTC) + timedelta(seconds=self.bridge_timeout),
|
||||
created_at=datetime.now(timezone.utc),
|
||||
expires_at=datetime.now(timezone.utc) + timedelta(seconds=self.bridge_timeout),
|
||||
)
|
||||
|
||||
self.session.add(bridge_request)
|
||||
@@ -156,7 +156,7 @@ class CrossChainBridgeService:
|
||||
# Update local status if different
|
||||
if contract_status.status != bridge_request.status.value:
|
||||
bridge_request.status = BridgeRequestStatus(contract_status.status)
|
||||
bridge_request.updated_at = datetime.now(datetime.UTC)
|
||||
bridge_request.updated_at = datetime.now(timezone.utc)
|
||||
self.session.commit()
|
||||
|
||||
# Get confirmation details
|
||||
@@ -217,7 +217,7 @@ class CrossChainBridgeService:
|
||||
# Record dispute resolution
|
||||
bridge_request.dispute_reason = dispute_reason
|
||||
bridge_request.resolution_action = resolution_action.action_type
|
||||
bridge_request.resolved_at = datetime.now(datetime.UTC)
|
||||
bridge_request.resolved_at = datetime.now(timezone.utc)
|
||||
bridge_request.status = BridgeRequestStatus.RESOLVED
|
||||
|
||||
self.session.commit()
|
||||
@@ -273,7 +273,7 @@ class CrossChainBridgeService:
|
||||
transaction_type="confirmation",
|
||||
transaction_hash=confirm_request.lock_tx_hash,
|
||||
signature=confirm_request.signature,
|
||||
confirmed_at=datetime.now(datetime.UTC),
|
||||
confirmed_at=datetime.now(timezone.utc),
|
||||
)
|
||||
|
||||
self.session.add(confirmation)
|
||||
@@ -285,7 +285,7 @@ class CrossChainBridgeService:
|
||||
if total_confirmations >= required_confirmations:
|
||||
# Update bridge request status
|
||||
bridge_request.status = BridgeRequestStatus.CONFIRMED
|
||||
bridge_request.confirmed_at = datetime.now(datetime.UTC)
|
||||
bridge_request.confirmed_at = datetime.now(timezone.utc)
|
||||
|
||||
# Generate Merkle proof for completion
|
||||
merkle_proof = await self._generate_merkle_proof(bridge_request)
|
||||
@@ -338,14 +338,14 @@ class CrossChainBridgeService:
|
||||
transaction_type="completion",
|
||||
transaction_hash=complete_request.unlock_tx_hash,
|
||||
merkle_proof=complete_request.merkle_proof,
|
||||
completed_at=datetime.now(datetime.UTC),
|
||||
completed_at=datetime.now(timezone.utc),
|
||||
)
|
||||
|
||||
self.session.add(completion)
|
||||
|
||||
# Update bridge request status
|
||||
bridge_request.status = BridgeRequestStatus.COMPLETED
|
||||
bridge_request.completed_at = datetime.now(datetime.UTC)
|
||||
bridge_request.completed_at = datetime.now(timezone.utc)
|
||||
bridge_request.unlock_tx_hash = complete_request.unlock_tx_hash
|
||||
|
||||
self.session.commit()
|
||||
@@ -386,7 +386,7 @@ class CrossChainBridgeService:
|
||||
fee_percentage=token_request.fee_percentage,
|
||||
requires_whitelist=token_request.requires_whitelist,
|
||||
is_active=True,
|
||||
created_at=datetime.now(datetime.UTC),
|
||||
created_at=datetime.now(timezone.utc),
|
||||
)
|
||||
|
||||
self.session.add(supported_token)
|
||||
@@ -422,7 +422,7 @@ class CrossChainBridgeService:
|
||||
min_confirmations=chain_request.min_confirmations,
|
||||
avg_block_time=chain_request.avg_block_time,
|
||||
is_active=True,
|
||||
created_at=datetime.now(datetime.UTC),
|
||||
created_at=datetime.now(timezone.utc),
|
||||
)
|
||||
|
||||
self.session.add(chain_config)
|
||||
@@ -489,7 +489,7 @@ class CrossChainBridgeService:
|
||||
"amount": transfer_request.amount,
|
||||
"source_chain": transfer_request.source_chain_id,
|
||||
"target_chain": transfer_request.target_chain_id,
|
||||
"timestamp": int(datetime.now(datetime.UTC).timestamp()),
|
||||
"timestamp": int(datetime.now(timezone.utc).timestamp()),
|
||||
}
|
||||
|
||||
# Generate ZK proof
|
||||
|
||||
@@ -6,7 +6,7 @@ Production-ready cross-chain bridge service with atomic swap protocol implementa
|
||||
import asyncio
|
||||
import hashlib
|
||||
import secrets
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from decimal import Decimal
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
@@ -153,9 +153,9 @@ class CrossChainBridgeService:
|
||||
bridge_fee=bridge_fee,
|
||||
network_fee=network_fee,
|
||||
total_fee=total_fee,
|
||||
deadline=datetime.now(datetime.UTC) + timedelta(minutes=deadline_minutes),
|
||||
deadline=datetime.now(timezone.utc) + timedelta(minutes=deadline_minutes),
|
||||
status=BridgeRequestStatus.PENDING,
|
||||
created_at=datetime.now(datetime.UTC),
|
||||
created_at=datetime.now(timezone.utc),
|
||||
)
|
||||
|
||||
self.session.add(bridge_request)
|
||||
@@ -274,7 +274,7 @@ class CrossChainBridgeService:
|
||||
# Update status
|
||||
bridge_request.status = BridgeRequestStatus.CANCELLED
|
||||
bridge_request.cancellation_reason = reason
|
||||
bridge_request.updated_at = datetime.now(datetime.UTC)
|
||||
bridge_request.updated_at = datetime.now(timezone.utc)
|
||||
|
||||
self.session.commit()
|
||||
|
||||
@@ -288,7 +288,7 @@ class CrossChainBridgeService:
|
||||
"bridge_request_id": bridge_request_id,
|
||||
"status": BridgeRequestStatus.CANCELLED.value,
|
||||
"reason": reason,
|
||||
"cancelled_at": datetime.now(datetime.UTC).isoformat(),
|
||||
"cancelled_at": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
@@ -300,7 +300,7 @@ class CrossChainBridgeService:
|
||||
"""Get bridge statistics for the specified time period"""
|
||||
|
||||
try:
|
||||
cutoff_time = datetime.now(datetime.UTC) - timedelta(hours=time_period_hours)
|
||||
cutoff_time = datetime.now(timezone.utc) - timedelta(hours=time_period_hours)
|
||||
|
||||
# Get total requests
|
||||
total_requests = (
|
||||
@@ -378,7 +378,7 @@ class CrossChainBridgeService:
|
||||
"total_fees": total_fees,
|
||||
"average_processing_time_minutes": avg_processing_time / 60,
|
||||
"chain_distribution": chain_distribution,
|
||||
"generated_at": datetime.now(datetime.UTC).isoformat(),
|
||||
"generated_at": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
@@ -401,7 +401,7 @@ class CrossChainBridgeService:
|
||||
"utilization_rate": pool.get("utilization_rate", 0),
|
||||
"apr": pool.get("apr", 0),
|
||||
"fee_rate": pool.get("fee_rate", 0.005),
|
||||
"last_updated": pool.get("last_updated", datetime.now(datetime.UTC).isoformat()),
|
||||
"last_updated": pool.get("last_updated", datetime.now(timezone.utc).isoformat()),
|
||||
}
|
||||
|
||||
pools.append(pool_info)
|
||||
@@ -426,7 +426,7 @@ class CrossChainBridgeService:
|
||||
|
||||
# Update status to confirmed
|
||||
bridge_request.status = BridgeRequestStatus.CONFIRMED
|
||||
bridge_request.updated_at = datetime.now(datetime.UTC)
|
||||
bridge_request.updated_at = datetime.now(timezone.utc)
|
||||
self.session.commit()
|
||||
|
||||
# Execute bridge based on protocol
|
||||
@@ -446,7 +446,7 @@ class CrossChainBridgeService:
|
||||
stmt = (
|
||||
update(BridgeRequest)
|
||||
.where(BridgeRequest.id == bridge_request_id)
|
||||
.values(status=BridgeRequestStatus.FAILED, error_message=str(e), updated_at=datetime.now(datetime.UTC))
|
||||
.values(status=BridgeRequestStatus.FAILED, error_message=str(e), updated_at=datetime.now(timezone.utc))
|
||||
)
|
||||
self.session.execute(stmt)
|
||||
self.session.commit()
|
||||
@@ -476,7 +476,7 @@ class CrossChainBridgeService:
|
||||
|
||||
# Update bridge request with source transaction
|
||||
bridge_request.source_transaction_hash = source_tx["transaction_hash"]
|
||||
bridge_request.updated_at = datetime.now(datetime.UTC)
|
||||
bridge_request.updated_at = datetime.now(timezone.utc)
|
||||
self.session.commit()
|
||||
|
||||
# Wait for confirmations
|
||||
@@ -496,8 +496,8 @@ class CrossChainBridgeService:
|
||||
# Update bridge request with target transaction
|
||||
bridge_request.target_transaction_hash = target_tx["transaction_hash"]
|
||||
bridge_request.status = BridgeRequestStatus.COMPLETED
|
||||
bridge_request.completed_at = datetime.now(datetime.UTC)
|
||||
bridge_request.updated_at = datetime.now(datetime.UTC)
|
||||
bridge_request.completed_at = datetime.now(timezone.utc)
|
||||
bridge_request.updated_at = datetime.now(timezone.utc)
|
||||
self.session.commit()
|
||||
|
||||
logger.info(f"Completed atomic swap for bridge request {bridge_request.id}")
|
||||
@@ -535,8 +535,8 @@ class CrossChainBridgeService:
|
||||
# Update bridge request
|
||||
bridge_request.source_transaction_hash = source_tx["transaction_hash"]
|
||||
bridge_request.status = BridgeRequestStatus.COMPLETED
|
||||
bridge_request.completed_at = datetime.now(datetime.UTC)
|
||||
bridge_request.updated_at = datetime.now(datetime.UTC)
|
||||
bridge_request.completed_at = datetime.now(timezone.utc)
|
||||
bridge_request.updated_at = datetime.now(timezone.utc)
|
||||
self.session.commit()
|
||||
|
||||
logger.info(f"Completed liquidity pool swap for bridge request {bridge_request.id}")
|
||||
@@ -568,7 +568,7 @@ class CrossChainBridgeService:
|
||||
# Update bridge request
|
||||
bridge_request.source_transaction_hash = source_tx["transaction_hash"]
|
||||
bridge_request.secret_hash = secret_hash
|
||||
bridge_request.updated_at = datetime.now(datetime.UTC)
|
||||
bridge_request.updated_at = datetime.now(timezone.utc)
|
||||
self.session.commit()
|
||||
|
||||
# Create HTLC contract on target chain
|
||||
@@ -627,8 +627,8 @@ class CrossChainBridgeService:
|
||||
f"0x{hashlib.sha256(f'htlc_complete_{bridge_request.id}_{secret}'.encode()).hexdigest()}"
|
||||
)
|
||||
bridge_request.status = BridgeRequestStatus.COMPLETED
|
||||
bridge_request.completed_at = datetime.now(datetime.UTC)
|
||||
bridge_request.updated_at = datetime.now(datetime.UTC)
|
||||
bridge_request.completed_at = datetime.now(timezone.utc)
|
||||
bridge_request.updated_at = datetime.now(timezone.utc)
|
||||
self.session.commit()
|
||||
|
||||
async def _estimate_network_fee(self, chain_id: int, amount: float, token_address: str | None) -> float:
|
||||
@@ -751,7 +751,7 @@ class CrossChainBridgeService:
|
||||
"utilization_rate": 0.0,
|
||||
"apr": 0.05, # 5% APR
|
||||
"fee_rate": 0.005, # 0.5% fee
|
||||
"last_updated": datetime.now(datetime.UTC),
|
||||
"last_updated": datetime.now(timezone.utc),
|
||||
}
|
||||
|
||||
logger.info(f"Initialized liquidity pool for chain {chain_id}")
|
||||
|
||||
@@ -10,7 +10,7 @@ from aitbc import get_logger
|
||||
logger = get_logger(__name__)
|
||||
import json
|
||||
from dataclasses import asdict, dataclass, field
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
|
||||
@@ -217,8 +217,8 @@ class CrossChainReputationService:
|
||||
task_count=0,
|
||||
success_count=0,
|
||||
failure_count=0,
|
||||
last_updated=datetime.now(datetime.UTC),
|
||||
sync_timestamp=datetime.now(datetime.UTC),
|
||||
last_updated=datetime.now(timezone.utc),
|
||||
sync_timestamp=datetime.now(timezone.utc),
|
||||
is_active=True,
|
||||
)
|
||||
|
||||
@@ -264,7 +264,7 @@ class CrossChainReputationService:
|
||||
reputation.failure_count += 1
|
||||
|
||||
reputation.task_count += 1
|
||||
reputation.last_updated = datetime.now(datetime.UTC)
|
||||
reputation.last_updated = datetime.now(timezone.utc)
|
||||
reputation.tier = reputation.calculate_tier()
|
||||
|
||||
# Update chain reputation
|
||||
@@ -291,7 +291,7 @@ class CrossChainReputationService:
|
||||
reputation = self.reputation_data[agent_id]
|
||||
|
||||
# Check sync cooldown
|
||||
time_since_sync = (datetime.now(datetime.UTC) - reputation.sync_timestamp).total_seconds()
|
||||
time_since_sync = (datetime.now(timezone.utc) - reputation.sync_timestamp).total_seconds()
|
||||
if time_since_sync < self.sync_cooldown:
|
||||
logger.warning(f"Sync cooldown not met for agent {agent_id}")
|
||||
return False
|
||||
@@ -305,7 +305,7 @@ class CrossChainReputationService:
|
||||
source_chain=reputation.chain_id,
|
||||
target_chain=target_chain,
|
||||
reputation_score=reputation.score,
|
||||
sync_timestamp=datetime.now(datetime.UTC),
|
||||
sync_timestamp=datetime.now(timezone.utc),
|
||||
verification_hash=verification_hash,
|
||||
is_verified=True,
|
||||
)
|
||||
@@ -322,16 +322,16 @@ class CrossChainReputationService:
|
||||
success_count=reputation.success_count,
|
||||
failure_count=reputation.failure_count,
|
||||
last_updated=reputation.last_updated,
|
||||
sync_timestamp=datetime.now(datetime.UTC),
|
||||
sync_timestamp=datetime.now(timezone.utc),
|
||||
is_active=True,
|
||||
)
|
||||
else:
|
||||
target_reputation = self.chain_reputations[agent_id][target_chain]
|
||||
target_reputation.score = reputation.score
|
||||
target_reputation.sync_timestamp = datetime.now(datetime.UTC)
|
||||
target_reputation.sync_timestamp = datetime.now(timezone.utc)
|
||||
|
||||
# Update sync timestamp
|
||||
reputation.sync_timestamp = datetime.now(datetime.UTC)
|
||||
reputation.sync_timestamp = datetime.now(timezone.utc)
|
||||
|
||||
logger.info(f"Synced reputation for agent {agent_id} to chain {target_chain}")
|
||||
return True
|
||||
@@ -360,8 +360,8 @@ class CrossChainReputationService:
|
||||
agent_id=agent_id,
|
||||
amount=amount,
|
||||
lock_period=lock_period,
|
||||
start_time=datetime.now(datetime.UTC),
|
||||
end_time=datetime.now(datetime.UTC) + timedelta(seconds=lock_period),
|
||||
start_time=datetime.now(timezone.utc),
|
||||
end_time=datetime.now(timezone.utc) + timedelta(seconds=lock_period),
|
||||
is_active=True,
|
||||
reward_rate=reward_rate,
|
||||
multiplier=1.0 + (reputation.score / 10000) * 0.5, # Up to 50% bonus
|
||||
@@ -407,7 +407,7 @@ class CrossChainReputationService:
|
||||
delegator=delegator,
|
||||
delegate=delegate,
|
||||
amount=amount,
|
||||
start_time=datetime.now(datetime.UTC),
|
||||
start_time=datetime.now(timezone.utc),
|
||||
is_active=True,
|
||||
fee_rate=fee_rate,
|
||||
)
|
||||
@@ -469,7 +469,7 @@ class CrossChainReputationService:
|
||||
delegation.amount for delegation in self.reputation_delegations.get(agent_id, []) if delegation.is_active
|
||||
)
|
||||
chain_count = len(self.chain_reputations.get(agent_id, {}))
|
||||
reputation_age = (datetime.now(datetime.UTC) - reputation.last_updated).days
|
||||
reputation_age = (datetime.now(timezone.utc) - reputation.last_updated).days
|
||||
|
||||
return ReputationAnalytics(
|
||||
agent_id=agent_id,
|
||||
@@ -543,7 +543,7 @@ class CrossChainReputationService:
|
||||
# In production, implement proper cross-chain signature verification
|
||||
import hashlib
|
||||
|
||||
hash_input = f"{agent_id}:{chain_id}:{datetime.now(datetime.UTC).isoformat()}".encode()
|
||||
hash_input = f"{agent_id}:{chain_id}:{datetime.now(timezone.utc).isoformat()}".encode()
|
||||
return hashlib.sha256(hash_input).hexdigest()
|
||||
|
||||
async def _get_total_delegated(self, agent_id: str) -> int:
|
||||
@@ -601,7 +601,7 @@ class CrossChainReputationService:
|
||||
|
||||
async def _distribute_stake_rewards(self):
|
||||
"""Distribute rewards for active stakes"""
|
||||
current_time = datetime.now(datetime.UTC)
|
||||
current_time = datetime.now(timezone.utc)
|
||||
|
||||
for agent_id, stakes in self.reputation_stakes.items():
|
||||
for stake in stakes:
|
||||
@@ -619,7 +619,7 @@ class CrossChainReputationService:
|
||||
"""Clean up expired stakes and delegations"""
|
||||
while True:
|
||||
try:
|
||||
current_time = datetime.now(datetime.UTC)
|
||||
current_time = datetime.now(timezone.utc)
|
||||
|
||||
# Clean up expired stakes
|
||||
for _agent_id, stakes in self.reputation_stakes.items():
|
||||
@@ -657,7 +657,7 @@ class CrossChainReputationService:
|
||||
"chain_reputations": {k: {str(k2): asdict(v2) for k2, v2 in v.items()} for k, v in self.chain_reputations.items()},
|
||||
"reputation_stakes": {k: [asdict(s) for s in v] for k, v in self.reputation_stakes.items()},
|
||||
"reputation_delegations": {k: [asdict(d) for d in v] for k, v in self.reputation_delegations.items()},
|
||||
"export_timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"export_timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
if format.lower() == "json":
|
||||
|
||||
@@ -6,7 +6,7 @@ Service for managing multi-jurisdictional DAOs, regional councils, and global tr
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
|
||||
from aitbc import get_logger
|
||||
from fastapi import HTTPException
|
||||
@@ -53,7 +53,7 @@ class DAOGovernanceService:
|
||||
if request.target_region and not (proposer.is_council_member and proposer.council_region == request.target_region):
|
||||
raise HTTPException(status_code=403, detail="Only regional council members can create regional proposals")
|
||||
|
||||
start_time = datetime.now(datetime.UTC)
|
||||
start_time = datetime.now(timezone.utc)
|
||||
end_time = start_time + timedelta(days=request.voting_period_days)
|
||||
|
||||
proposal = DAOProposal(
|
||||
@@ -89,7 +89,7 @@ class DAOGovernanceService:
|
||||
if proposal.status != ProposalState.ACTIVE:
|
||||
raise HTTPException(status_code=400, detail="Proposal is not active")
|
||||
|
||||
now = datetime.now(datetime.UTC)
|
||||
now = datetime.now(timezone.utc)
|
||||
if now < proposal.start_time or now > proposal.end_time:
|
||||
proposal.status = ProposalState.EXPIRED
|
||||
self.session.commit()
|
||||
@@ -133,7 +133,7 @@ class DAOGovernanceService:
|
||||
if proposal.status != ProposalState.ACTIVE:
|
||||
raise HTTPException(status_code=400, detail=f"Cannot execute proposal in state {proposal.status}")
|
||||
|
||||
if datetime.now(datetime.UTC) <= proposal.end_time:
|
||||
if datetime.now(timezone.utc) <= proposal.end_time:
|
||||
raise HTTPException(status_code=400, detail="Voting period has not ended yet")
|
||||
|
||||
if proposal.for_votes > proposal.against_votes:
|
||||
|
||||
@@ -6,7 +6,7 @@ Service for managing the developer ecosystem, bounties, certifications, and regi
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
|
||||
from aitbc import get_logger
|
||||
from fastapi import HTTPException
|
||||
@@ -150,7 +150,7 @@ class DeveloperPlatformService:
|
||||
submission.is_approved = True
|
||||
submission.review_notes = review_notes
|
||||
submission.reviewer_address = reviewer_address
|
||||
submission.reviewed_at = datetime.now(datetime.UTC)
|
||||
submission.reviewed_at = datetime.now(timezone.utc)
|
||||
|
||||
bounty.status = BountyStatus.COMPLETED
|
||||
bounty.assigned_developer_id = developer.id
|
||||
@@ -185,7 +185,7 @@ class DeveloperPlatformService:
|
||||
if hasattr(profile, key):
|
||||
setattr(profile, key, value)
|
||||
|
||||
profile.updated_at = datetime.now(datetime.UTC)
|
||||
profile.updated_at = datetime.now(timezone.utc)
|
||||
self.session.commit()
|
||||
self.session.refresh(profile)
|
||||
|
||||
@@ -306,7 +306,7 @@ class DeveloperPlatformService:
|
||||
"amount_staked": amount,
|
||||
"apy": 5.0 + (developer.reputation_score / 100), # Base APY + reputation bonus
|
||||
"staking_id": f"stake_{staker_address[:8]}_{developer_address[:8]}",
|
||||
"created_at": datetime.now(datetime.UTC).isoformat(),
|
||||
"created_at": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
logger.info(f"Staked {amount} AITBC on developer {developer_address} by {staker_address}")
|
||||
@@ -332,7 +332,7 @@ class DeveloperPlatformService:
|
||||
"amount_unstaked": amount,
|
||||
"rewards_earned": 25.5,
|
||||
"tx_hash": "0xmock_unstake_tx_hash",
|
||||
"completed_at": datetime.now(datetime.UTC).isoformat(),
|
||||
"completed_at": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
logger.info(f"Unstaked {amount} AITBC from staking position {staking_id}")
|
||||
@@ -345,8 +345,8 @@ class DeveloperPlatformService:
|
||||
"address": address,
|
||||
"pending_rewards": 45.75,
|
||||
"claimed_rewards": 250.25,
|
||||
"last_claim_time": (datetime.now(datetime.UTC) - timedelta(days=7)).isoformat(),
|
||||
"next_claim_time": (datetime.now(datetime.UTC) + timedelta(days=1)).isoformat(),
|
||||
"last_claim_time": (datetime.now(timezone.utc) - timedelta(days=7)).isoformat(),
|
||||
"next_claim_time": (datetime.now(timezone.utc) + timedelta(days=1)).isoformat(),
|
||||
}
|
||||
|
||||
async def claim_rewards(self, address: str) -> dict:
|
||||
@@ -367,7 +367,7 @@ class DeveloperPlatformService:
|
||||
"address": address,
|
||||
"amount_claimed": rewards["pending_rewards"],
|
||||
"tx_hash": "0xmock_claim_tx_hash",
|
||||
"claimed_at": datetime.now(datetime.UTC).isoformat(),
|
||||
"claimed_at": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
logger.info(f"Claimed {rewards['pending_rewards']} AITBC rewards for {address}")
|
||||
|
||||
@@ -9,7 +9,7 @@ import time
|
||||
import json
|
||||
import hashlib
|
||||
from typing import Dict, List, Optional, Any, Callable, Awaitable
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from enum import Enum
|
||||
|
||||
from aitbc import get_logger
|
||||
@@ -465,5 +465,5 @@ class DistributedProcessingCoordinator:
|
||||
"utilization_percent": round(utilization, 2),
|
||||
"cache_size": len(self.result_cache)
|
||||
},
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat()
|
||||
"timestamp": datetime.now(timezone.utc).isoformat()
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ Implements sophisticated pricing algorithms based on real-time market conditions
|
||||
|
||||
import asyncio
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
|
||||
@@ -107,7 +107,7 @@ class MarketConditions:
|
||||
utilization_rate: float
|
||||
competitor_prices: list[float] = field(default_factory=list)
|
||||
market_sentiment: float = 0.0 # -1 to 1
|
||||
timestamp: datetime = field(default_factory=datetime.now(datetime.UTC))
|
||||
timestamp: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -238,7 +238,7 @@ class DynamicPricingEngine:
|
||||
confidence = await self._calculate_confidence_score(factors, market_conditions)
|
||||
|
||||
# Schedule next update
|
||||
next_update = datetime.now(datetime.UTC) + timedelta(seconds=self.update_interval)
|
||||
next_update = datetime.now(timezone.utc) + timedelta(seconds=self.update_interval)
|
||||
|
||||
# Store price point
|
||||
await self._store_price_point(resource_id, final_price, factors, strategy)
|
||||
@@ -302,7 +302,7 @@ class DynamicPricingEngine:
|
||||
confidence = max(0.3, 0.9 - (hour / hours_ahead) * 0.6)
|
||||
|
||||
forecast_point = PricePoint(
|
||||
timestamp=datetime.now(datetime.UTC) + timedelta(hours=hour),
|
||||
timestamp=datetime.now(timezone.utc) + timedelta(hours=hour),
|
||||
price=forecast_price,
|
||||
demand_level=demand_forecast,
|
||||
supply_level=supply_forecast,
|
||||
@@ -485,8 +485,8 @@ class DynamicPricingEngine:
|
||||
def _calculate_time_multiplier(self) -> float:
|
||||
"""Calculate time-based price multiplier"""
|
||||
|
||||
hour = datetime.now(datetime.UTC).hour
|
||||
day_of_week = datetime.now(datetime.UTC).weekday()
|
||||
hour = datetime.now(timezone.utc).hour
|
||||
day_of_week = datetime.now(timezone.utc).weekday()
|
||||
|
||||
# Business hours premium (8 AM - 8 PM, Monday-Friday)
|
||||
if 8 <= hour <= 20 and day_of_week < 5:
|
||||
@@ -624,7 +624,7 @@ class DynamicPricingEngine:
|
||||
reasoning.append("High supply enables competitive pricing")
|
||||
|
||||
# Time-based reasoning
|
||||
hour = datetime.now(datetime.UTC).hour
|
||||
hour = datetime.now(timezone.utc).hour
|
||||
if 8 <= hour <= 20:
|
||||
reasoning.append("Business hours premium applied")
|
||||
elif 2 <= hour <= 6:
|
||||
@@ -677,7 +677,7 @@ class DynamicPricingEngine:
|
||||
self.pricing_history[resource_id] = []
|
||||
|
||||
price_point = PricePoint(
|
||||
timestamp=datetime.now(datetime.UTC),
|
||||
timestamp=datetime.now(timezone.utc),
|
||||
price=price,
|
||||
demand_level=factors.demand_level,
|
||||
supply_level=factors.supply_level,
|
||||
@@ -699,7 +699,7 @@ class DynamicPricingEngine:
|
||||
if cache_key in self.market_conditions_cache:
|
||||
cached = self.market_conditions_cache[cache_key]
|
||||
# Use cached data if less than 5 minutes old
|
||||
if (datetime.now(datetime.UTC) - cached.timestamp).total_seconds() < 300:
|
||||
if (datetime.now(timezone.utc) - cached.timestamp).total_seconds() < 300:
|
||||
return cached
|
||||
|
||||
# In a real implementation, this would fetch from market data sources
|
||||
|
||||
@@ -3,7 +3,7 @@ Ecosystem Analytics Service
|
||||
Business logic for developer ecosystem metrics and analytics
|
||||
"""
|
||||
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import and_, func, select
|
||||
@@ -30,13 +30,13 @@ class EcosystemService:
|
||||
try:
|
||||
# Calculate time period
|
||||
if period == "daily":
|
||||
start_date = datetime.now(datetime.UTC) - timedelta(days=1)
|
||||
start_date = datetime.now(timezone.utc) - timedelta(days=1)
|
||||
elif period == "weekly":
|
||||
start_date = datetime.now(datetime.UTC) - timedelta(weeks=1)
|
||||
start_date = datetime.now(timezone.utc) - timedelta(weeks=1)
|
||||
elif period == "monthly":
|
||||
start_date = datetime.now(datetime.UTC) - timedelta(days=30)
|
||||
start_date = datetime.now(timezone.utc) - timedelta(days=30)
|
||||
else:
|
||||
start_date = datetime.now(datetime.UTC) - timedelta(days=30)
|
||||
start_date = datetime.now(timezone.utc) - timedelta(days=30)
|
||||
|
||||
# Get total earnings from completed bounties
|
||||
earnings_stmt = select(
|
||||
@@ -114,13 +114,13 @@ class EcosystemService:
|
||||
try:
|
||||
# Calculate time period
|
||||
if period == "daily":
|
||||
start_date = datetime.now(datetime.UTC) - timedelta(days=1)
|
||||
start_date = datetime.now(timezone.utc) - timedelta(days=1)
|
||||
elif period == "weekly":
|
||||
start_date = datetime.now(datetime.UTC) - timedelta(weeks=1)
|
||||
start_date = datetime.now(timezone.utc) - timedelta(weeks=1)
|
||||
elif period == "monthly":
|
||||
start_date = datetime.now(datetime.UTC) - timedelta(days=30)
|
||||
start_date = datetime.now(timezone.utc) - timedelta(days=30)
|
||||
else:
|
||||
start_date = datetime.now(datetime.UTC) - timedelta(days=30)
|
||||
start_date = datetime.now(timezone.utc) - timedelta(days=30)
|
||||
|
||||
# Get agent metrics
|
||||
agents_stmt = select(
|
||||
@@ -196,13 +196,13 @@ class EcosystemService:
|
||||
try:
|
||||
# Calculate time period
|
||||
if period == "daily":
|
||||
start_date = datetime.now(datetime.UTC) - timedelta(days=1)
|
||||
start_date = datetime.now(timezone.utc) - timedelta(days=1)
|
||||
elif period == "weekly":
|
||||
start_date = datetime.now(datetime.UTC) - timedelta(weeks=1)
|
||||
start_date = datetime.now(timezone.utc) - timedelta(weeks=1)
|
||||
elif period == "monthly":
|
||||
start_date = datetime.now(datetime.UTC) - timedelta(days=30)
|
||||
start_date = datetime.now(timezone.utc) - timedelta(days=30)
|
||||
else:
|
||||
start_date = datetime.now(datetime.UTC) - timedelta(days=30)
|
||||
start_date = datetime.now(timezone.utc) - timedelta(days=30)
|
||||
|
||||
# Get bounty fees (treasury inflow)
|
||||
inflow_stmt = select(
|
||||
@@ -252,13 +252,13 @@ class EcosystemService:
|
||||
try:
|
||||
# Calculate time period
|
||||
if period == "daily":
|
||||
start_date = datetime.now(datetime.UTC) - timedelta(days=1)
|
||||
start_date = datetime.now(timezone.utc) - timedelta(days=1)
|
||||
elif period == "weekly":
|
||||
start_date = datetime.now(datetime.UTC) - timedelta(weeks=1)
|
||||
start_date = datetime.now(timezone.utc) - timedelta(weeks=1)
|
||||
elif period == "monthly":
|
||||
start_date = datetime.now(datetime.UTC) - timedelta(days=30)
|
||||
start_date = datetime.now(timezone.utc) - timedelta(days=30)
|
||||
else:
|
||||
start_date = datetime.now(datetime.UTC) - timedelta(days=30)
|
||||
start_date = datetime.now(timezone.utc) - timedelta(days=30)
|
||||
|
||||
# Get staking metrics
|
||||
staking_stmt = select(
|
||||
@@ -335,13 +335,13 @@ class EcosystemService:
|
||||
try:
|
||||
# Calculate time period
|
||||
if period == "daily":
|
||||
start_date = datetime.now(datetime.UTC) - timedelta(days=1)
|
||||
start_date = datetime.now(timezone.utc) - timedelta(days=1)
|
||||
elif period == "weekly":
|
||||
start_date = datetime.now(datetime.UTC) - timedelta(weeks=1)
|
||||
start_date = datetime.now(timezone.utc) - timedelta(weeks=1)
|
||||
elif period == "monthly":
|
||||
start_date = datetime.now(datetime.UTC) - timedelta(days=30)
|
||||
start_date = datetime.now(timezone.utc) - timedelta(days=30)
|
||||
else:
|
||||
start_date = datetime.now(datetime.UTC) - timedelta(days=30)
|
||||
start_date = datetime.now(timezone.utc) - timedelta(days=30)
|
||||
|
||||
# Get bounty counts
|
||||
bounty_stmt = select(
|
||||
@@ -455,9 +455,9 @@ class EcosystemService:
|
||||
"""Get time-series ecosystem metrics"""
|
||||
try:
|
||||
if not start_date:
|
||||
start_date = datetime.now(datetime.UTC) - timedelta(days=30)
|
||||
start_date = datetime.now(timezone.utc) - timedelta(days=30)
|
||||
if not end_date:
|
||||
end_date = datetime.now(datetime.UTC)
|
||||
end_date = datetime.now(timezone.utc)
|
||||
|
||||
# This is a simplified implementation
|
||||
# In production, you'd want more sophisticated time-series aggregation
|
||||
@@ -651,7 +651,7 @@ class EcosystemService:
|
||||
"type": "performance",
|
||||
"severity": "medium",
|
||||
"message": "Agent utilization dropped below 70%",
|
||||
"timestamp": datetime.now(datetime.UTC) - timedelta(hours=2),
|
||||
"timestamp": datetime.now(timezone.utc) - timedelta(hours=2),
|
||||
"resolved": False,
|
||||
},
|
||||
{
|
||||
@@ -659,7 +659,7 @@ class EcosystemService:
|
||||
"type": "financial",
|
||||
"severity": "low",
|
||||
"message": "Bounty completion rate decreased by 5%",
|
||||
"timestamp": datetime.now(datetime.UTC) - timedelta(hours=6),
|
||||
"timestamp": datetime.now(timezone.utc) - timedelta(hours=6),
|
||||
"resolved": False,
|
||||
},
|
||||
]
|
||||
@@ -762,12 +762,12 @@ class EcosystemService:
|
||||
metrics = await self.get_time_series_metrics(period_type, start_date, end_date)
|
||||
|
||||
# Mock export URL generation
|
||||
export_url = f"/exports/ecosystem_data_{datetime.now(datetime.UTC).strftime('%Y%m%d_%H%M%S')}.{format}"
|
||||
export_url = f"/exports/ecosystem_data_{datetime.now(timezone.utc).strftime('%Y%m%d_%H%M%S')}.{format}"
|
||||
|
||||
return {
|
||||
"url": export_url,
|
||||
"file_size": len(str(metrics)) * 0.001, # Mock file size in KB
|
||||
"expires_at": datetime.now(datetime.UTC) + timedelta(hours=24),
|
||||
"expires_at": datetime.now(timezone.utc) + timedelta(hours=24),
|
||||
"record_count": len(metrics),
|
||||
}
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user