Skip to content

Commit c2b876d

Browse files
committed
fix: resolve ruff linting errors and improve code quality
- Add missing return type annotations to example functions - Fix exception handling with proper chaining (raise ... from e) - Move inline imports to top-level in test files - Add missing __init__.py file for test package structure - Fix long line formatting issues throughout codebase - Improve try/except/else structure consistency - Update quote style consistency in string literals
1 parent 0d51859 commit c2b876d

File tree

7 files changed

+49
-38
lines changed

7 files changed

+49
-38
lines changed

examples/03_turnkey_wallet_integration.py

Lines changed: 19 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
import asyncio
1616
import os
1717
from decimal import Decimal
18+
from typing import Any
1819

1920
from flare_ai_kit.agents.turnkey import (
2021
AgentTransaction,
@@ -29,7 +30,7 @@
2930
from flare_ai_kit.wallet.turnkey_wallet import TurnkeySettings
3031

3132

32-
async def setup_turnkey_wallet():
33+
async def setup_turnkey_wallet() -> TurnkeyWallet:
3334
"""Set up Turnkey wallet with proper configuration."""
3435
print("🔧 Setting up Turnkey wallet...")
3536

@@ -78,7 +79,7 @@ async def setup_turnkey_wallet():
7879
return wallet
7980

8081

81-
async def create_demo_wallet(wallet: TurnkeyWallet):
82+
async def create_demo_wallet(wallet: TurnkeyWallet) -> tuple[str, str]:
8283
"""Create a demo wallet for the AI agent."""
8384
print("\n💼 Creating demo wallet...")
8485

@@ -99,7 +100,9 @@ async def create_demo_wallet(wallet: TurnkeyWallet):
99100
return "demo_wallet_id", "0x742d35Cc6634C0532925a3b8D8C8EE7c9e92bb1b"
100101

101102

102-
async def register_ai_agent(agent_connector: TurnkeyAgentConnector, wallet_id: str):
103+
async def register_ai_agent(
104+
agent_connector: TurnkeyAgentConnector, wallet_id: str
105+
) -> AgentWalletConfig:
103106
"""Register an AI agent with specific permissions."""
104107
print("\n🤖 Registering AI agent...")
105108

@@ -127,7 +130,7 @@ async def register_ai_agent(agent_connector: TurnkeyAgentConnector, wallet_id: s
127130
return agent_config if success else None
128131

129132

130-
async def simulate_tee_operation(tee_manager: TEESecurityManager):
133+
async def simulate_tee_operation(_tee_manager: TEESecurityManager) -> str:
131134
"""Simulate a TEE secure operation."""
132135
print("\n🔐 Simulating TEE secure operation...")
133136

@@ -142,18 +145,13 @@ async def simulate_tee_operation(tee_manager: TEESecurityManager):
142145
# This would normally validate against real TEE attestation
143146
print("⚠️ Note: Using mock TEE attestation for demo purposes")
144147

145-
# Create secure operation (this will fail in demo without real TEE)
146-
# secure_op = await tee_manager.create_secure_operation(
147-
# "ai_transaction",
148-
# operation_data,
149-
# mock_attestation_token
150-
# )
148+
# In production, this would create a secure operation
151149

152150
print("✅ TEE operation simulated (would validate in production)")
153151
return mock_attestation_token
154152

155153
except Exception as e:
156-
print(f"⚠️ TEE validation would fail in production: {e}")
154+
print(f"TEE operation failed: {e}")
157155
print(" Using mock attestation for demo purposes")
158156
return mock_attestation_token
159157

@@ -162,7 +160,7 @@ async def execute_ai_transaction(
162160
agent_connector: TurnkeyAgentConnector,
163161
agent_config: AgentWalletConfig,
164162
attestation_token: str,
165-
):
163+
) -> dict[str, Any]:
166164
"""Execute a transaction initiated by the AI agent."""
167165
print("\n💸 Executing AI agent transaction...")
168166

@@ -179,7 +177,9 @@ async def execute_ai_transaction(
179177
agent_transaction = AgentTransaction(
180178
agent_id=agent_config.agent_id,
181179
transaction_request=transaction_request,
182-
justification="Automated yield optimization - moving funds to higher yield protocol",
180+
justification=(
181+
"Automated yield optimization - moving funds to higher yield protocol"
182+
),
183183
confidence_score=0.85,
184184
risk_assessment="Low risk - established DeFi protocol with 99.9% uptime",
185185
)
@@ -283,7 +283,8 @@ async def demonstrate_policy_enforcement(
283283
)
284284
if not result["success"]:
285285
print(
286-
f"✅ Policy correctly blocked transaction without justification: {result['error']}"
286+
"✅ Policy correctly blocked transaction without justification: "
287+
f"{result['error']}"
287288
)
288289
else:
289290
print("❌ Policy should have blocked this transaction")
@@ -302,12 +303,10 @@ async def show_agent_status_and_history(
302303
print(f" 💼 Wallet ID: {status['wallet_id']}")
303304
print(f" 📊 Total transactions: {status['statistics']['total_transactions']}")
304305
print(f" 💰 Total value: {status['statistics']['total_value_eth']:.6f} ETH")
305-
print(
306-
f" 📈 Average confidence: {status['statistics']['avg_confidence_score']:.2f}"
307-
)
308-
print(
309-
f" 🕒 Recent transactions (24h): {status['statistics']['recent_transactions_24h']}"
310-
)
306+
avg_confidence = status["statistics"]["avg_confidence_score"]
307+
print(f" 📈 Average confidence: {avg_confidence:.2f}")
308+
recent_24h = status["statistics"]["recent_transactions_24h"]
309+
print(f" 🕒 Recent transactions (24h): {recent_24h}")
311310

312311
# Get transaction history
313312
history = await agent_connector.get_transaction_history(agent_id=agent_id, limit=10)

src/flare_ai_kit/agents/turnkey.py

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -221,12 +221,6 @@ async def execute_agent_transaction(
221221
tx_hash=signed_tx.transaction_hash,
222222
)
223223

224-
return {
225-
"success": True,
226-
"transaction_hash": signed_tx.transaction_hash,
227-
"signed_transaction": signed_tx.signed_transaction,
228-
}
229-
230224
except PermissionError as e:
231225
logger.exception(
232226
"agent_transaction_denied", agent_id=agent_id, error=str(e)
@@ -238,6 +232,12 @@ async def execute_agent_transaction(
238232
"agent_transaction_failed", agent_id=agent_id, error=str(e)
239233
)
240234
return {"success": False, "error": f"Transaction failed: {e}"}
235+
else:
236+
return {
237+
"success": True,
238+
"transaction_hash": signed_tx.transaction_hash,
239+
"signed_transaction": signed_tx.signed_transaction,
240+
}
241241

242242
async def _validate_agent_transaction(
243243
self, agent_transaction: AgentTransaction, config: AgentWalletConfig
@@ -258,7 +258,10 @@ async def _validate_agent_transaction(
258258
if agent_transaction.confidence_score < min_confidence:
259259
return {
260260
"valid": False,
261-
"reason": f"Agent confidence {agent_transaction.confidence_score} below threshold {min_confidence}",
261+
"reason": (
262+
f"Agent confidence {agent_transaction.confidence_score} "
263+
f"below threshold {min_confidence}"
264+
),
262265
}
263266

264267
# Validate justification is provided
@@ -272,7 +275,10 @@ async def _validate_agent_transaction(
272275
if tx_value > config.max_transaction_value:
273276
return {
274277
"valid": False,
275-
"reason": f"Transaction value {tx_value} ETH exceeds agent limit {config.max_transaction_value} ETH",
278+
"reason": (
279+
f"Transaction value {tx_value} ETH exceeds agent limit "
280+
f"{config.max_transaction_value} ETH"
281+
),
276282
}
277283

278284
# Additional risk-based validations could be added here

src/flare_ai_kit/wallet/permissions.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -293,7 +293,10 @@ def _check_rate_limit(
293293
PolicyViolation(
294294
policy_name=policy.name,
295295
violation_type="rate_limit_transactions",
296-
description=f"Too many transactions in {window.duration_minutes} minutes. Limit: {window.max_transactions}",
296+
description=(
297+
f"Too many transactions in {window.duration_minutes} "
298+
f"minutes. Limit: {window.max_transactions}"
299+
),
297300
suggested_action=PolicyAction.DENY,
298301
)
299302
)
@@ -307,7 +310,10 @@ def _check_rate_limit(
307310
PolicyViolation(
308311
policy_name=policy.name,
309312
violation_type="rate_limit_value",
310-
description=f"Total value in {window.duration_minutes} minutes would exceed limit {window.max_value} ETH",
313+
description=(
314+
f"Total value in {window.duration_minutes} minutes "
315+
f"would exceed limit {window.max_value} ETH"
316+
),
311317
suggested_action=PolicyAction.DENY,
312318
)
313319
)

src/flare_ai_kit/wallet/tee_security.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,8 @@ async def create_secure_operation(
4747
Create a secure operation with TEE attestation.
4848
4949
Args:
50-
operation_type: Type of operation (e.g., "wallet_creation", "transaction_signing")
50+
operation_type: Type of operation (e.g., "wallet_creation",
51+
"transaction_signing")
5152
operation_data: Operation-specific data
5253
attestation_token: TEE attestation token
5354
@@ -126,14 +127,15 @@ async def verify_operation_integrity(self, operation: SecureOperation) -> bool:
126127
# Re-validate TEE attestation
127128
try:
128129
self.vtpm_validator.validate_token(operation.attestation_token)
129-
return True
130130
except Exception as e:
131131
logger.exception(
132132
"TEE attestation re-validation failed",
133133
operation_id=operation.operation_id,
134134
error=str(e),
135135
)
136136
return False
137+
else:
138+
return True
137139

138140
async def encrypt_sensitive_data(
139141
self,
@@ -158,7 +160,7 @@ async def encrypt_sensitive_data(
158160
claims = self.vtpm_validator.validate_token(attestation_token)
159161
except Exception as e:
160162
msg = f"Invalid TEE context: {e}"
161-
raise ValueError(msg)
163+
raise ValueError(msg) from e
162164

163165
# Derive encryption key from TEE-specific data
164166
key_material = self._derive_tee_key(claims, additional_data)

tests/unit/agents/__init__.py

Whitespace-only changes.

tests/unit/agents/test_turnkey.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
AgentWalletConfig,
1010
TurnkeyAgentConnector,
1111
)
12-
from flare_ai_kit.wallet.base import TransactionRequest
12+
from flare_ai_kit.wallet.base import SignedTransaction, TransactionRequest
1313
from flare_ai_kit.wallet.turnkey_wallet import TurnkeyWallet
1414

1515

@@ -124,7 +124,7 @@ def test_confidence_score_validation(self):
124124
assert transaction.confidence_score == 0.75
125125

126126
# Invalid confidence scores should raise validation error
127-
with pytest.raises(ValueError):
127+
with pytest.raises(ValueError, match="Confidence score must be"):
128128
AgentTransaction(
129129
agent_id="test_agent",
130130
transaction_request=TransactionRequest(
@@ -183,7 +183,6 @@ async def test_execute_agent_transaction_success(
183183
await agent_connector.register_agent(agent_config)
184184

185185
# Mock successful transaction signing
186-
from flare_ai_kit.wallet.base import SignedTransaction
187186

188187
signed_tx = SignedTransaction(
189188
transaction_hash="0x123abc...",
@@ -382,7 +381,6 @@ async def test_get_transaction_history(
382381
await agent_connector.register_agent(agent_config)
383382

384383
# Mock successful transaction
385-
from flare_ai_kit.wallet.base import SignedTransaction
386384

387385
signed_tx = SignedTransaction(
388386
transaction_hash="0x123abc...",

tests/unit/wallet/test_turnkey_wallet.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
from unittest.mock import AsyncMock, MagicMock, patch
44

55
import pytest
6+
from cryptography.hazmat.primitives.asymmetric import ec
67

78
from flare_ai_kit.wallet.base import TransactionRequest, WalletAddress
89
from flare_ai_kit.wallet.permissions import PermissionEngine, PolicyViolation
@@ -269,7 +270,6 @@ def test_sign_request(self, turnkey_wallet):
269270
test_body = '{"test": "data"}'
270271

271272
# Mock private key operations
272-
from cryptography.hazmat.primitives.asymmetric import ec
273273

274274
with patch(
275275
"cryptography.hazmat.primitives.serialization.load_pem_private_key"

0 commit comments

Comments
 (0)