fix: resolve SQLModel migrations for .exec() -> .execute().scalars() and API schema issues

This commit is contained in:
oib
2026-03-05 08:28:40 +01:00
parent bbbfbf8dde
commit 1f16a1c406
37 changed files with 243 additions and 238 deletions

View File

@@ -418,10 +418,10 @@ async def get_pricing(
) -> Dict[str, Any]: ) -> Dict[str, Any]:
"""Get enhanced pricing information for a model with dynamic pricing.""" """Get enhanced pricing information for a model with dynamic pricing."""
# SQLite JSON doesn't support array contains, so fetch all and filter in Python # SQLite JSON doesn't support array contains, so fetch all and filter in Python
all_gpus = session.execute(select(GPURegistry)).all() all_gpus = session.execute(select(GPURegistry)).scalars().all()
compatible = [ compatible = [
g for g in all_gpus g for g in all_gpus
if any(model.lower() in cap.lower() for cap in (g.capabilities or [])) if model.lower() in g.model.lower()
] ]
if not compatible: if not compatible:

View File

@@ -630,7 +630,7 @@ class AdvancedReinforcementLearningEngine:
async def train_rl_agent(self, session: Session, config_id: str) -> Dict[str, Any]: async def train_rl_agent(self, session: Session, config_id: str) -> Dict[str, Any]:
"""Train RL agent""" """Train RL agent"""
rl_config = session.exec( rl_config = session.execute(
select(ReinforcementLearningConfig).where(ReinforcementLearningConfig.config_id == config_id) select(ReinforcementLearningConfig).where(ReinforcementLearningConfig.config_id == config_id)
).first() ).first()
@@ -1404,7 +1404,7 @@ class MarketplaceStrategyOptimizer:
await asyncio.sleep(1) # Simulate training time await asyncio.sleep(1) # Simulate training time
# Get trained agent performance # Get trained agent performance
trained_config = session.exec( trained_config = session.execute(
select(ReinforcementLearningConfig).where( select(ReinforcementLearningConfig).where(
ReinforcementLearningConfig.config_id == rl_config.config_id ReinforcementLearningConfig.config_id == rl_config.config_id
) )
@@ -1435,7 +1435,7 @@ class MarketplaceStrategyOptimizer:
) -> Dict[str, Any]: ) -> Dict[str, Any]:
"""Deploy trained strategy""" """Deploy trained strategy"""
rl_config = session.exec( rl_config = session.execute(
select(ReinforcementLearningConfig).where( select(ReinforcementLearningConfig).where(
ReinforcementLearningConfig.config_id == config_id ReinforcementLearningConfig.config_id == config_id
) )
@@ -1521,7 +1521,7 @@ class CrossDomainCapabilityIntegrator:
"""Integrate capabilities across different domains""" """Integrate capabilities across different domains"""
# Get agent capabilities # Get agent capabilities
agent_capabilities = session.exec( agent_capabilities = session.execute(
select(AgentCapability).where(AgentCapability.agent_id == agent_id) select(AgentCapability).where(AgentCapability.agent_id == agent_id)
).all() ).all()

View File

@@ -178,7 +178,7 @@ class AgentIntegrationManager:
try: try:
# Get execution details # Get execution details
execution = self.session.exec( execution = self.session.execute(
select(AgentExecution).where(AgentExecution.id == execution_id) select(AgentExecution).where(AgentExecution.id == execution_id)
).first() ).first()
@@ -186,7 +186,7 @@ class AgentIntegrationManager:
raise ValueError(f"Execution not found: {execution_id}") raise ValueError(f"Execution not found: {execution_id}")
# Get step executions # Get step executions
step_executions = self.session.exec( step_executions = self.session.execute(
select(AgentStepExecution).where( select(AgentStepExecution).where(
AgentStepExecution.execution_id == execution_id AgentStepExecution.execution_id == execution_id
) )
@@ -557,7 +557,7 @@ class AgentDeploymentManager:
raise ValueError(f"Deployment config not found: {deployment_config_id}") raise ValueError(f"Deployment config not found: {deployment_config_id}")
# Get deployment instances # Get deployment instances
instances = self.session.exec( instances = self.session.execute(
select(AgentDeploymentInstance).where( select(AgentDeploymentInstance).where(
AgentDeploymentInstance.deployment_id == deployment_config_id AgentDeploymentInstance.deployment_id == deployment_config_id
) )
@@ -671,7 +671,7 @@ class AgentDeploymentManager:
raise ValueError(f"Deployment config not found: {deployment_config_id}") raise ValueError(f"Deployment config not found: {deployment_config_id}")
# Get current instances # Get current instances
current_instances = self.session.exec( current_instances = self.session.execute(
select(AgentDeploymentInstance).where( select(AgentDeploymentInstance).where(
AgentDeploymentInstance.deployment_id == deployment_config_id AgentDeploymentInstance.deployment_id == deployment_config_id
) )
@@ -767,7 +767,7 @@ class AgentDeploymentManager:
} }
# Get current instances # Get current instances
current_instances = self.session.exec( current_instances = self.session.execute(
select(AgentDeploymentInstance).where( select(AgentDeploymentInstance).where(
AgentDeploymentInstance.deployment_id == deployment_config_id AgentDeploymentInstance.deployment_id == deployment_config_id
) )
@@ -846,7 +846,7 @@ class AgentMonitoringManager:
raise ValueError(f"Deployment config not found: {deployment_config_id}") raise ValueError(f"Deployment config not found: {deployment_config_id}")
# Get deployment instances # Get deployment instances
instances = self.session.exec( instances = self.session.execute(
select(AgentDeploymentInstance).where( select(AgentDeploymentInstance).where(
AgentDeploymentInstance.deployment_id == deployment_config_id AgentDeploymentInstance.deployment_id == deployment_config_id
) )

View File

@@ -91,7 +91,7 @@ class MetaLearningEngine:
async def train_meta_model(self, session: Session, model_id: str) -> Dict[str, Any]: async def train_meta_model(self, session: Session, model_id: str) -> Dict[str, Any]:
"""Train a meta-learning model""" """Train a meta-learning model"""
model = session.exec( model = session.execute(
select(MetaLearningModel).where(MetaLearningModel.model_id == model_id) select(MetaLearningModel).where(MetaLearningModel.model_id == model_id)
).first() ).first()
@@ -194,7 +194,7 @@ class MetaLearningEngine:
) -> Dict[str, Any]: ) -> Dict[str, Any]:
"""Adapt meta-learning model to new task""" """Adapt meta-learning model to new task"""
model = session.exec( model = session.execute(
select(MetaLearningModel).where(MetaLearningModel.model_id == model_id) select(MetaLearningModel).where(MetaLearningModel.model_id == model_id)
).first() ).first()
@@ -1003,7 +1003,7 @@ class AgentPerformanceService:
) -> AgentPerformanceProfile: ) -> AgentPerformanceProfile:
"""Update agent performance metrics""" """Update agent performance metrics"""
profile = self.session.exec( profile = self.session.execute(
select(AgentPerformanceProfile).where(AgentPerformanceProfile.agent_id == agent_id) select(AgentPerformanceProfile).where(AgentPerformanceProfile.agent_id == agent_id)
).first() ).first()
@@ -1089,7 +1089,7 @@ class AgentPerformanceService:
) -> Dict[str, Any]: ) -> Dict[str, Any]:
"""Get comprehensive agent performance profile""" """Get comprehensive agent performance profile"""
profile = self.session.exec( profile = self.session.execute(
select(AgentPerformanceProfile).where(AgentPerformanceProfile.agent_id == agent_id) select(AgentPerformanceProfile).where(AgentPerformanceProfile.agent_id == agent_id)
).first() ).first()

View File

@@ -77,7 +77,7 @@ class AgentPortfolioManager:
raise HTTPException(status_code=400, detail="Invalid agent address") raise HTTPException(status_code=400, detail="Invalid agent address")
# Check if portfolio already exists # Check if portfolio already exists
existing_portfolio = self.session.exec( existing_portfolio = self.session.execute(
select(AgentPortfolio).where( select(AgentPortfolio).where(
AgentPortfolio.agent_address == agent_address AgentPortfolio.agent_address == agent_address
) )
@@ -289,7 +289,7 @@ class AgentPortfolioManager:
) )
# Update risk metrics in database # Update risk metrics in database
existing_metrics = self.session.exec( existing_metrics = self.session.execute(
select(RiskMetrics).where(RiskMetrics.portfolio_id == portfolio.id) select(RiskMetrics).where(RiskMetrics.portfolio_id == portfolio.id)
).first() ).first()
@@ -382,7 +382,7 @@ class AgentPortfolioManager:
def _get_agent_portfolio(self, agent_address: str) -> AgentPortfolio: def _get_agent_portfolio(self, agent_address: str) -> AgentPortfolio:
"""Get portfolio for agent address""" """Get portfolio for agent address"""
portfolio = self.session.exec( portfolio = self.session.execute(
select(AgentPortfolio).where( select(AgentPortfolio).where(
AgentPortfolio.agent_address == agent_address AgentPortfolio.agent_address == agent_address
) )
@@ -456,7 +456,7 @@ class AgentPortfolioManager:
"""Validate trade request""" """Validate trade request"""
# Check if sell token exists in portfolio # Check if sell token exists in portfolio
sell_asset = self.session.exec( sell_asset = self.session.execute(
select(PortfolioAsset).where( select(PortfolioAsset).where(
PortfolioAsset.portfolio_id == portfolio.id, PortfolioAsset.portfolio_id == portfolio.id,
PortfolioAsset.token_symbol == trade_request.sell_token PortfolioAsset.token_symbol == trade_request.sell_token
@@ -507,7 +507,7 @@ class AgentPortfolioManager:
"""Update portfolio assets after trade""" """Update portfolio assets after trade"""
# Update sell asset # Update sell asset
sell_asset = self.session.exec( sell_asset = self.session.execute(
select(PortfolioAsset).where( select(PortfolioAsset).where(
PortfolioAsset.portfolio_id == portfolio.id, PortfolioAsset.portfolio_id == portfolio.id,
PortfolioAsset.token_symbol == trade.sell_token PortfolioAsset.token_symbol == trade.sell_token
@@ -519,7 +519,7 @@ class AgentPortfolioManager:
sell_asset.updated_at = datetime.utcnow() sell_asset.updated_at = datetime.utcnow()
# Update buy asset # Update buy asset
buy_asset = self.session.exec( buy_asset = self.session.execute(
select(PortfolioAsset).where( select(PortfolioAsset).where(
PortfolioAsset.portfolio_id == portfolio.id, PortfolioAsset.portfolio_id == portfolio.id,
PortfolioAsset.token_symbol == trade.buy_token PortfolioAsset.token_symbol == trade.buy_token
@@ -547,7 +547,7 @@ class AgentPortfolioManager:
portfolio_value = await self._calculate_portfolio_value(portfolio) portfolio_value = await self._calculate_portfolio_value(portfolio)
# Update current allocations # Update current allocations
assets = self.session.exec( assets = self.session.execute(
select(PortfolioAsset).where( select(PortfolioAsset).where(
PortfolioAsset.portfolio_id == portfolio.id PortfolioAsset.portfolio_id == portfolio.id
) )
@@ -566,7 +566,7 @@ class AgentPortfolioManager:
async def _calculate_portfolio_value(self, portfolio: AgentPortfolio) -> float: async def _calculate_portfolio_value(self, portfolio: AgentPortfolio) -> float:
"""Calculate total portfolio value""" """Calculate total portfolio value"""
assets = self.session.exec( assets = self.session.execute(
select(PortfolioAsset).where( select(PortfolioAsset).where(
PortfolioAsset.portfolio_id == portfolio.id PortfolioAsset.portfolio_id == portfolio.id
) )
@@ -593,7 +593,7 @@ class AgentPortfolioManager:
return True return True
# Check threshold-based rebalancing # Check threshold-based rebalancing
assets = self.session.exec( assets = self.session.execute(
select(PortfolioAsset).where( select(PortfolioAsset).where(
PortfolioAsset.portfolio_id == portfolio.id PortfolioAsset.portfolio_id == portfolio.id
) )
@@ -615,7 +615,7 @@ class AgentPortfolioManager:
"""Generate rebalancing trades""" """Generate rebalancing trades"""
trades = [] trades = []
assets = self.session.exec( assets = self.session.execute(
select(PortfolioAsset).where( select(PortfolioAsset).where(
PortfolioAsset.portfolio_id == portfolio.id PortfolioAsset.portfolio_id == portfolio.id
) )
@@ -657,7 +657,7 @@ class AgentPortfolioManager:
"""Calculate portfolio performance metrics""" """Calculate portfolio performance metrics"""
# Get historical trades # Get historical trades
trades = self.session.exec( trades = self.session.execute(
select(PortfolioTrade) select(PortfolioTrade)
.where(PortfolioTrade.portfolio_id == portfolio.id) .where(PortfolioTrade.portfolio_id == portfolio.id)
.order_by(PortfolioTrade.executed_at.desc()) .order_by(PortfolioTrade.executed_at.desc())

View File

@@ -379,7 +379,7 @@ class AgentTrustManager:
"""Update trust score based on execution results""" """Update trust score based on execution results"""
# Get or create trust score record # Get or create trust score record
trust_score = self.session.exec( trust_score = self.session.execute(
select(AgentTrustScore).where( select(AgentTrustScore).where(
(AgentTrustScore.entity_type == entity_type) & (AgentTrustScore.entity_type == entity_type) &
(AgentTrustScore.entity_id == entity_id) (AgentTrustScore.entity_id == entity_id)
@@ -677,7 +677,7 @@ class AgentSandboxManager:
"""Monitor sandbox execution for security violations""" """Monitor sandbox execution for security violations"""
# Get sandbox configuration # Get sandbox configuration
sandbox = self.session.exec( sandbox = self.session.execute(
select(AgentSandboxConfig).where( select(AgentSandboxConfig).where(
AgentSandboxConfig.id == f"sandbox_{execution_id}" AgentSandboxConfig.id == f"sandbox_{execution_id}"
) )
@@ -716,7 +716,7 @@ class AgentSandboxManager:
try: try:
# Get sandbox record # Get sandbox record
sandbox = self.session.exec( sandbox = self.session.execute(
select(AgentSandboxConfig).where( select(AgentSandboxConfig).where(
AgentSandboxConfig.id == f"sandbox_{execution_id}" AgentSandboxConfig.id == f"sandbox_{execution_id}"
) )

View File

@@ -95,7 +95,7 @@ class AgentStateManager:
.where(AgentStep.workflow_id == workflow_id) .where(AgentStep.workflow_id == workflow_id)
.order_by(AgentStep.step_order) .order_by(AgentStep.step_order)
) )
return self.session.exec(stmt).all() return self.session.execute(stmt).all()
async def create_step_execution( async def create_step_execution(
self, self,

View File

@@ -177,7 +177,7 @@ class AMMService:
pool.updated_at = datetime.utcnow() pool.updated_at = datetime.utcnow()
# Update or create liquidity position # Update or create liquidity position
position = self.session.exec( position = self.session.execute(
select(LiquidityPosition).where( select(LiquidityPosition).where(
LiquidityPosition.pool_id == pool.id, LiquidityPosition.pool_id == pool.id,
LiquidityPosition.provider_address == provider_address LiquidityPosition.provider_address == provider_address
@@ -228,7 +228,7 @@ class AMMService:
pool = await self._get_pool_by_id(liquidity_request.pool_id) pool = await self._get_pool_by_id(liquidity_request.pool_id)
# Get liquidity position # Get liquidity position
position = self.session.exec( position = self.session.execute(
select(LiquidityPosition).where( select(LiquidityPosition).where(
LiquidityPosition.pool_id == pool.id, LiquidityPosition.pool_id == pool.id,
LiquidityPosition.provider_address == provider_address LiquidityPosition.provider_address == provider_address
@@ -447,7 +447,7 @@ class AMMService:
daily_reward = 100 * incentive_multiplier # Base $100 per day, adjusted by multiplier daily_reward = 100 * incentive_multiplier # Base $100 per day, adjusted by multiplier
# Create or update incentive program # Create or update incentive program
existing_program = self.session.exec( existing_program = self.session.execute(
select(IncentiveProgram).where(IncentiveProgram.pool_id == pool_id) select(IncentiveProgram).where(IncentiveProgram.pool_id == pool_id)
).first() ).first()
@@ -498,7 +498,7 @@ class AMMService:
"""Get all liquidity positions for a user""" """Get all liquidity positions for a user"""
try: try:
positions = self.session.exec( positions = self.session.execute(
select(LiquidityPosition).where( select(LiquidityPosition).where(
LiquidityPosition.provider_address == user_address LiquidityPosition.provider_address == user_address
) )
@@ -521,7 +521,7 @@ class AMMService:
async def _get_existing_pool(self, token_a: str, token_b: str) -> Optional[LiquidityPool]: async def _get_existing_pool(self, token_a: str, token_b: str) -> Optional[LiquidityPool]:
"""Check if pool exists for token pair""" """Check if pool exists for token pair"""
pool = self.session.exec( pool = self.session.execute(
select(LiquidityPool).where( select(LiquidityPool).where(
( (
(LiquidityPool.token_a == token_a) & (LiquidityPool.token_a == token_a) &
@@ -694,13 +694,13 @@ class AMMService:
"""Update pool metrics""" """Update pool metrics"""
# Get existing metrics # Get existing metrics
metrics = self.session.exec( metrics = self.session.execute(
select(PoolMetrics).where(PoolMetrics.pool_id == pool.id) select(PoolMetrics).where(PoolMetrics.pool_id == pool.id)
).first() ).first()
if not metrics: if not metrics:
await self._initialize_pool_metrics(pool) await self._initialize_pool_metrics(pool)
metrics = self.session.exec( metrics = self.session.execute(
select(PoolMetrics).where(PoolMetrics.pool_id == pool.id) select(PoolMetrics).where(PoolMetrics.pool_id == pool.id)
).first() ).first()
@@ -734,20 +734,20 @@ class AMMService:
async def _get_pool_metrics(self, pool: LiquidityPool) -> PoolMetrics: async def _get_pool_metrics(self, pool: LiquidityPool) -> PoolMetrics:
"""Get comprehensive pool metrics""" """Get comprehensive pool metrics"""
metrics = self.session.exec( metrics = self.session.execute(
select(PoolMetrics).where(PoolMetrics.pool_id == pool.id) select(PoolMetrics).where(PoolMetrics.pool_id == pool.id)
).first() ).first()
if not metrics: if not metrics:
await self._initialize_pool_metrics(pool) await self._initialize_pool_metrics(pool)
metrics = self.session.exec( metrics = self.session.execute(
select(PoolMetrics).where(PoolMetrics.pool_id == pool.id) select(PoolMetrics).where(PoolMetrics.pool_id == pool.id)
).first() ).first()
# Calculate 24h volume and fees # Calculate 24h volume and fees
twenty_four_hours_ago = datetime.utcnow() - timedelta(hours=24) twenty_four_hours_ago = datetime.utcnow() - timedelta(hours=24)
recent_swaps = self.session.exec( recent_swaps = self.session.execute(
select(SwapTransaction).where( select(SwapTransaction).where(
SwapTransaction.pool_id == pool.id, SwapTransaction.pool_id == pool.id,
SwapTransaction.executed_at >= twenty_four_hours_ago SwapTransaction.executed_at >= twenty_four_hours_ago

View File

@@ -424,7 +424,7 @@ class AnalyticsEngine:
insights = [] insights = []
# Get metrics for analysis # Get metrics for analysis
metrics = session.exec( metrics = session.execute(
select(MarketMetric).where( select(MarketMetric).where(
and_( and_(
MarketMetric.period_type == period_type, MarketMetric.period_type == period_type,
@@ -1068,7 +1068,7 @@ class MarketplaceAnalytics:
end_time = datetime.utcnow() end_time = datetime.utcnow()
start_time = end_time - timedelta(days=1) start_time = end_time - timedelta(days=1)
metrics = self.session.exec( metrics = self.session.execute(
select(MarketMetric).where( select(MarketMetric).where(
and_( and_(
MarketMetric.period_type == AnalyticsPeriod.DAILY, MarketMetric.period_type == AnalyticsPeriod.DAILY,
@@ -1079,14 +1079,14 @@ class MarketplaceAnalytics:
).all() ).all()
# Get recent insights # Get recent insights
recent_insights = self.session.exec( recent_insights = self.session.execute(
select(MarketInsight).where( select(MarketInsight).where(
MarketInsight.created_at >= start_time MarketInsight.created_at >= start_time
).order_by(MarketInsight.created_at.desc()).limit(10) ).order_by(MarketInsight.created_at.desc()).limit(10)
).all() ).all()
# Get active alerts # Get active alerts
active_alerts = self.session.exec( active_alerts = self.session.execute(
select(AnalyticsAlert).where( select(AnalyticsAlert).where(
and_( and_(
AnalyticsAlert.status == "active", AnalyticsAlert.status == "active",

View File

@@ -82,7 +82,7 @@ class AtomicSwapService:
async def get_agent_swaps(self, agent_id: str) -> List[AtomicSwapOrder]: async def get_agent_swaps(self, agent_id: str) -> List[AtomicSwapOrder]:
"""Get all swaps where the agent is either initiator or participant""" """Get all swaps where the agent is either initiator or participant"""
return self.session.exec( return self.session.execute(
select(AtomicSwapOrder).where( select(AtomicSwapOrder).where(
(AtomicSwapOrder.initiator_agent_id == agent_id) | (AtomicSwapOrder.initiator_agent_id == agent_id) |
(AtomicSwapOrder.participant_agent_id == agent_id) (AtomicSwapOrder.participant_agent_id == agent_id)

View File

@@ -207,7 +207,7 @@ class CertificationSystem:
} }
# Check if agent has the prerequisite certification # Check if agent has the prerequisite certification
certification = session.exec( certification = session.execute(
select(AgentCertification).where( select(AgentCertification).where(
and_( and_(
AgentCertification.agent_id == agent_id, AgentCertification.agent_id == agent_id,
@@ -244,7 +244,7 @@ class CertificationSystem:
# For now, assume all agents have basic identity verification # For now, assume all agents have basic identity verification
# Check if agent has any reputation record (indicates identity verification) # Check if agent has any reputation record (indicates identity verification)
reputation = session.exec( reputation = session.execute(
select(AgentReputation).where(AgentReputation.agent_id == agent_id) select(AgentReputation).where(AgentReputation.agent_id == agent_id)
).first() ).first()
@@ -271,7 +271,7 @@ class CertificationSystem:
"""Verify agent performance metrics""" """Verify agent performance metrics"""
# Get agent reputation for performance metrics # Get agent reputation for performance metrics
reputation = session.exec( reputation = session.execute(
select(AgentReputation).where(AgentReputation.agent_id == agent_id) select(AgentReputation).where(AgentReputation.agent_id == agent_id)
).first() ).first()
@@ -366,7 +366,7 @@ class CertificationSystem:
async def verify_reliability(self, session: Session, agent_id: str) -> Dict[str, Any]: async def verify_reliability(self, session: Session, agent_id: str) -> Dict[str, Any]:
"""Verify agent reliability and consistency""" """Verify agent reliability and consistency"""
reputation = session.exec( reputation = session.execute(
select(AgentReputation).where(AgentReputation.agent_id == agent_id) select(AgentReputation).where(AgentReputation.agent_id == agent_id)
).first() ).first()
@@ -428,7 +428,7 @@ class CertificationSystem:
# Mock security verification - in real system would check security audits # Mock security verification - in real system would check security audits
# For now, assume agents with high trust scores have basic security # For now, assume agents with high trust scores have basic security
reputation = session.exec( reputation = session.execute(
select(AgentReputation).where(AgentReputation.agent_id == agent_id) select(AgentReputation).where(AgentReputation.agent_id == agent_id)
).first() ).first()
@@ -479,7 +479,7 @@ class CertificationSystem:
# Mock compliance verification - in real system would check regulatory compliance # Mock compliance verification - in real system would check regulatory compliance
# For now, assume agents with certifications are compliant # For now, assume agents with certifications are compliant
certifications = session.exec( certifications = session.execute(
select(AgentCertification).where( select(AgentCertification).where(
and_( and_(
AgentCertification.agent_id == agent_id, AgentCertification.agent_id == agent_id,
@@ -513,7 +513,7 @@ class CertificationSystem:
async def verify_capability(self, session: Session, agent_id: str) -> Dict[str, Any]: async def verify_capability(self, session: Session, agent_id: str) -> Dict[str, Any]:
"""Verify agent capabilities and specializations""" """Verify agent capabilities and specializations"""
reputation = session.exec( reputation = session.execute(
select(AgentReputation).where(AgentReputation.agent_id == agent_id) select(AgentReputation).where(AgentReputation.agent_id == agent_id)
).first() ).first()
@@ -608,7 +608,7 @@ class CertificationSystem:
) -> Tuple[bool, Optional[str]]: ) -> Tuple[bool, Optional[str]]:
"""Renew an existing certification""" """Renew an existing certification"""
certification = session.exec( certification = session.execute(
select(AgentCertification).where(AgentCertification.certification_id == certification_id) select(AgentCertification).where(AgentCertification.certification_id == certification_id)
).first() ).first()
@@ -753,7 +753,7 @@ class PartnershipManager:
"""Apply for partnership program""" """Apply for partnership program"""
# Get program details # Get program details
program = session.exec( program = session.execute(
select(PartnershipProgram).where(PartnershipProgram.program_id == program_id) select(PartnershipProgram).where(PartnershipProgram.program_id == program_id)
).first() ).first()
@@ -846,7 +846,7 @@ class PartnershipManager:
async def check_technical_capability(self, session: Session, agent_id: str) -> Dict[str, Any]: async def check_technical_capability(self, session: Session, agent_id: str) -> Dict[str, Any]:
"""Check technical capability requirement""" """Check technical capability requirement"""
reputation = session.exec( reputation = session.execute(
select(AgentReputation).where(AgentReputation.agent_id == agent_id) select(AgentReputation).where(AgentReputation.agent_id == agent_id)
).first() ).first()
@@ -884,7 +884,7 @@ class PartnershipManager:
# Mock integration readiness check # Mock integration readiness check
# In real system would check API integration capabilities, technical infrastructure # In real system would check API integration capabilities, technical infrastructure
reputation = session.exec( reputation = session.execute(
select(AgentReputation).where(AgentReputation.agent_id == agent_id) select(AgentReputation).where(AgentReputation.agent_id == agent_id)
).first() ).first()
@@ -916,7 +916,7 @@ class PartnershipManager:
async def check_service_quality(self, session: Session, agent_id: str) -> Dict[str, Any]: async def check_service_quality(self, session: Session, agent_id: str) -> Dict[str, Any]:
"""Check service quality requirement""" """Check service quality requirement"""
reputation = session.exec( reputation = session.execute(
select(AgentReputation).where(AgentReputation.agent_id == agent_id) select(AgentReputation).where(AgentReputation.agent_id == agent_id)
).first() ).first()
@@ -951,7 +951,7 @@ class PartnershipManager:
# Mock customer support check # Mock customer support check
# In real system would check support response times, customer satisfaction # In real system would check support response times, customer satisfaction
reputation = session.exec( reputation = session.execute(
select(AgentReputation).where(AgentReputation.agent_id == agent_id) select(AgentReputation).where(AgentReputation.agent_id == agent_id)
).first() ).first()
@@ -986,7 +986,7 @@ class PartnershipManager:
# Mock sales capability check # Mock sales capability check
# In real system would check sales history, customer acquisition, revenue # In real system would check sales history, customer acquisition, revenue
reputation = session.exec( reputation = session.execute(
select(AgentReputation).where(AgentReputation.agent_id == agent_id) select(AgentReputation).where(AgentReputation.agent_id == agent_id)
).first() ).first()
@@ -1021,7 +1021,7 @@ class PartnershipManager:
# Mock market presence check # Mock market presence check
# In real system would check market share, brand recognition, geographic reach # In real system would check market share, brand recognition, geographic reach
reputation = session.exec( reputation = session.execute(
select(AgentReputation).where(AgentReputation.agent_id == agent_id) select(AgentReputation).where(AgentReputation.agent_id == agent_id)
).first() ).first()
@@ -1062,7 +1062,7 @@ class PartnershipManager:
# Mock development resources check # Mock development resources check
# In real system would check team size, technical infrastructure, development capacity # In real system would check team size, technical infrastructure, development capacity
reputation = session.exec( reputation = session.execute(
select(AgentReputation).where(AgentReputation.agent_id == agent_id) select(AgentReputation).where(AgentReputation.agent_id == agent_id)
).first() ).first()
@@ -1098,7 +1098,7 @@ class PartnershipManager:
# Mock market leader check # Mock market leader check
# In real system would check market share, industry influence, thought leadership # In real system would check market share, industry influence, thought leadership
reputation = session.exec( reputation = session.execute(
select(AgentReputation).where(AgentReputation.agent_id == agent_id) select(AgentReputation).where(AgentReputation.agent_id == agent_id)
).first() ).first()
@@ -1151,7 +1151,7 @@ class PartnershipManager:
# Mock marketing capability check # Mock marketing capability check
# In real system would check marketing materials, brand presence, outreach capabilities # In real system would check marketing materials, brand presence, outreach capabilities
reputation = session.exec( reputation = session.execute(
select(AgentReputation).where(AgentReputation.agent_id == agent_id) select(AgentReputation).where(AgentReputation.agent_id == agent_id)
).first() ).first()
@@ -1187,7 +1187,7 @@ class PartnershipManager:
# Mock audience reach check # Mock audience reach check
# In real system would check audience size, engagement metrics, reach demographics # In real system would check audience size, engagement metrics, reach demographics
reputation = session.exec( reputation = session.execute(
select(AgentReputation).where(AgentReputation.agent_id == agent_id) select(AgentReputation).where(AgentReputation.agent_id == agent_id)
).first() ).first()
@@ -1300,7 +1300,7 @@ class BadgeSystem:
"""Award a badge to an agent""" """Award a badge to an agent"""
# Get badge details # Get badge details
badge = session.exec( badge = session.execute(
select(AchievementBadge).where(AchievementBadge.badge_id == badge_id) select(AchievementBadge).where(AchievementBadge.badge_id == badge_id)
).first() ).first()
@@ -1314,7 +1314,7 @@ class BadgeSystem:
return False, None, "Badge has reached maximum awards" return False, None, "Badge has reached maximum awards"
# Check if agent already has this badge # Check if agent already has this badge
existing_badge = session.exec( existing_badge = session.execute(
select(AgentBadge).where( select(AgentBadge).where(
and_( and_(
AgentBadge.agent_id == agent_id, AgentBadge.agent_id == agent_id,
@@ -1362,7 +1362,7 @@ class BadgeSystem:
"""Verify if agent is eligible for a badge""" """Verify if agent is eligible for a badge"""
# Get agent reputation data # Get agent reputation data
reputation = session.exec( reputation = session.execute(
select(AgentReputation).where(AgentReputation.agent_id == agent_id) select(AgentReputation).where(AgentReputation.agent_id == agent_id)
).first() ).first()
@@ -1449,7 +1449,7 @@ class BadgeSystem:
awarded_badges = [] awarded_badges = []
# Get all active automatic badges # Get all active automatic badges
automatic_badges = session.exec( automatic_badges = session.execute(
select(AchievementBadge).where( select(AchievementBadge).where(
and_( and_(
AchievementBadge.is_active == True, AchievementBadge.is_active == True,
@@ -1464,7 +1464,7 @@ class BadgeSystem:
if eligibility_result['eligible']: if eligibility_result['eligible']:
# Check if already awarded # Check if already awarded
existing = session.exec( existing = session.execute(
select(AgentBadge).where( select(AgentBadge).where(
and_( and_(
AgentBadge.agent_id == agent_id, AgentBadge.agent_id == agent_id,
@@ -1505,22 +1505,22 @@ class CertificationAndPartnershipService:
"""Get comprehensive certification summary for an agent""" """Get comprehensive certification summary for an agent"""
# Get certifications # Get certifications
certifications = self.session.exec( certifications = self.session.execute(
select(AgentCertification).where(AgentCertification.agent_id == agent_id) select(AgentCertification).where(AgentCertification.agent_id == agent_id)
).all() ).all()
# Get partnerships # Get partnerships
partnerships = self.session.exec( partnerships = self.session.execute(
select(AgentPartnership).where(AgentPartnership.agent_id == agent_id) select(AgentPartnership).where(AgentPartnership.agent_id == agent_id)
).all() ).all()
# Get badges # Get badges
badges = self.session.exec( badges = self.session.execute(
select(AgentBadge).where(AgentBadge.agent_id == agent_id) select(AgentBadge).where(AgentBadge.agent_id == agent_id)
).all() ).all()
# Get verification records # Get verification records
verifications = self.session.exec( verifications = self.session.execute(
select(VerificationRecord).where(VerificationRecord.agent_id == agent_id) select(VerificationRecord).where(VerificationRecord.agent_id == agent_id)
).all() ).all()
@@ -1585,7 +1585,7 @@ class CertificationAndPartnershipService:
def get_badge_point_value(self, badge_id: str) -> int: def get_badge_point_value(self, badge_id: str) -> int:
"""Get point value for a badge""" """Get point value for a badge"""
badge = self.session.exec( badge = self.session.execute(
select(AchievementBadge).where(AchievementBadge.badge_id == badge_id) select(AchievementBadge).where(AchievementBadge.badge_id == badge_id)
).first() ).first()

View File

@@ -37,7 +37,7 @@ class DeveloperEcosystemService:
async def get_developer_profile(self, developer_id: str) -> Optional[DeveloperProfile]: async def get_developer_profile(self, developer_id: str) -> Optional[DeveloperProfile]:
"""Get developer profile by ID""" """Get developer profile by ID"""
return self.session.exec( return self.session.execute(
select(DeveloperProfile).where(DeveloperProfile.developer_id == developer_id) select(DeveloperProfile).where(DeveloperProfile.developer_id == developer_id)
).first() ).first()
@@ -118,7 +118,7 @@ class ThirdPartySolutionService:
# Filtering by JSON column capability (simplified) # Filtering by JSON column capability (simplified)
# In a real app, we might use PostgreSQL specific operators # In a real app, we might use PostgreSQL specific operators
solutions = self.session.exec(query.limit(limit)).all() solutions = self.session.execute(query.limit(limit)).all()
if category: if category:
solutions = [s for s in solutions if category in s.capabilities] solutions = [s for s in solutions if category in s.capabilities]
@@ -127,7 +127,7 @@ class ThirdPartySolutionService:
async def purchase_solution(self, buyer_id: str, solution_id: str) -> Dict[str, Any]: async def purchase_solution(self, buyer_id: str, solution_id: str) -> Dict[str, Any]:
"""Purchase or download a third-party solution""" """Purchase or download a third-party solution"""
solution = self.session.exec( solution = self.session.execute(
select(AgentSolution).where(AgentSolution.solution_id == solution_id) select(AgentSolution).where(AgentSolution.solution_id == solution_id)
).first() ).first()
@@ -140,7 +140,7 @@ class ThirdPartySolutionService:
# Update developer earnings if paid # Update developer earnings if paid
if solution.price_amount > 0: if solution.price_amount > 0:
dev = self.session.exec( dev = self.session.execute(
select(DeveloperProfile).where(DeveloperProfile.developer_id == solution.developer_id) select(DeveloperProfile).where(DeveloperProfile.developer_id == solution.developer_id)
).first() ).first()
if dev: if dev:
@@ -181,7 +181,7 @@ class InnovationLabService:
async def join_lab(self, lab_id: str, developer_id: str) -> InnovationLab: async def join_lab(self, lab_id: str, developer_id: str) -> InnovationLab:
"""Join an active innovation lab""" """Join an active innovation lab"""
lab = self.session.exec(select(InnovationLab).where(InnovationLab.lab_id == lab_id)).first() lab = self.session.execute(select(InnovationLab).where(InnovationLab.lab_id == lab_id)).first()
if not lab: if not lab:
raise ValueError("Lab not found") raise ValueError("Lab not found")
@@ -196,7 +196,7 @@ class InnovationLabService:
async def fund_lab(self, lab_id: str, amount: float) -> InnovationLab: async def fund_lab(self, lab_id: str, amount: float) -> InnovationLab:
"""Provide funding to an innovation lab""" """Provide funding to an innovation lab"""
lab = self.session.exec(select(InnovationLab).where(InnovationLab.lab_id == lab_id)).first() lab = self.session.execute(select(InnovationLab).where(InnovationLab.lab_id == lab_id)).first()
if not lab: if not lab:
raise ValueError("Lab not found") raise ValueError("Lab not found")
@@ -245,11 +245,11 @@ class CommunityPlatformService:
query = query.where(CommunityPost.category == category) query = query.where(CommunityPost.category == category)
query = query.order_by(CommunityPost.created_at.desc()).limit(limit) query = query.order_by(CommunityPost.created_at.desc()).limit(limit)
return self.session.exec(query).all() return self.session.execute(query).all()
async def upvote_post(self, post_id: str) -> CommunityPost: async def upvote_post(self, post_id: str) -> CommunityPost:
"""Upvote a post and reward the author""" """Upvote a post and reward the author"""
post = self.session.exec(select(CommunityPost).where(CommunityPost.post_id == post_id)).first() post = self.session.execute(select(CommunityPost).where(CommunityPost.post_id == post_id)).first()
if not post: if not post:
raise ValueError("Post not found") raise ValueError("Post not found")
@@ -267,7 +267,7 @@ class CommunityPlatformService:
async def create_hackathon(self, organizer_id: str, data: Dict[str, Any]) -> Hackathon: async def create_hackathon(self, organizer_id: str, data: Dict[str, Any]) -> Hackathon:
"""Create a new agent innovation hackathon""" """Create a new agent innovation hackathon"""
# Verify organizer is an expert or partner # Verify organizer is an expert or partner
dev = self.session.exec(select(DeveloperProfile).where(DeveloperProfile.developer_id == organizer_id)).first() dev = self.session.execute(select(DeveloperProfile).where(DeveloperProfile.developer_id == organizer_id)).first()
if not dev or dev.tier not in [DeveloperTier.EXPERT, DeveloperTier.MASTER, DeveloperTier.PARTNER]: if not dev or dev.tier not in [DeveloperTier.EXPERT, DeveloperTier.MASTER, DeveloperTier.PARTNER]:
raise ValueError("Only high-tier developers can organize hackathons") raise ValueError("Only high-tier developers can organize hackathons")
@@ -290,7 +290,7 @@ class CommunityPlatformService:
async def register_for_hackathon(self, hackathon_id: str, developer_id: str) -> Hackathon: async def register_for_hackathon(self, hackathon_id: str, developer_id: str) -> Hackathon:
"""Register a developer for a hackathon""" """Register a developer for a hackathon"""
hackathon = self.session.exec(select(Hackathon).where(Hackathon.hackathon_id == hackathon_id)).first() hackathon = self.session.execute(select(Hackathon).where(Hackathon.hackathon_id == hackathon_id)).first()
if not hackathon: if not hackathon:
raise ValueError("Hackathon not found") raise ValueError("Hackathon not found")

View File

@@ -98,7 +98,7 @@ class CreativityEnhancementEngine:
) -> Dict[str, Any]: ) -> Dict[str, Any]:
"""Enhance a specific creative capability""" """Enhance a specific creative capability"""
capability = session.exec( capability = session.execute(
select(CreativeCapability).where(CreativeCapability.capability_id == capability_id) select(CreativeCapability).where(CreativeCapability.capability_id == capability_id)
).first() ).first()
@@ -245,7 +245,7 @@ class CreativityEnhancementEngine:
) -> Dict[str, Any]: ) -> Dict[str, Any]:
"""Evaluate a creative output and update capability""" """Evaluate a creative output and update capability"""
capability = session.exec( capability = session.execute(
select(CreativeCapability).where(CreativeCapability.capability_id == capability_id) select(CreativeCapability).where(CreativeCapability.capability_id == capability_id)
).first() ).first()
@@ -469,7 +469,7 @@ class CrossDomainCreativeIntegrator:
"""Synthesize concepts from multiple domains to create novel outputs""" """Synthesize concepts from multiple domains to create novel outputs"""
# Verify agent has capabilities in these domains # Verify agent has capabilities in these domains
capabilities = session.exec( capabilities = session.execute(
select(CreativeCapability).where( select(CreativeCapability).where(
and_( and_(
CreativeCapability.agent_id == agent_id, CreativeCapability.agent_id == agent_id,

View File

@@ -303,7 +303,7 @@ class CrossChainBridgeService:
) )
# Check if already confirmed by this validator # Check if already confirmed by this validator
existing_confirmation = self.session.exec( existing_confirmation = self.session.execute(
select(BridgeTransaction).where( select(BridgeTransaction).where(
BridgeTransaction.bridge_request_id == bridge_request.id, BridgeTransaction.bridge_request_id == bridge_request.id,
BridgeTransaction.validator_address == validator_address, BridgeTransaction.validator_address == validator_address,
@@ -567,7 +567,7 @@ class CrossChainBridgeService:
async def _get_supported_token(self, token_address: str) -> Optional[SupportedToken]: async def _get_supported_token(self, token_address: str) -> Optional[SupportedToken]:
"""Get supported token configuration""" """Get supported token configuration"""
return self.session.exec( return self.session.execute(
select(SupportedToken).where( select(SupportedToken).where(
SupportedToken.token_address == token_address SupportedToken.token_address == token_address
) )
@@ -575,7 +575,7 @@ class CrossChainBridgeService:
async def _get_chain_config(self, chain_id: int) -> Optional[ChainConfig]: async def _get_chain_config(self, chain_id: int) -> Optional[ChainConfig]:
"""Get chain configuration""" """Get chain configuration"""
return self.session.exec( return self.session.execute(
select(ChainConfig).where( select(ChainConfig).where(
ChainConfig.chain_id == chain_id ChainConfig.chain_id == chain_id
) )
@@ -609,7 +609,7 @@ class CrossChainBridgeService:
async def _get_bridge_confirmations(self, request_id: int) -> List[Dict]: async def _get_bridge_confirmations(self, request_id: int) -> List[Dict]:
"""Get bridge confirmations""" """Get bridge confirmations"""
confirmations = self.session.exec( confirmations = self.session.execute(
select(BridgeTransaction).where( select(BridgeTransaction).where(
BridgeTransaction.bridge_request_id == request_id, BridgeTransaction.bridge_request_id == request_id,
BridgeTransaction.transaction_type == "confirmation" BridgeTransaction.transaction_type == "confirmation"
@@ -628,7 +628,7 @@ class CrossChainBridgeService:
async def _get_bridge_transactions(self, request_id: int) -> List[Dict]: async def _get_bridge_transactions(self, request_id: int) -> List[Dict]:
"""Get all bridge transactions""" """Get all bridge transactions"""
transactions = self.session.exec( transactions = self.session.execute(
select(BridgeTransaction).where( select(BridgeTransaction).where(
BridgeTransaction.bridge_request_id == request_id BridgeTransaction.bridge_request_id == request_id
) )
@@ -723,7 +723,7 @@ class CrossChainBridgeService:
async def _get_validator(self, validator_address: str) -> Optional[Validator]: async def _get_validator(self, validator_address: str) -> Optional[Validator]:
"""Get validator information""" """Get validator information"""
return self.session.exec( return self.session.execute(
select(Validator).where( select(Validator).where(
Validator.validator_address == validator_address Validator.validator_address == validator_address
) )
@@ -743,7 +743,7 @@ class CrossChainBridgeService:
async def _count_confirmations(self, request_id: int) -> int: async def _count_confirmations(self, request_id: int) -> int:
"""Count confirmations for bridge request""" """Count confirmations for bridge request"""
confirmations = self.session.exec( confirmations = self.session.execute(
select(BridgeTransaction).where( select(BridgeTransaction).where(
BridgeTransaction.bridge_request_id == request_id, BridgeTransaction.bridge_request_id == request_id,
BridgeTransaction.transaction_type == "confirmation" BridgeTransaction.transaction_type == "confirmation"

View File

@@ -194,7 +194,7 @@ class CrossChainBridgeService:
stmt = select(BridgeRequest).where( stmt = select(BridgeRequest).where(
BridgeRequest.id == bridge_request_id BridgeRequest.id == bridge_request_id
) )
bridge_request = self.session.exec(stmt).first() bridge_request = self.session.execute(stmt).first()
if not bridge_request: if not bridge_request:
raise ValueError(f"Bridge request {bridge_request_id} not found") raise ValueError(f"Bridge request {bridge_request_id} not found")
@@ -266,7 +266,7 @@ class CrossChainBridgeService:
stmt = select(BridgeRequest).where( stmt = select(BridgeRequest).where(
BridgeRequest.id == bridge_request_id BridgeRequest.id == bridge_request_id
) )
bridge_request = self.session.exec(stmt).first() bridge_request = self.session.execute(stmt).first()
if not bridge_request: if not bridge_request:
raise ValueError(f"Bridge request {bridge_request_id} not found") raise ValueError(f"Bridge request {bridge_request_id} not found")
@@ -306,14 +306,14 @@ class CrossChainBridgeService:
cutoff_time = datetime.utcnow() - timedelta(hours=time_period_hours) cutoff_time = datetime.utcnow() - timedelta(hours=time_period_hours)
# Get total requests # Get total requests
total_requests = self.session.exec( total_requests = self.session.execute(
select(func.count(BridgeRequest.id)).where( select(func.count(BridgeRequest.id)).where(
BridgeRequest.created_at >= cutoff_time BridgeRequest.created_at >= cutoff_time
) )
).scalar() or 0 ).scalar() or 0
# Get completed requests # Get completed requests
completed_requests = self.session.exec( completed_requests = self.session.execute(
select(func.count(BridgeRequest.id)).where( select(func.count(BridgeRequest.id)).where(
BridgeRequest.created_at >= cutoff_time, BridgeRequest.created_at >= cutoff_time,
BridgeRequest.status == BridgeRequestStatus.COMPLETED BridgeRequest.status == BridgeRequestStatus.COMPLETED
@@ -321,7 +321,7 @@ class CrossChainBridgeService:
).scalar() or 0 ).scalar() or 0
# Get total volume # Get total volume
total_volume = self.session.exec( total_volume = self.session.execute(
select(func.sum(BridgeRequest.amount)).where( select(func.sum(BridgeRequest.amount)).where(
BridgeRequest.created_at >= cutoff_time, BridgeRequest.created_at >= cutoff_time,
BridgeRequest.status == BridgeRequestStatus.COMPLETED BridgeRequest.status == BridgeRequestStatus.COMPLETED
@@ -329,7 +329,7 @@ class CrossChainBridgeService:
).scalar() or 0 ).scalar() or 0
# Get total fees # Get total fees
total_fees = self.session.exec( total_fees = self.session.execute(
select(func.sum(BridgeRequest.total_fee)).where( select(func.sum(BridgeRequest.total_fee)).where(
BridgeRequest.created_at >= cutoff_time, BridgeRequest.created_at >= cutoff_time,
BridgeRequest.status == BridgeRequestStatus.COMPLETED BridgeRequest.status == BridgeRequestStatus.COMPLETED
@@ -340,7 +340,7 @@ class CrossChainBridgeService:
success_rate = completed_requests / max(total_requests, 1) success_rate = completed_requests / max(total_requests, 1)
# Get average processing time # Get average processing time
avg_processing_time = self.session.exec( avg_processing_time = self.session.execute(
select(func.avg( select(func.avg(
func.extract('epoch', BridgeRequest.completed_at) - func.extract('epoch', BridgeRequest.completed_at) -
func.extract('epoch', BridgeRequest.created_at) func.extract('epoch', BridgeRequest.created_at)
@@ -353,7 +353,7 @@ class CrossChainBridgeService:
# Get chain distribution # Get chain distribution
chain_distribution = {} chain_distribution = {}
for chain_id in self.wallet_adapters.keys(): for chain_id in self.wallet_adapters.keys():
chain_requests = self.session.exec( chain_requests = self.session.execute(
select(func.count(BridgeRequest.id)).where( select(func.count(BridgeRequest.id)).where(
BridgeRequest.created_at >= cutoff_time, BridgeRequest.created_at >= cutoff_time,
BridgeRequest.source_chain_id == chain_id BridgeRequest.source_chain_id == chain_id
@@ -413,7 +413,7 @@ class CrossChainBridgeService:
stmt = select(BridgeRequest).where( stmt = select(BridgeRequest).where(
BridgeRequest.id == bridge_request_id BridgeRequest.id == bridge_request_id
) )
bridge_request = self.session.exec(stmt).first() bridge_request = self.session.execute(stmt).first()
if not bridge_request: if not bridge_request:
logger.error(f"Bridge request {bridge_request_id} not found") logger.error(f"Bridge request {bridge_request_id} not found")
@@ -445,7 +445,7 @@ class CrossChainBridgeService:
error_message=str(e), error_message=str(e),
updated_at=datetime.utcnow() updated_at=datetime.utcnow()
) )
self.session.exec(stmt) self.session.execute(stmt)
self.session.commit() self.session.commit()
except: except:
pass pass

View File

@@ -34,7 +34,7 @@ class DAOGovernanceService:
self.contract_service = contract_service self.contract_service = contract_service
async def register_member(self, request: MemberCreate) -> DAOMember: async def register_member(self, request: MemberCreate) -> DAOMember:
existing = self.session.exec( existing = self.session.execute(
select(DAOMember).where(DAOMember.wallet_address == request.wallet_address) select(DAOMember).where(DAOMember.wallet_address == request.wallet_address)
).first() ).first()
@@ -58,7 +58,7 @@ class DAOGovernanceService:
return member return member
async def create_proposal(self, request: ProposalCreate) -> DAOProposal: async def create_proposal(self, request: ProposalCreate) -> DAOProposal:
proposer = self.session.exec( proposer = self.session.execute(
select(DAOMember).where(DAOMember.wallet_address == request.proposer_address) select(DAOMember).where(DAOMember.wallet_address == request.proposer_address)
).first() ).first()
@@ -91,7 +91,7 @@ class DAOGovernanceService:
return proposal return proposal
async def cast_vote(self, request: VoteCreate) -> Vote: async def cast_vote(self, request: VoteCreate) -> Vote:
member = self.session.exec( member = self.session.execute(
select(DAOMember).where(DAOMember.wallet_address == request.member_address) select(DAOMember).where(DAOMember.wallet_address == request.member_address)
).first() ).first()
@@ -112,7 +112,7 @@ class DAOGovernanceService:
self.session.commit() self.session.commit()
raise HTTPException(status_code=400, detail="Voting period has ended") raise HTTPException(status_code=400, detail="Voting period has ended")
existing_vote = self.session.exec( existing_vote = self.session.execute(
select(Vote).where( select(Vote).where(
Vote.proposal_id == request.proposal_id, Vote.proposal_id == request.proposal_id,
Vote.member_id == member.id Vote.member_id == member.id

View File

@@ -32,7 +32,7 @@ class DeveloperPlatformService:
self.session = session self.session = session
async def register_developer(self, request: DeveloperCreate) -> DeveloperProfile: async def register_developer(self, request: DeveloperCreate) -> DeveloperProfile:
existing = self.session.exec( existing = self.session.execute(
select(DeveloperProfile).where(DeveloperProfile.wallet_address == request.wallet_address) select(DeveloperProfile).where(DeveloperProfile.wallet_address == request.wallet_address)
).first() ).first()
@@ -173,7 +173,7 @@ class DeveloperPlatformService:
async def get_developer_profile(self, wallet_address: str) -> Optional[DeveloperProfile]: async def get_developer_profile(self, wallet_address: str) -> Optional[DeveloperProfile]:
"""Get developer profile by wallet address""" """Get developer profile by wallet address"""
return self.session.exec( return self.session.execute(
select(DeveloperProfile).where(DeveloperProfile.wallet_address == wallet_address) select(DeveloperProfile).where(DeveloperProfile.wallet_address == wallet_address)
).first() ).first()
@@ -195,7 +195,7 @@ class DeveloperPlatformService:
async def get_leaderboard(self, limit: int = 100, offset: int = 0) -> List[DeveloperProfile]: async def get_leaderboard(self, limit: int = 100, offset: int = 0) -> List[DeveloperProfile]:
"""Get developer leaderboard sorted by reputation score""" """Get developer leaderboard sorted by reputation score"""
return self.session.exec( return self.session.execute(
select(DeveloperProfile) select(DeveloperProfile)
.where(DeveloperProfile.is_active == True) .where(DeveloperProfile.is_active == True)
.order_by(DeveloperProfile.reputation_score.desc()) .order_by(DeveloperProfile.reputation_score.desc())
@@ -210,7 +210,7 @@ class DeveloperPlatformService:
raise HTTPException(status_code=404, detail="Developer profile not found") raise HTTPException(status_code=404, detail="Developer profile not found")
# Get bounty statistics # Get bounty statistics
completed_bounties = self.session.exec( completed_bounties = self.session.execute(
select(BountySubmission).where( select(BountySubmission).where(
BountySubmission.developer_id == profile.id, BountySubmission.developer_id == profile.id,
BountySubmission.is_approved == True BountySubmission.is_approved == True
@@ -218,7 +218,7 @@ class DeveloperPlatformService:
).all() ).all()
# Get certification statistics # Get certification statistics
certifications = self.session.exec( certifications = self.session.execute(
select(DeveloperCertification).where(DeveloperCertification.developer_id == profile.id) select(DeveloperCertification).where(DeveloperCertification.developer_id == profile.id)
).all() ).all()
@@ -240,7 +240,7 @@ class DeveloperPlatformService:
if status: if status:
query = query.where(BountyTask.status == status) query = query.where(BountyTask.status == status)
return self.session.exec( return self.session.execute(
query.order_by(BountyTask.created_at.desc()) query.order_by(BountyTask.created_at.desc())
.offset(offset) .offset(offset)
.limit(limit) .limit(limit)
@@ -253,7 +253,7 @@ class DeveloperPlatformService:
raise HTTPException(status_code=404, detail="Bounty not found") raise HTTPException(status_code=404, detail="Bounty not found")
# Get submissions count # Get submissions count
submissions_count = self.session.exec( submissions_count = self.session.execute(
select(BountySubmission).where(BountySubmission.bounty_id == bounty_id) select(BountySubmission).where(BountySubmission.bounty_id == bounty_id)
).count() ).count()
@@ -264,7 +264,7 @@ class DeveloperPlatformService:
async def get_my_submissions(self, developer_id: str) -> List[BountySubmission]: async def get_my_submissions(self, developer_id: str) -> List[BountySubmission]:
"""Get all submissions by a developer""" """Get all submissions by a developer"""
return self.session.exec( return self.session.execute(
select(BountySubmission) select(BountySubmission)
.where(BountySubmission.developer_id == developer_id) .where(BountySubmission.developer_id == developer_id)
.order_by(BountySubmission.submitted_at.desc()) .order_by(BountySubmission.submitted_at.desc())
@@ -288,7 +288,7 @@ class DeveloperPlatformService:
async def get_regional_hubs(self) -> List[RegionalHub]: async def get_regional_hubs(self) -> List[RegionalHub]:
"""Get all regional developer hubs""" """Get all regional developer hubs"""
return self.session.exec( return self.session.execute(
select(RegionalHub).where(RegionalHub.is_active == True) select(RegionalHub).where(RegionalHub.is_active == True)
).all() ).all()
@@ -301,7 +301,7 @@ class DeveloperPlatformService:
raise HTTPException(status_code=404, detail="Regional hub not found") raise HTTPException(status_code=404, detail="Regional hub not found")
# Mock implementation - in reality would use hub membership table # Mock implementation - in reality would use hub membership table
return self.session.exec( return self.session.execute(
select(DeveloperProfile).where(DeveloperProfile.is_active == True) select(DeveloperProfile).where(DeveloperProfile.is_active == True)
).all() ).all()
@@ -394,15 +394,15 @@ class DeveloperPlatformService:
async def get_bounty_statistics(self) -> dict: async def get_bounty_statistics(self) -> dict:
"""Get comprehensive bounty statistics""" """Get comprehensive bounty statistics"""
total_bounties = self.session.exec(select(BountyTask)).count() total_bounties = self.session.execute(select(BountyTask)).count()
open_bounties = self.session.exec( open_bounties = self.session.execute(
select(BountyTask).where(BountyTask.status == BountyStatus.OPEN) select(BountyTask).where(BountyTask.status == BountyStatus.OPEN)
).count() ).count()
completed_bounties = self.session.exec( completed_bounties = self.session.execute(
select(BountyTask).where(BountyTask.status == BountyStatus.COMPLETED) select(BountyTask).where(BountyTask.status == BountyStatus.COMPLETED)
).count() ).count()
total_rewards = self.session.exec( total_rewards = self.session.execute(
select(BountyTask).where(BountyTask.status == BountyStatus.COMPLETED) select(BountyTask).where(BountyTask.status == BountyStatus.COMPLETED)
).all() ).all()
total_reward_amount = sum(bounty.reward_amount for bounty in total_rewards) total_reward_amount = sum(bounty.reward_amount for bounty in total_rewards)

View File

@@ -23,7 +23,7 @@ class EdgeGPUService:
stmt = stmt.where(ConsumerGPUProfile.edge_optimized == edge_optimized) stmt = stmt.where(ConsumerGPUProfile.edge_optimized == edge_optimized)
if min_memory_gb is not None: if min_memory_gb is not None:
stmt = stmt.where(ConsumerGPUProfile.memory_gb >= min_memory_gb) stmt = stmt.where(ConsumerGPUProfile.memory_gb >= min_memory_gb)
return list(self.session.exec(stmt).all()) return list(self.session.execute(stmt).all())
def list_metrics(self, gpu_id: str, limit: int = 100) -> List[EdgeGPUMetrics]: def list_metrics(self, gpu_id: str, limit: int = 100) -> List[EdgeGPUMetrics]:
stmt = ( stmt = (
@@ -32,7 +32,7 @@ class EdgeGPUService:
.order_by(EdgeGPUMetrics.timestamp.desc()) .order_by(EdgeGPUMetrics.timestamp.desc())
.limit(limit) .limit(limit)
) )
return list(self.session.exec(stmt).all()) return list(self.session.execute(stmt).all())
def create_metric(self, payload: dict) -> EdgeGPUMetrics: def create_metric(self, payload: dict) -> EdgeGPUMetrics:
metric = EdgeGPUMetrics(**payload) metric = EdgeGPUMetrics(**payload)
@@ -42,7 +42,7 @@ class EdgeGPUService:
return metric return metric
def seed_profiles(self) -> None: def seed_profiles(self) -> None:
existing_models = set(self.session.exec(select(ConsumerGPUProfile.gpu_model)).all()) existing_models = set(self.session.execute(select(ConsumerGPUProfile.gpu_model)).all())
created = 0 created = 0
for profile in CONSUMER_GPU_PROFILES: for profile in CONSUMER_GPU_PROFILES:
if profile["gpu_model"] in existing_models: if profile["gpu_model"] in existing_models:

View File

@@ -83,7 +83,7 @@ class ExplorerService:
# Fallback to fake data if RPC is unavailable # Fallback to fake data if RPC is unavailable
print(f"Warning: Failed to fetch blocks from RPC: {e}, falling back to fake data") print(f"Warning: Failed to fetch blocks from RPC: {e}, falling back to fake data")
statement = select(Job).order_by(Job.requested_at.desc()) statement = select(Job).order_by(Job.requested_at.desc())
jobs = self.session.exec(statement.offset(offset).limit(limit)).all() jobs = self.session.execute(statement.offset(offset).limit(limit)).all()
items: list[BlockSummary] = [] items: list[BlockSummary] = []
for index, job in enumerate(jobs): for index, job in enumerate(jobs):
@@ -109,7 +109,7 @@ class ExplorerService:
.offset(offset) .offset(offset)
.limit(limit) .limit(limit)
) )
jobs = self.session.exec(statement).all() jobs = self.session.execute(statement).all()
items: list[TransactionSummary] = [] items: list[TransactionSummary] = []
for index, job in enumerate(jobs): for index, job in enumerate(jobs):
@@ -149,7 +149,7 @@ class ExplorerService:
def list_addresses(self, *, limit: int = 50, offset: int = 0) -> AddressListResponse: def list_addresses(self, *, limit: int = 50, offset: int = 0) -> AddressListResponse:
statement = select(Job).order_by(Job.requested_at.desc()) statement = select(Job).order_by(Job.requested_at.desc())
jobs = self.session.exec(statement.offset(offset).limit(limit)).all() jobs = self.session.execute(statement.offset(offset).limit(limit)).all()
address_map: dict[str, dict[str, object]] = defaultdict( address_map: dict[str, dict[str, object]] = defaultdict(
lambda: { lambda: {
@@ -237,7 +237,7 @@ class ExplorerService:
if job_id: if job_id:
statement = statement.where(JobReceipt.job_id == job_id) statement = statement.where(JobReceipt.job_id == job_id)
rows = self.session.exec(statement.offset(offset).limit(limit)).all() rows = self.session.execute(statement.offset(offset).limit(limit)).all()
items: list[ReceiptSummary] = [] items: list[ReceiptSummary] = []
for row in rows: for row in rows:
payload = row.payload or {} payload = row.payload or {}

View File

@@ -67,7 +67,7 @@ class FederatedLearningService:
raise HTTPException(status_code=400, detail="Session is not currently accepting participants") raise HTTPException(status_code=400, detail="Session is not currently accepting participants")
# Check if already joined # Check if already joined
existing = self.session.exec( existing = self.session.execute(
select(TrainingParticipant).where( select(TrainingParticipant).where(
TrainingParticipant.session_id == session_id, TrainingParticipant.session_id == session_id,
TrainingParticipant.agent_id == request.agent_id TrainingParticipant.agent_id == request.agent_id
@@ -128,7 +128,7 @@ class FederatedLearningService:
if fl_session.status != TrainingStatus.TRAINING or current_round.status != "active": if fl_session.status != TrainingStatus.TRAINING or current_round.status != "active":
raise HTTPException(status_code=400, detail="Round is not currently active") raise HTTPException(status_code=400, detail="Round is not currently active")
participant = self.session.exec( participant = self.session.execute(
select(TrainingParticipant).where( select(TrainingParticipant).where(
TrainingParticipant.session_id == session_id, TrainingParticipant.session_id == session_id,
TrainingParticipant.agent_id == request.agent_id TrainingParticipant.agent_id == request.agent_id

View File

@@ -127,7 +127,7 @@ class GlobalMarketplaceService:
GlobalMarketplaceOffer.created_at.desc() GlobalMarketplaceOffer.created_at.desc()
).offset(offset).limit(limit) ).offset(offset).limit(limit)
offers = self.session.exec(stmt).all() offers = self.session.execute(stmt).all()
# Filter out expired offers # Filter out expired offers
current_time = datetime.utcnow() current_time = datetime.utcnow()
@@ -155,7 +155,7 @@ class GlobalMarketplaceService:
stmt = select(GlobalMarketplaceOffer).where( stmt = select(GlobalMarketplaceOffer).where(
GlobalMarketplaceOffer.id == request.offer_id GlobalMarketplaceOffer.id == request.offer_id
) )
offer = self.session.exec(stmt).first() offer = self.session.execute(stmt).first()
if not offer: if not offer:
raise ValueError("Offer not found") raise ValueError("Offer not found")
@@ -252,7 +252,7 @@ class GlobalMarketplaceService:
GlobalMarketplaceTransaction.created_at.desc() GlobalMarketplaceTransaction.created_at.desc()
).offset(offset).limit(limit) ).offset(offset).limit(limit)
transactions = self.session.exec(stmt).all() transactions = self.session.execute(stmt).all()
return transactions return transactions
except Exception as e: except Exception as e:
@@ -274,7 +274,7 @@ class GlobalMarketplaceService:
GlobalMarketplaceAnalytics.region == request.region GlobalMarketplaceAnalytics.region == request.region
) )
existing_analytics = self.session.exec(stmt).first() existing_analytics = self.session.execute(stmt).first()
if existing_analytics: if existing_analytics:
return existing_analytics return existing_analytics
@@ -309,7 +309,7 @@ class GlobalMarketplaceService:
GlobalMarketplaceOffer.regions_available.contains([request.region]) GlobalMarketplaceOffer.regions_available.contains([request.region])
) )
offers = self.session.exec(stmt).all() offers = self.session.execute(stmt).all()
# Get transactions in the period # Get transactions in the period
stmt = select(GlobalMarketplaceTransaction).where( stmt = select(GlobalMarketplaceTransaction).where(
@@ -323,7 +323,7 @@ class GlobalMarketplaceService:
(GlobalMarketplaceTransaction.target_region == request.region) (GlobalMarketplaceTransaction.target_region == request.region)
) )
transactions = self.session.exec(stmt).all() transactions = self.session.execute(stmt).all()
# Calculate metrics # Calculate metrics
total_offers = len(offers) total_offers = len(offers)
@@ -370,7 +370,7 @@ class GlobalMarketplaceService:
MarketplaceRegion.status == RegionStatus.ACTIVE MarketplaceRegion.status == RegionStatus.ACTIVE
) )
regions = self.session.exec(stmt).all() regions = self.session.execute(stmt).all()
return regions return regions
async def get_region_health(self, region_code: str) -> Dict[str, Any]: async def get_region_health(self, region_code: str) -> Dict[str, Any]:
@@ -381,7 +381,7 @@ class GlobalMarketplaceService:
MarketplaceRegion.region_code == region_code MarketplaceRegion.region_code == region_code
) )
region = self.session.exec(stmt).first() region = self.session.execute(stmt).first()
if not region: if not region:
return {"status": "not_found"} return {"status": "not_found"}
@@ -417,7 +417,7 @@ class GlobalMarketplaceService:
GlobalMarketplaceAnalytics.created_at >= cutoff_time GlobalMarketplaceAnalytics.created_at >= cutoff_time
).order_by(GlobalMarketplaceAnalytics.created_at.desc()) ).order_by(GlobalMarketplaceAnalytics.created_at.desc())
analytics = self.session.exec(stmt).first() analytics = self.session.execute(stmt).first()
if analytics: if analytics:
return { return {
@@ -488,7 +488,7 @@ class RegionManager:
MarketplaceRegion.region_code == region_code MarketplaceRegion.region_code == region_code
) )
region = self.session.exec(stmt).first() region = self.session.execute(stmt).first()
if not region: if not region:
raise ValueError(f"Region {region_code} not found") raise ValueError(f"Region {region_code} not found")
@@ -532,7 +532,7 @@ class RegionManager:
MarketplaceRegion.status == RegionStatus.ACTIVE MarketplaceRegion.status == RegionStatus.ACTIVE
).order_by(MarketplaceRegion.priority_weight.desc()) ).order_by(MarketplaceRegion.priority_weight.desc())
regions = self.session.exec(stmt).all() regions = self.session.execute(stmt).all()
if not regions: if not regions:
raise ValueError("No active regions available") raise ValueError("No active regions available")

View File

@@ -209,7 +209,7 @@ class GlobalMarketplaceIntegrationService:
try: try:
# Get the global offer # Get the global offer
stmt = select(GlobalMarketplaceOffer).where(GlobalMarketplaceOffer.id == offer_id) stmt = select(GlobalMarketplaceOffer).where(GlobalMarketplaceOffer.id == offer_id)
offer = self.session.exec(stmt).first() offer = self.session.execute(stmt).first()
if not offer: if not offer:
raise ValueError("Offer not found") raise ValueError("Offer not found")
@@ -433,7 +433,7 @@ class GlobalMarketplaceIntegrationService:
try: try:
# Get the offer # Get the offer
stmt = select(GlobalMarketplaceOffer).where(GlobalMarketplaceOffer.id == offer_id) stmt = select(GlobalMarketplaceOffer).where(GlobalMarketplaceOffer.id == offer_id)
offer = self.session.exec(stmt).first() offer = self.session.execute(stmt).first()
if not offer: if not offer:
raise ValueError("Offer not found") raise ValueError("Offer not found")

View File

@@ -25,7 +25,7 @@ class GovernanceService:
async def get_or_create_profile(self, user_id: str, initial_voting_power: float = 0.0) -> GovernanceProfile: async def get_or_create_profile(self, user_id: str, initial_voting_power: float = 0.0) -> GovernanceProfile:
"""Get an existing governance profile or create a new one""" """Get an existing governance profile or create a new one"""
profile = self.session.exec(select(GovernanceProfile).where(GovernanceProfile.user_id == user_id)).first() profile = self.session.execute(select(GovernanceProfile).where(GovernanceProfile.user_id == user_id)).first()
if not profile: if not profile:
profile = GovernanceProfile( profile = GovernanceProfile(
@@ -40,15 +40,15 @@ class GovernanceService:
async def delegate_votes(self, delegator_id: str, delegatee_id: str) -> GovernanceProfile: async def delegate_votes(self, delegator_id: str, delegatee_id: str) -> GovernanceProfile:
"""Delegate voting power from one profile to another""" """Delegate voting power from one profile to another"""
delegator = self.session.exec(select(GovernanceProfile).where(GovernanceProfile.profile_id == delegator_id)).first() delegator = self.session.execute(select(GovernanceProfile).where(GovernanceProfile.profile_id == delegator_id)).first()
delegatee = self.session.exec(select(GovernanceProfile).where(GovernanceProfile.profile_id == delegatee_id)).first() delegatee = self.session.execute(select(GovernanceProfile).where(GovernanceProfile.profile_id == delegatee_id)).first()
if not delegator or not delegatee: if not delegator or not delegatee:
raise ValueError("Delegator or Delegatee not found") raise ValueError("Delegator or Delegatee not found")
# Remove old delegation if exists # Remove old delegation if exists
if delegator.delegate_to: if delegator.delegate_to:
old_delegatee = self.session.exec(select(GovernanceProfile).where(GovernanceProfile.profile_id == delegator.delegate_to)).first() old_delegatee = self.session.execute(select(GovernanceProfile).where(GovernanceProfile.profile_id == delegator.delegate_to)).first()
if old_delegatee: if old_delegatee:
old_delegatee.delegated_power -= delegator.voting_power old_delegatee.delegated_power -= delegator.voting_power
@@ -65,7 +65,7 @@ class GovernanceService:
async def create_proposal(self, proposer_id: str, data: Dict[str, Any]) -> Proposal: async def create_proposal(self, proposer_id: str, data: Dict[str, Any]) -> Proposal:
"""Create a new governance proposal""" """Create a new governance proposal"""
proposer = self.session.exec(select(GovernanceProfile).where(GovernanceProfile.profile_id == proposer_id)).first() proposer = self.session.execute(select(GovernanceProfile).where(GovernanceProfile.profile_id == proposer_id)).first()
if not proposer: if not proposer:
raise ValueError("Proposer not found") raise ValueError("Proposer not found")
@@ -110,8 +110,8 @@ class GovernanceService:
async def cast_vote(self, proposal_id: str, voter_id: str, vote_type: VoteType, reason: str = None) -> Vote: async def cast_vote(self, proposal_id: str, voter_id: str, vote_type: VoteType, reason: str = None) -> Vote:
"""Cast a vote on an active proposal""" """Cast a vote on an active proposal"""
proposal = self.session.exec(select(Proposal).where(Proposal.proposal_id == proposal_id)).first() proposal = self.session.execute(select(Proposal).where(Proposal.proposal_id == proposal_id)).first()
voter = self.session.exec(select(GovernanceProfile).where(GovernanceProfile.profile_id == voter_id)).first() voter = self.session.execute(select(GovernanceProfile).where(GovernanceProfile.profile_id == voter_id)).first()
if not proposal or not voter: if not proposal or not voter:
raise ValueError("Proposal or Voter not found") raise ValueError("Proposal or Voter not found")
@@ -121,7 +121,7 @@ class GovernanceService:
raise ValueError("Proposal is not currently active for voting") raise ValueError("Proposal is not currently active for voting")
# Check if already voted # Check if already voted
existing_vote = self.session.exec( existing_vote = self.session.execute(
select(Vote).where(Vote.proposal_id == proposal_id).where(Vote.voter_id == voter_id) select(Vote).where(Vote.proposal_id == proposal_id).where(Vote.voter_id == voter_id)
).first() ).first()
@@ -163,7 +163,7 @@ class GovernanceService:
async def process_proposal_lifecycle(self, proposal_id: str) -> Proposal: async def process_proposal_lifecycle(self, proposal_id: str) -> Proposal:
"""Update proposal status based on time and votes""" """Update proposal status based on time and votes"""
proposal = self.session.exec(select(Proposal).where(Proposal.proposal_id == proposal_id)).first() proposal = self.session.execute(select(Proposal).where(Proposal.proposal_id == proposal_id)).first()
if not proposal: if not proposal:
raise ValueError("Proposal not found") raise ValueError("Proposal not found")
@@ -191,7 +191,7 @@ class GovernanceService:
proposal.status = ProposalStatus.SUCCEEDED proposal.status = ProposalStatus.SUCCEEDED
# Update proposer stats # Update proposer stats
proposer = self.session.exec(select(GovernanceProfile).where(GovernanceProfile.profile_id == proposal.proposer_id)).first() proposer = self.session.execute(select(GovernanceProfile).where(GovernanceProfile.profile_id == proposal.proposer_id)).first()
if proposer: if proposer:
proposer.proposals_passed += 1 proposer.proposals_passed += 1
self.session.add(proposer) self.session.add(proposer)
@@ -205,8 +205,8 @@ class GovernanceService:
async def execute_proposal(self, proposal_id: str, executor_id: str) -> Proposal: async def execute_proposal(self, proposal_id: str, executor_id: str) -> Proposal:
"""Execute a successful proposal's payload""" """Execute a successful proposal's payload"""
proposal = self.session.exec(select(Proposal).where(Proposal.proposal_id == proposal_id)).first() proposal = self.session.execute(select(Proposal).where(Proposal.proposal_id == proposal_id)).first()
executor = self.session.exec(select(GovernanceProfile).where(GovernanceProfile.profile_id == executor_id)).first() executor = self.session.execute(select(GovernanceProfile).where(GovernanceProfile.profile_id == executor_id)).first()
if not proposal or not executor: if not proposal or not executor:
raise ValueError("Proposal or Executor not found") raise ValueError("Proposal or Executor not found")
@@ -223,7 +223,7 @@ class GovernanceService:
# If it's a funding proposal, deduct from treasury # If it's a funding proposal, deduct from treasury
if proposal.category == 'funding' and 'amount' in proposal.execution_payload: if proposal.category == 'funding' and 'amount' in proposal.execution_payload:
treasury = self.session.exec(select(DaoTreasury).where(DaoTreasury.treasury_id == "main_treasury")).first() treasury = self.session.execute(select(DaoTreasury).where(DaoTreasury.treasury_id == "main_treasury")).first()
if treasury: if treasury:
amount = float(proposal.execution_payload['amount']) amount = float(proposal.execution_payload['amount'])
if treasury.total_balance - treasury.allocated_funds >= amount: if treasury.total_balance - treasury.allocated_funds >= amount:
@@ -246,9 +246,9 @@ class GovernanceService:
# In reality, we would calculate this based on timestamps matching the period # In reality, we would calculate this based on timestamps matching the period
# For simplicity, we just aggregate current totals # For simplicity, we just aggregate current totals
proposals = self.session.exec(select(Proposal)).all() proposals = self.session.execute(select(Proposal)).all()
profiles = self.session.exec(select(GovernanceProfile)).all() profiles = self.session.execute(select(GovernanceProfile)).all()
treasury = self.session.exec(select(DaoTreasury).where(DaoTreasury.treasury_id == "main_treasury")).first() treasury = self.session.execute(select(DaoTreasury).where(DaoTreasury.treasury_id == "main_treasury")).first()
total_proposals = len(proposals) total_proposals = len(proposals)
passed_proposals = len([p for p in proposals if p.status in [ProposalStatus.SUCCEEDED, ProposalStatus.EXECUTED]]) passed_proposals = len([p for p in proposals if p.status in [ProposalStatus.SUCCEEDED, ProposalStatus.EXECUTED]])

View File

@@ -104,7 +104,7 @@ class IPFSAdapterService:
query = query.where(AgentMemoryNode.memory_type == memory_type) query = query.where(AgentMemoryNode.memory_type == memory_type)
# Execute query and filter by tags in Python (since SQLite JSON JSON_CONTAINS is complex via pure SQLAlchemy without specific dialects) # Execute query and filter by tags in Python (since SQLite JSON JSON_CONTAINS is complex via pure SQLAlchemy without specific dialects)
results = self.session.exec(query).all() results = self.session.execute(query).all()
if tags and len(tags) > 0: if tags and len(tags) > 0:
filtered_results = [] filtered_results = []

View File

@@ -36,17 +36,17 @@ class MarketplaceService:
stmt = stmt.where(MarketplaceOffer.status == normalised) stmt = stmt.where(MarketplaceOffer.status == normalised)
stmt = stmt.offset(offset).limit(limit) stmt = stmt.offset(offset).limit(limit)
offers = self.session.exec(stmt).all() offers = self.session.execute(stmt).all()
return [self._to_offer_view(o) for o in offers] return [self._to_offer_view(o) for o in offers]
def get_stats(self) -> MarketplaceStatsView: def get_stats(self) -> MarketplaceStatsView:
offers = self.session.exec(select(MarketplaceOffer)).all() offers = self.session.execute(select(MarketplaceOffer)).all()
open_offers = [offer for offer in offers if offer.status == "open"] open_offers = [offer for offer in offers if offer.status == "open"]
total_offers = len(offers) total_offers = len(offers)
open_capacity = sum(offer.capacity for offer in open_offers) open_capacity = sum(offer.capacity for offer in open_offers)
average_price = mean([offer.price for offer in open_offers]) if open_offers else 0.0 average_price = mean([offer.price for offer in open_offers]) if open_offers else 0.0
active_bids = self.session.exec( active_bids = self.session.execute(
select(MarketplaceBid).where(MarketplaceBid.status == "pending") select(MarketplaceBid).where(MarketplaceBid.status == "pending")
).all() ).all()
@@ -89,7 +89,7 @@ class MarketplaceService:
stmt = stmt.where(MarketplaceBid.provider == provider) stmt = stmt.where(MarketplaceBid.provider == provider)
stmt = stmt.offset(offset).limit(limit) stmt = stmt.offset(offset).limit(limit)
bids = self.session.exec(stmt).all() bids = self.session.execute(stmt).all()
return [self._to_bid_view(bid) for bid in bids] return [self._to_bid_view(bid) for bid in bids]
def get_bid(self, bid_id: str) -> Optional[MarketplaceBidView]: def get_bid(self, bid_id: str) -> Optional[MarketplaceBidView]:

View File

@@ -294,7 +294,7 @@ class EnhancedMarketplaceService:
async def _get_volume_analytics(self, start_date: datetime, end_date: datetime) -> Dict[str, Any]: async def _get_volume_analytics(self, start_date: datetime, end_date: datetime) -> Dict[str, Any]:
"""Get volume analytics""" """Get volume analytics"""
offers = self.session.exec( offers = self.session.execute(
select(MarketplaceOffer).where( select(MarketplaceOffer).where(
MarketplaceOffer.created_at >= start_date, MarketplaceOffer.created_at >= start_date,
MarketplaceOffer.created_at <= end_date MarketplaceOffer.created_at <= end_date

View File

@@ -225,12 +225,12 @@ class EnhancedMarketplaceService:
offers_query = select(MarketplaceOffer).where( offers_query = select(MarketplaceOffer).where(
MarketplaceOffer.created_at >= start_date MarketplaceOffer.created_at >= start_date
) )
offers = self.session.exec(offers_query).all() offers = self.session.execute(offers_query).all()
bids_query = select(MarketplaceBid).where( bids_query = select(MarketplaceBid).where(
MarketplaceBid.created_at >= start_date MarketplaceBid.created_at >= start_date
) )
bids = self.session.exec(bids_query).all() bids = self.session.execute(bids_query).all()
# Calculate analytics # Calculate analytics
analytics = { analytics = {

View File

@@ -111,8 +111,8 @@ class MinerService:
return miner return miner
def list_records(self) -> list[Miner]: def list_records(self) -> list[Miner]:
return list(self.session.exec(select(Miner)).all()) return list(self.session.execute(select(Miner)).all())
def online_count(self) -> int: def online_count(self) -> int:
result = self.session.exec(select(Miner).where(Miner.status == "ONLINE")) result = self.session.execute(select(Miner).where(Miner.status == "ONLINE"))
return len(result.all()) return len(result.all())

View File

@@ -603,7 +603,7 @@ class MultiModalFusionEngine:
async def train_fusion_model(self, session: Session, fusion_id: str) -> Dict[str, Any]: async def train_fusion_model(self, session: Session, fusion_id: str) -> Dict[str, Any]:
"""Train a fusion model""" """Train a fusion model"""
fusion_model = session.exec( fusion_model = session.execute(
select(FusionModel).where(FusionModel.fusion_id == fusion_id) select(FusionModel).where(FusionModel.fusion_id == fusion_id)
).first() ).first()
@@ -778,7 +778,7 @@ class MultiModalFusionEngine:
) -> Dict[str, Any]: ) -> Dict[str, Any]:
"""Fuse multiple modalities using trained fusion model""" """Fuse multiple modalities using trained fusion model"""
fusion_model = session.exec( fusion_model = session.execute(
select(FusionModel).where(FusionModel.fusion_id == fusion_id) select(FusionModel).where(FusionModel.fusion_id == fusion_id)
).first() ).first()

View File

@@ -3,6 +3,7 @@
from datetime import datetime, timedelta from datetime import datetime, timedelta
from typing import Optional, Dict, Any from typing import Optional, Dict, Any
import httpx import httpx
from sqlmodel import select
from aitbc.logging import get_logger from aitbc.logging import get_logger
from ..domain.payment import JobPayment, PaymentEscrow from ..domain.payment import JobPayment, PaymentEscrow
@@ -42,11 +43,13 @@ class PaymentService:
# For AITBC token payments, use token escrow # For AITBC token payments, use token escrow
if payment_data.payment_method == "aitbc_token": if payment_data.payment_method == "aitbc_token":
escrow = await self._create_token_escrow(payment) escrow = await self._create_token_escrow(payment)
self.session.add(escrow) if escrow is not None:
self.session.add(escrow)
# Bitcoin payments only for exchange purchases # Bitcoin payments only for exchange purchases
elif payment_data.payment_method == "bitcoin": elif payment_data.payment_method == "bitcoin":
escrow = await self._create_bitcoin_escrow(payment) escrow = await self._create_bitcoin_escrow(payment)
self.session.add(escrow) if escrow is not None:
self.session.add(escrow)
# Single atomic commit - all or nothing # Single atomic commit - all or nothing
self.session.commit() self.session.commit()
@@ -92,7 +95,8 @@ class PaymentService:
address=escrow_data.get("escrow_id"), address=escrow_data.get("escrow_id"),
expires_at=datetime.utcnow() + timedelta(hours=1) expires_at=datetime.utcnow() + timedelta(hours=1)
) )
self.session.add(escrow) if escrow is not None:
self.session.add(escrow)
self.session.commit() self.session.commit()
logger.info(f"Created AITBC token escrow for payment {payment.id}") logger.info(f"Created AITBC token escrow for payment {payment.id}")
@@ -134,7 +138,8 @@ class PaymentService:
address=escrow_data["address"], address=escrow_data["address"],
expires_at=datetime.utcnow() + timedelta(hours=1) expires_at=datetime.utcnow() + timedelta(hours=1)
) )
self.session.add(escrow) if escrow is not None:
self.session.add(escrow)
self.session.commit() self.session.commit()
logger.info(f"Created Bitcoin escrow for payment {payment.id}") logger.info(f"Created Bitcoin escrow for payment {payment.id}")
@@ -176,11 +181,11 @@ class PaymentService:
payment.transaction_hash = release_data.get("transaction_hash") payment.transaction_hash = release_data.get("transaction_hash")
# Update escrow record # Update escrow record
escrow = self.session.exec( escrow = self.session.execute(
self.session.query(PaymentEscrow).where( select(PaymentEscrow).where(
PaymentEscrow.payment_id == payment_id PaymentEscrow.payment_id == payment_id
) )
).first() ).scalars().first()
if escrow: if escrow:
escrow.is_released = True escrow.is_released = True
@@ -228,11 +233,11 @@ class PaymentService:
payment.refund_transaction_hash = refund_data.get("transaction_hash") payment.refund_transaction_hash = refund_data.get("transaction_hash")
# Update escrow record # Update escrow record
escrow = self.session.exec( escrow = self.session.execute(
self.session.query(PaymentEscrow).where( select(PaymentEscrow).where(
PaymentEscrow.payment_id == payment_id PaymentEscrow.payment_id == payment_id
) )
).first() ).scalars().first()
if escrow: if escrow:
escrow.is_refunded = True escrow.is_refunded = True
@@ -255,9 +260,9 @@ class PaymentService:
def get_job_payment(self, job_id: str) -> Optional[JobPayment]: def get_job_payment(self, job_id: str) -> Optional[JobPayment]:
"""Get payment for a specific job""" """Get payment for a specific job"""
return self.session.exec( return self.session.execute(
self.session.query(JobPayment).where(JobPayment.job_id == job_id) select(JobPayment).where(JobPayment.job_id == job_id)
).first() ).scalars().first()
def to_view(self, payment: JobPayment) -> JobPaymentView: def to_view(self, payment: JobPayment) -> JobPaymentView:
"""Convert payment to view model""" """Convert payment to view model"""

View File

@@ -172,7 +172,7 @@ class OptimizedMinerService(BaseService[Miner]):
if key.startswith("miner_"): if key.startswith("miner_"):
address = key[7:] # Remove "miner_" prefix address = key[7:] # Remove "miner_" prefix
statement = select(Miner).where(Miner.address == address) statement = select(Miner).where(Miner.address == address)
result = self.session.exec(statement).first() result = self.session.execute(statement).first()
if result: if result:
await self.set_cached(key, result) await self.set_cached(key, result)
return result return result

View File

@@ -67,7 +67,7 @@ class TrustScoreCalculator:
# For now, use existing performance rating # For now, use existing performance rating
# In real implementation, this would analyze actual job performance # In real implementation, this would analyze actual job performance
reputation = session.exec( reputation = session.execute(
select(AgentReputation).where(AgentReputation.agent_id == agent_id) select(AgentReputation).where(AgentReputation.agent_id == agent_id)
).first() ).first()
@@ -98,7 +98,7 @@ class TrustScoreCalculator:
) -> float: ) -> float:
"""Calculate reliability-based trust score component""" """Calculate reliability-based trust score component"""
reputation = session.exec( reputation = session.execute(
select(AgentReputation).where(AgentReputation.agent_id == agent_id) select(AgentReputation).where(AgentReputation.agent_id == agent_id)
).first() ).first()
@@ -140,7 +140,7 @@ class TrustScoreCalculator:
) )
) )
feedbacks = session.exec(feedback_query).all() feedbacks = session.execute(feedback_query).all()
if not feedbacks: if not feedbacks:
return 500.0 # Neutral score return 500.0 # Neutral score
@@ -178,7 +178,7 @@ class TrustScoreCalculator:
) -> float: ) -> float:
"""Calculate security-based trust score component""" """Calculate security-based trust score component"""
reputation = session.exec( reputation = session.execute(
select(AgentReputation).where(AgentReputation.agent_id == agent_id) select(AgentReputation).where(AgentReputation.agent_id == agent_id)
).first() ).first()
@@ -209,7 +209,7 @@ class TrustScoreCalculator:
) -> float: ) -> float:
"""Calculate economic-based trust score component""" """Calculate economic-based trust score component"""
reputation = session.exec( reputation = session.execute(
select(AgentReputation).where(AgentReputation.agent_id == agent_id) select(AgentReputation).where(AgentReputation.agent_id == agent_id)
).first() ).first()
@@ -258,7 +258,7 @@ class TrustScoreCalculator:
) )
# Apply smoothing with previous score if available # Apply smoothing with previous score if available
reputation = session.exec( reputation = session.execute(
select(AgentReputation).where(AgentReputation.agent_id == agent_id) select(AgentReputation).where(AgentReputation.agent_id == agent_id)
).first() ).first()
@@ -296,7 +296,7 @@ class ReputationService:
"""Create a new reputation profile for an agent""" """Create a new reputation profile for an agent"""
# Check if profile already exists # Check if profile already exists
existing = self.session.exec( existing = self.session.execute(
select(AgentReputation).where(AgentReputation.agent_id == agent_id) select(AgentReputation).where(AgentReputation.agent_id == agent_id)
).first() ).first()
@@ -478,7 +478,7 @@ class ReputationService:
"""Update agent's community rating based on feedback""" """Update agent's community rating based on feedback"""
# Get all approved feedback # Get all approved feedback
feedbacks = self.session.exec( feedbacks = self.session.execute(
select(CommunityFeedback).where( select(CommunityFeedback).where(
and_( and_(
CommunityFeedback.agent_id == agent_id, CommunityFeedback.agent_id == agent_id,
@@ -505,7 +505,7 @@ class ReputationService:
avg_rating = weighted_sum / total_weight avg_rating = weighted_sum / total_weight
# Update reputation profile # Update reputation profile
reputation = self.session.exec( reputation = self.session.execute(
select(AgentReputation).where(AgentReputation.agent_id == agent_id) select(AgentReputation).where(AgentReputation.agent_id == agent_id)
).first() ).first()
@@ -517,7 +517,7 @@ class ReputationService:
async def get_reputation_summary(self, agent_id: str) -> Dict[str, Any]: async def get_reputation_summary(self, agent_id: str) -> Dict[str, Any]:
"""Get comprehensive reputation summary for an agent""" """Get comprehensive reputation summary for an agent"""
reputation = self.session.exec( reputation = self.session.execute(
select(AgentReputation).where(AgentReputation.agent_id == agent_id) select(AgentReputation).where(AgentReputation.agent_id == agent_id)
).first() ).first()
@@ -525,7 +525,7 @@ class ReputationService:
return {"error": "Reputation profile not found"} return {"error": "Reputation profile not found"}
# Get recent events # Get recent events
recent_events = self.session.exec( recent_events = self.session.execute(
select(ReputationEvent).where( select(ReputationEvent).where(
and_( and_(
ReputationEvent.agent_id == agent_id, ReputationEvent.agent_id == agent_id,
@@ -535,7 +535,7 @@ class ReputationService:
).all() ).all()
# Get recent feedback # Get recent feedback
recent_feedback = self.session.exec( recent_feedback = self.session.execute(
select(CommunityFeedback).where( select(CommunityFeedback).where(
and_( and_(
CommunityFeedback.agent_id == agent_id, CommunityFeedback.agent_id == agent_id,
@@ -595,7 +595,7 @@ class ReputationService:
if region: if region:
query = query.where(AgentReputation.geographic_region == region) query = query.where(AgentReputation.geographic_region == region)
reputations = self.session.exec(query).all() reputations = self.session.execute(query).all()
leaderboard = [] leaderboard = []
for rank, reputation in enumerate(reputations, 1): for rank, reputation in enumerate(reputations, 1):

View File

@@ -49,7 +49,7 @@ class RewardCalculator:
"""Calculate reward multiplier based on agent's tier""" """Calculate reward multiplier based on agent's tier"""
# Get tier configuration # Get tier configuration
tier_config = session.exec( tier_config = session.execute(
select(RewardTierConfig).where( select(RewardTierConfig).where(
and_( and_(
RewardTierConfig.min_trust_score <= trust_score, RewardTierConfig.min_trust_score <= trust_score,
@@ -116,7 +116,7 @@ class RewardCalculator:
"""Calculate loyalty bonus based on agent history""" """Calculate loyalty bonus based on agent history"""
# Get agent reward profile # Get agent reward profile
reward_profile = session.exec( reward_profile = session.execute(
select(AgentRewardProfile).where(AgentRewardProfile.agent_id == agent_id) select(AgentRewardProfile).where(AgentRewardProfile.agent_id == agent_id)
).first() ).first()
@@ -170,7 +170,7 @@ class RewardCalculator:
"""Calculate milestone achievement bonus""" """Calculate milestone achievement bonus"""
# Check for unclaimed milestones # Check for unclaimed milestones
milestones = session.exec( milestones = session.execute(
select(RewardMilestone).where( select(RewardMilestone).where(
and_( and_(
RewardMilestone.agent_id == agent_id, RewardMilestone.agent_id == agent_id,
@@ -200,7 +200,7 @@ class RewardCalculator:
"""Calculate total reward with all bonuses and multipliers""" """Calculate total reward with all bonuses and multipliers"""
# Get agent's trust score and tier # Get agent's trust score and tier
reputation = session.exec( reputation = session.execute(
select(AgentReputation).where(AgentReputation.agent_id == agent_id) select(AgentReputation).where(AgentReputation.agent_id == agent_id)
).first() ).first()
@@ -243,7 +243,7 @@ class RewardEngine:
"""Create a new reward profile for an agent""" """Create a new reward profile for an agent"""
# Check if profile already exists # Check if profile already exists
existing = self.session.exec( existing = self.session.execute(
select(AgentRewardProfile).where(AgentRewardProfile.agent_id == agent_id) select(AgentRewardProfile).where(AgentRewardProfile.agent_id == agent_id)
).first() ).first()
@@ -346,7 +346,7 @@ class RewardEngine:
async def process_reward_distribution(self, distribution_id: str) -> RewardDistribution: async def process_reward_distribution(self, distribution_id: str) -> RewardDistribution:
"""Process a reward distribution""" """Process a reward distribution"""
distribution = self.session.exec( distribution = self.session.execute(
select(RewardDistribution).where(RewardDistribution.id == distribution_id) select(RewardDistribution).where(RewardDistribution.id == distribution_id)
).first() ).first()
@@ -389,7 +389,7 @@ class RewardEngine:
async def update_agent_reward_profile(self, agent_id: str, reward_calculation: Dict[str, Any]): async def update_agent_reward_profile(self, agent_id: str, reward_calculation: Dict[str, Any]):
"""Update agent reward profile after reward distribution""" """Update agent reward profile after reward distribution"""
profile = self.session.exec( profile = self.session.execute(
select(AgentRewardProfile).where(AgentRewardProfile.agent_id == agent_id) select(AgentRewardProfile).where(AgentRewardProfile.agent_id == agent_id)
).first() ).first()
@@ -426,7 +426,7 @@ class RewardEngine:
"""Check and update agent's reward tier""" """Check and update agent's reward tier"""
# Get agent reputation # Get agent reputation
reputation = self.session.exec( reputation = self.session.execute(
select(AgentReputation).where(AgentReputation.agent_id == agent_id) select(AgentReputation).where(AgentReputation.agent_id == agent_id)
).first() ).first()
@@ -434,7 +434,7 @@ class RewardEngine:
return return
# Get reward profile # Get reward profile
profile = self.session.exec( profile = self.session.execute(
select(AgentRewardProfile).where(AgentRewardProfile.agent_id == agent_id) select(AgentRewardProfile).where(AgentRewardProfile.agent_id == agent_id)
).first() ).first()
@@ -502,7 +502,7 @@ class RewardEngine:
async def get_reward_summary(self, agent_id: str) -> Dict[str, Any]: async def get_reward_summary(self, agent_id: str) -> Dict[str, Any]:
"""Get comprehensive reward summary for an agent""" """Get comprehensive reward summary for an agent"""
profile = self.session.exec( profile = self.session.execute(
select(AgentRewardProfile).where(AgentRewardProfile.agent_id == agent_id) select(AgentRewardProfile).where(AgentRewardProfile.agent_id == agent_id)
).first() ).first()
@@ -510,7 +510,7 @@ class RewardEngine:
return {"error": "Reward profile not found"} return {"error": "Reward profile not found"}
# Get recent calculations # Get recent calculations
recent_calculations = self.session.exec( recent_calculations = self.session.execute(
select(RewardCalculation).where( select(RewardCalculation).where(
and_( and_(
RewardCalculation.agent_id == agent_id, RewardCalculation.agent_id == agent_id,
@@ -520,7 +520,7 @@ class RewardEngine:
).all() ).all()
# Get recent distributions # Get recent distributions
recent_distributions = self.session.exec( recent_distributions = self.session.execute(
select(RewardDistribution).where( select(RewardDistribution).where(
and_( and_(
RewardDistribution.agent_id == agent_id, RewardDistribution.agent_id == agent_id,
@@ -567,7 +567,7 @@ class RewardEngine:
"""Process pending reward distributions in batch""" """Process pending reward distributions in batch"""
# Get pending distributions # Get pending distributions
pending_distributions = self.session.exec( pending_distributions = self.session.execute(
select(RewardDistribution).where( select(RewardDistribution).where(
and_( and_(
RewardDistribution.status == RewardStatus.PENDING, RewardDistribution.status == RewardStatus.PENDING,
@@ -608,7 +608,7 @@ class RewardEngine:
end_date = datetime.utcnow() end_date = datetime.utcnow()
# Get distributions in period # Get distributions in period
distributions = self.session.exec( distributions = self.session.execute(
select(RewardDistribution).where( select(RewardDistribution).where(
and_( and_(
RewardDistribution.created_at >= start_date, RewardDistribution.created_at >= start_date,
@@ -635,7 +635,7 @@ class RewardEngine:
# Get agent profiles for tier distribution # Get agent profiles for tier distribution
agent_ids = list(set(d.agent_id for d in distributions)) agent_ids = list(set(d.agent_id for d in distributions))
profiles = self.session.exec( profiles = self.session.execute(
select(AgentRewardProfile).where(AgentRewardProfile.agent_id.in_(agent_ids)) select(AgentRewardProfile).where(AgentRewardProfile.agent_id.in_(agent_ids))
).all() ).all()

View File

@@ -68,7 +68,7 @@ class SecureWalletService:
) )
# Check if agent already has an active wallet of this type # Check if agent already has an active wallet of this type
existing = self.session.exec( existing = self.session.execute(
select(AgentWallet).where( select(AgentWallet).where(
AgentWallet.agent_id == request.agent_id, AgentWallet.agent_id == request.agent_id,
AgentWallet.wallet_type == request.wallet_type, AgentWallet.wallet_type == request.wallet_type,
@@ -116,7 +116,7 @@ class SecureWalletService:
async def get_wallet_by_agent(self, agent_id: str) -> List[AgentWallet]: async def get_wallet_by_agent(self, agent_id: str) -> List[AgentWallet]:
"""Retrieve all active wallets for an agent""" """Retrieve all active wallets for an agent"""
return self.session.exec( return self.session.execute(
select(AgentWallet).where( select(AgentWallet).where(
AgentWallet.agent_id == agent_id, AgentWallet.agent_id == agent_id,
AgentWallet.is_active == True AgentWallet.is_active == True
@@ -264,13 +264,13 @@ class SecureWalletService:
async def get_balances(self, wallet_id: int) -> List[TokenBalance]: async def get_balances(self, wallet_id: int) -> List[TokenBalance]:
"""Get all tracked balances for a wallet""" """Get all tracked balances for a wallet"""
return self.session.exec( return self.session.execute(
select(TokenBalance).where(TokenBalance.wallet_id == wallet_id) select(TokenBalance).where(TokenBalance.wallet_id == wallet_id)
).all() ).all()
async def update_balance(self, wallet_id: int, chain_id: int, token_address: str, balance: float) -> TokenBalance: async def update_balance(self, wallet_id: int, chain_id: int, token_address: str, balance: float) -> TokenBalance:
"""Update a specific token balance for a wallet""" """Update a specific token balance for a wallet"""
record = self.session.exec( record = self.session.execute(
select(TokenBalance).where( select(TokenBalance).where(
TokenBalance.wallet_id == wallet_id, TokenBalance.wallet_id == wallet_id,
TokenBalance.chain_id == chain_id, TokenBalance.chain_id == chain_id,

View File

@@ -816,7 +816,7 @@ class P2PTradingProtocol:
"""Find matching sellers for a trade request""" """Find matching sellers for a trade request"""
# Get trade request # Get trade request
trade_request = self.session.exec( trade_request = self.session.execute(
select(TradeRequest).where(TradeRequest.request_id == request_id) select(TradeRequest).where(TradeRequest.request_id == request_id)
).first() ).first()
@@ -879,7 +879,7 @@ class P2PTradingProtocol:
"""Initiate negotiation between buyer and seller""" """Initiate negotiation between buyer and seller"""
# Get trade match # Get trade match
trade_match = self.session.exec( trade_match = self.session.execute(
select(TradeMatch).where(TradeMatch.match_id == match_id) select(TradeMatch).where(TradeMatch.match_id == match_id)
).first() ).first()
@@ -887,7 +887,7 @@ class P2PTradingProtocol:
raise ValueError(f"Trade match {match_id} not found") raise ValueError(f"Trade match {match_id} not found")
# Get trade request # Get trade request
trade_request = self.session.exec( trade_request = self.session.execute(
select(TradeRequest).where(TradeRequest.request_id == trade_match.request_id) select(TradeRequest).where(TradeRequest.request_id == trade_match.request_id)
).first() ).first()
@@ -970,12 +970,12 @@ class P2PTradingProtocol:
"""Get comprehensive trading summary for an agent""" """Get comprehensive trading summary for an agent"""
# Get trade requests # Get trade requests
requests = self.session.exec( requests = self.session.execute(
select(TradeRequest).where(TradeRequest.buyer_agent_id == agent_id) select(TradeRequest).where(TradeRequest.buyer_agent_id == agent_id)
).all() ).all()
# Get trade matches # Get trade matches
matches = self.session.exec( matches = self.session.execute(
select(TradeMatch).where( select(TradeMatch).where(
or_( or_(
TradeMatch.buyer_agent_id == agent_id, TradeMatch.buyer_agent_id == agent_id,
@@ -985,7 +985,7 @@ class P2PTradingProtocol:
).all() ).all()
# Get negotiations # Get negotiations
negotiations = self.session.exec( negotiations = self.session.execute(
select(TradeNegotiation).where( select(TradeNegotiation).where(
or_( or_(
TradeNegotiation.buyer_agent_id == agent_id, TradeNegotiation.buyer_agent_id == agent_id,
@@ -995,7 +995,7 @@ class P2PTradingProtocol:
).all() ).all()
# Get agreements # Get agreements
agreements = self.session.exec( agreements = self.session.execute(
select(TradeAgreement).where( select(TradeAgreement).where(
or_( or_(
TradeAgreement.buyer_agent_id == agent_id, TradeAgreement.buyer_agent_id == agent_id,

View File

@@ -37,7 +37,7 @@ class WalletService:
"""Create a new wallet for an agent""" """Create a new wallet for an agent"""
# Check if agent already has an active wallet of this type # Check if agent already has an active wallet of this type
existing = self.session.exec( existing = self.session.execute(
select(AgentWallet).where( select(AgentWallet).where(
AgentWallet.agent_id == request.agent_id, AgentWallet.agent_id == request.agent_id,
AgentWallet.wallet_type == request.wallet_type, AgentWallet.wallet_type == request.wallet_type,
@@ -72,7 +72,7 @@ class WalletService:
async def get_wallet_by_agent(self, agent_id: str) -> List[AgentWallet]: async def get_wallet_by_agent(self, agent_id: str) -> List[AgentWallet]:
"""Retrieve all active wallets for an agent""" """Retrieve all active wallets for an agent"""
return self.session.exec( return self.session.execute(
select(AgentWallet).where( select(AgentWallet).where(
AgentWallet.agent_id == agent_id, AgentWallet.agent_id == agent_id,
AgentWallet.is_active == True AgentWallet.is_active == True
@@ -81,13 +81,13 @@ class WalletService:
async def get_balances(self, wallet_id: int) -> List[TokenBalance]: async def get_balances(self, wallet_id: int) -> List[TokenBalance]:
"""Get all tracked balances for a wallet""" """Get all tracked balances for a wallet"""
return self.session.exec( return self.session.execute(
select(TokenBalance).where(TokenBalance.wallet_id == wallet_id) select(TokenBalance).where(TokenBalance.wallet_id == wallet_id)
).all() ).all()
async def update_balance(self, wallet_id: int, chain_id: int, token_address: str, balance: float) -> TokenBalance: async def update_balance(self, wallet_id: int, chain_id: int, token_address: str, balance: float) -> TokenBalance:
"""Update a specific token balance for a wallet""" """Update a specific token balance for a wallet"""
record = self.session.exec( record = self.session.execute(
select(TokenBalance).where( select(TokenBalance).where(
TokenBalance.wallet_id == wallet_id, TokenBalance.wallet_id == wallet_id,
TokenBalance.chain_id == chain_id, TokenBalance.chain_id == chain_id,

View File

@@ -295,11 +295,11 @@ def integration(ctx, component, verbose):
elif component == 'job': elif component == 'job':
ctx.invoke(job, []) ctx.invoke(job, [])
elif component == 'marketplace': elif component == 'marketplace':
ctx.invoke(marketplace, []) ctx.invoke(marketplace)
elif component == 'blockchain': elif component == 'blockchain':
ctx.invoke(blockchain, []) ctx.invoke(blockchain, [])
elif component == 'api': elif component == 'api':
ctx.invoke(api, ['--endpoint', 'health']) ctx.invoke(api, endpoint='health')
else: else:
error(f"Unknown component: {component}") error(f"Unknown component: {component}")
return return
@@ -308,7 +308,7 @@ def integration(ctx, component, verbose):
# Test API connectivity first # Test API connectivity first
output("1. Testing API connectivity...") output("1. Testing API connectivity...")
ctx.invoke(api, ['--endpoint', 'health']) ctx.invoke(api, endpoint='health')
# Test wallet functionality # Test wallet functionality
output("2. Testing wallet functionality...") output("2. Testing wallet functionality...")
@@ -316,7 +316,7 @@ def integration(ctx, component, verbose):
# Test marketplace functionality # Test marketplace functionality
output("3. Testing marketplace functionality...") output("3. Testing marketplace functionality...")
ctx.invoke(marketplace, []) ctx.invoke(marketplace)
# Test blockchain functionality # Test blockchain functionality
output("4. Testing blockchain functionality...") output("4. Testing blockchain functionality...")
@@ -351,7 +351,7 @@ def diagnostics(ctx, output_file):
# Test 1: Environment # Test 1: Environment
output("1. Testing environment...") output("1. Testing environment...")
try: try:
ctx.invoke(environment, ['--format', 'json']) ctx.invoke(environment, format='json')
diagnostics_data['environment'] = 'PASS' diagnostics_data['environment'] = 'PASS'
except Exception as e: except Exception as e:
diagnostics_data['environment'] = f'FAIL: {str(e)}' diagnostics_data['environment'] = f'FAIL: {str(e)}'
@@ -360,7 +360,7 @@ def diagnostics(ctx, output_file):
# Test 2: API Connectivity # Test 2: API Connectivity
output("2. Testing API connectivity...") output("2. Testing API connectivity...")
try: try:
ctx.invoke(api, ['--endpoint', 'health']) ctx.invoke(api, endpoint='health')
diagnostics_data['api_connectivity'] = 'PASS' diagnostics_data['api_connectivity'] = 'PASS'
except Exception as e: except Exception as e:
diagnostics_data['api_connectivity'] = f'FAIL: {str(e)}' diagnostics_data['api_connectivity'] = f'FAIL: {str(e)}'
@@ -369,7 +369,7 @@ def diagnostics(ctx, output_file):
# Test 3: Wallet Creation # Test 3: Wallet Creation
output("3. Testing wallet creation...") output("3. Testing wallet creation...")
try: try:
ctx.invoke(wallet, ['--wallet-name', 'diagnostics-test', '--test-operations']) ctx.invoke(wallet, wallet_name='diagnostics-test', test_operations=True)
diagnostics_data['wallet_creation'] = 'PASS' diagnostics_data['wallet_creation'] = 'PASS'
except Exception as e: except Exception as e:
diagnostics_data['wallet_creation'] = f'FAIL: {str(e)}' diagnostics_data['wallet_creation'] = f'FAIL: {str(e)}'
@@ -378,7 +378,7 @@ def diagnostics(ctx, output_file):
# Test 4: Marketplace # Test 4: Marketplace
output("4. Testing marketplace...") output("4. Testing marketplace...")
try: try:
ctx.invoke(marketplace, []) ctx.invoke(marketplace)
diagnostics_data['marketplace'] = 'PASS' diagnostics_data['marketplace'] = 'PASS'
except Exception as e: except Exception as e:
diagnostics_data['marketplace'] = f'FAIL: {str(e)}' diagnostics_data['marketplace'] = f'FAIL: {str(e)}'