diff --git a/apps/exchange/complete_cross_chain_exchange.py b/apps/exchange/complete_cross_chain_exchange.py index a1236888..b2b00d61 100755 --- a/apps/exchange/complete_cross_chain_exchange.py +++ b/apps/exchange/complete_cross_chain_exchange.py @@ -226,7 +226,7 @@ def init_database(): conn.close() return True except Exception as e: - print(f"Database initialization error: {e}") + logger.error(f"Database initialization error: {e}") return False # Cross-chain rate calculation @@ -250,10 +250,10 @@ def get_cross_chain_rate(from_chain: str, to_chain: str, from_token: str, to_tok # Fallback to 1:1 for same tokens if from_token == to_token: return 1.0 - + return 1.0 # Default fallback rate except Exception as e: - print(f"Rate calculation error: {e}") + logger.error(f"Rate calculation error: {e}") return None # Cross-chain swap execution @@ -354,9 +354,9 @@ async def process_cross_chain_swap(swap_id: str): conn.commit() conn.close() - + except Exception as e: - print(f"Cross-chain swap processing error: {e}") + logger.error(f"Cross-chain swap processing error: {e}") # API Endpoints @app.get("/health") @@ -544,9 +544,9 @@ async def process_bridge_transaction(bridge_id: str): conn.commit() conn.close() - + except Exception as e: - print(f"Bridge processing error: {e}") + logger.error(f"Bridge processing error: {e}") @app.get("/api/v1/cross-chain/bridge/{bridge_id}") async def get_bridge_transaction(bridge_id: str): diff --git a/apps/exchange/cross_chain_exchange.py b/apps/exchange/cross_chain_exchange.py index bdecd85e..c2fb410b 100755 --- a/apps/exchange/cross_chain_exchange.py +++ b/apps/exchange/cross_chain_exchange.py @@ -132,7 +132,7 @@ def init_cross_chain_tables(): conn.close() return True except Exception as e: - print(f"Cross-chain database initialization error: {e}") + logger.error(f"Cross-chain database initialization error: {e}") return False # Cross-Chain Liquidity Management @@ -165,10 +165,10 @@ def get_cross_chain_rate(from_chain: str, to_chain: str, from_token: str, to_tok if rate_a and rate_b: return rate_b / rate_a - + return None except Exception as e: - print(f"Rate calculation error: {e}") + logger.error(f"Rate calculation error: {e}") return None def get_chain_token_price(chain_id: str, token: str) -> Optional[float]: @@ -299,9 +299,9 @@ async def process_cross_chain_swap(swap_id: str): conn.commit() conn.close() - + except Exception as e: - print(f"Cross-chain swap processing error: {e}") + logger.error(f"Cross-chain swap processing error: {e}") async def lock_funds_on_chain(chain_id: str, token: str, amount: float, user_address: str) -> Optional[str]: """Lock funds on source chain""" @@ -510,9 +510,9 @@ async def process_bridge_transaction(bridge_id: str): conn.commit() conn.close() - + except Exception as e: - print(f"Bridge processing error: {e}") + logger.error(f"Bridge processing error: {e}") @app.get("/api/v1/cross-chain/bridge/{bridge_id}") async def get_bridge_transaction(bridge_id: str): diff --git a/apps/exchange/multichain_exchange_api.py b/apps/exchange/multichain_exchange_api.py index 2daa0a97..0e9de800 100755 --- a/apps/exchange/multichain_exchange_api.py +++ b/apps/exchange/multichain_exchange_api.py @@ -470,7 +470,7 @@ async def submit_trade_to_blockchain(trade_id: int, chain_id: str): conn.close() except Exception as e: - print(f"Background trade blockchain submission error: {e}") + logger.error(f"Background trade blockchain submission error: {e}") @app.get("/api/v1/stats/{chain_id}") async def get_chain_stats(chain_id: str): diff --git a/cli/aitbc_cli/commands/cross_chain.py b/cli/aitbc_cli/commands/cross_chain.py index 5a92cc83..d74c34ed 100755 --- a/cli/aitbc_cli/commands/cross_chain.py +++ b/cli/aitbc_cli/commands/cross_chain.py @@ -191,24 +191,6 @@ def status(ctx, swap_id: str): success("🔄 Swap is executing...") elif swap_data.get('status') == 'refunded': success("💰 Swap was refunded") - except NetworkError as e: - output(details, ctx.obj['output_format']) - - # Show additional status info - if swap_data.get('status') == 'completed': - success("✅ Swap completed successfully!") - elif swap_data.get('status') == 'failed': - error("❌ Swap failed") - if swap_data.get('error_message'): - error(f"Error: {swap_data['error_message']}") - elif swap_data.get('status') == 'pending': - success("⏳ Swap is pending...") - elif swap_data.get('status') == 'executing': - success("🔄 Swap is executing...") - elif swap_data.get('status') == 'refunded': - success("💰 Swap was refunded") - else: - error(f"Failed to get swap status: {response.status_code}") except Exception as e: error(f"Network error: {e}") @@ -233,27 +215,25 @@ def swaps(ctx, user_address: Optional[str], status: Optional[str], limit: int): if swaps: success(f"Found {len(swaps)} cross-chain swaps:") - - # Create table - swap_table = [] - for swap in swaps[:limit]: - swap_table.append([ - swap.get('swap_id', '')[:8] + '...', - swap.get('from_chain', ''), - swap.get('to_chain', ''), - swap.get('amount', 0), - swap.get('status', ''), - swap.get('created_at', '')[:19] - ]) - - table(["ID", "From", "To", "Amount", "Status", "Created"], swap_table) - - if len(swaps) > limit: - success(f"Showing {limit} of {len(swaps)} total swaps") - else: - success("No cross-chain swaps found") - else: - error(f"Failed to get swaps: {response.status_code}") + + # Create table + swap_table = [] + for swap in swaps[:limit]: + swap_table.append([ + swap.get('swap_id', '')[:8] + '...', + swap.get('from_chain', ''), + swap.get('to_chain', ''), + swap.get('amount', 0), + swap.get('status', ''), + swap.get('created_at', '')[:19] + ]) + + table(["ID", "From", "To", "Amount", "Status", "Created"], swap_table) + + if len(swaps) > limit: + success(f"Showing {limit} of {len(swaps)} total swaps") + else: + success("No cross-chain swaps found") except Exception as e: error(f"Network error: {e}") @@ -292,7 +272,7 @@ def bridge(ctx, source_chain: str, target_chain: str, token: str, } try: - http_client = AITBCHTTPClient(base_url="{config.exchange_service_url}", timeout=30) + http_client = AITBCHTTPClient(base_url=config.exchange_service_url, timeout=30) bridge_result = http_client.post("/cross-chain/bridge", json=bridge_data) success("Cross-chain bridge created successfully!") output({ @@ -302,15 +282,11 @@ def bridge(ctx, source_chain: str, target_chain: str, token: str, "Token": bridge_result.get('token'), "Amount": bridge_result.get('amount'), "Bridge Fee": bridge_result.get('bridge_fee'), - "Status": bridge_result.get('status') - }, ctx.obj['output_format']) - - # Show bridge ID for tracking - success(f"Track bridge with: aitbc cross-chain bridge-status {bridge_result.get('bridge_id')}") - else: - error(f"Failed to create bridge: {response.status_code}") - if response.text: - error(f"Details: {response.text}") + "Status": bridge_result.get('status') + }, ctx.obj['output_format']) + + # Show bridge ID for tracking + success(f"Track bridge with: aitbc cross-chain bridge-status {bridge_result.get('bridge_id')}") except Exception as e: error(f"Network error: {e}") @@ -324,40 +300,38 @@ def bridge_status(ctx, bridge_id: str): http_client = AITBCHTTPClient(base_url=config.exchange_service_url, timeout=10) bridge_data = http_client.get(f"/cross-chain/bridge/{bridge_id}") success(f"Bridge Status: {bridge_data.get('status', 'unknown')}") - - # Display bridge details - details = { - "Bridge ID": bridge_data.get('bridge_id'), - "Source Chain": bridge_data.get('source_chain'), - "Target Chain": bridge_data.get('target_chain'), - "Token": bridge_data.get('token'), - "Amount": bridge_data.get('amount'), - "Recipient Address": bridge_data.get('recipient_address'), - "Status": bridge_data.get('status'), - "Created At": bridge_data.get('created_at'), - "Completed At": bridge_data.get('completed_at'), - "Bridge Fee": bridge_data.get('bridge_fee'), - "Source Tx Hash": bridge_data.get('source_tx_hash'), - "Target Tx Hash": bridge_data.get('target_tx_hash') - } - - output(details, ctx.obj['output_format']) - - # Show additional status info - if bridge_data.get('status') == 'completed': - success("✅ Bridge completed successfully!") - elif bridge_data.get('status') == 'failed': - error("❌ Bridge failed") - if bridge_data.get('error_message'): - error(f"Error: {bridge_data['error_message']}") - elif bridge_data.get('status') == 'pending': - success("⏳ Bridge is pending...") - elif bridge_data.get('status') == 'locked': - success("🔒 Bridge is locked...") - elif bridge_data.get('status') == 'transferred': - success("🔄 Bridge is transferring...") - else: - error(f"Failed to get bridge status: {response.status_code}") + + # Display bridge details + details = { + "Bridge ID": bridge_data.get('bridge_id'), + "Source Chain": bridge_data.get('source_chain'), + "Target Chain": bridge_data.get('target_chain'), + "Token": bridge_data.get('token'), + "Amount": bridge_data.get('amount'), + "Recipient Address": bridge_data.get('recipient_address'), + "Status": bridge_data.get('status'), + "Created At": bridge_data.get('created_at'), + "Completed At": bridge_data.get('completed_at'), + "Bridge Fee": bridge_data.get('bridge_fee'), + "Source Tx Hash": bridge_data.get('source_tx_hash'), + "Target Tx Hash": bridge_data.get('target_tx_hash') + } + + output(details, ctx.obj['output_format']) + + # Show additional status info + if bridge_data.get('status') == 'completed': + success("✅ Bridge completed successfully!") + elif bridge_data.get('status') == 'failed': + error("❌ Bridge failed") + if bridge_data.get('error_message'): + error(f"Error: {bridge_data['error_message']}") + elif bridge_data.get('status') == 'pending': + success("⏳ Bridge is pending...") + elif bridge_data.get('status') == 'locked': + success("🔒 Bridge is locked...") + elif bridge_data.get('status') == 'transferred': + success("🔄 Bridge is transferring...") except Exception as e: error(f"Network error: {e}") diff --git a/pyproject.toml.backup.clean b/pyproject.toml.backup.clean new file mode 100644 index 00000000..6be9440f --- /dev/null +++ b/pyproject.toml.backup.clean @@ -0,0 +1,243 @@ +[tool.poetry] +name = "aitbc" +version = "0.6.0" +description = "AI Agent Compute Network - Main Project" +authors = ["AITBC Team"] + + + +[tool.poetry.dependencies] +python = ">=3.13,<3.14" +# Core Web Framework +fastapi = ">=0.115.6" +uvicorn = {extras = ["standard"], version = ">=0.34.0"} +gunicorn = ">=23.0.0" +starlette = ">=0.49.1" +# Database & ORM +sqlalchemy = {extras = ["asyncio"], version = ">=2.0.49"} +sqlmodel = ">=0.0.38" +alembic = ">=1.18.4" +aiosqlite = ">=0.20.0" +asyncpg = ">=0.30.0" +# Configuration & Environment +pydantic = ">=2.11.0" +pydantic-settings = ">=2.13.1" +python-dotenv = ">=1.1.0" +# Rate Limiting & Security +slowapi = ">=0.1.9" +limits = ">=5.8.0" +prometheus-client = ">=0.21.1" +# HTTP Client & Networking +httpx = ">=0.28.1" +requests = ">=2.32.4" +urllib3 = ">=2.6.3" +aiohttp = ">=3.12.14" +aiostun = ">=0.1.0" +# Cryptocurrency & Blockchain +cryptography = ">=46.0.0" +pynacl = ">=1.6.2" +base58 = ">=2.1.1" +bech32 = ">=1.2.0" +web3 = ">=7.15.0" +eth-account = ">=0.13.7" +# Data Processing +pandas = ">=2.2.3" +numpy = ">=2.2.0" +# Machine Learning & AI +torch = ">=2.11.0" +torchvision = ">=0.26.0" +# CLI Tools +click = ">=8.3.2" +rich = ">=14.3.3" +typer = ">=0.24.1" +click-completion = ">=0.5.2" +tabulate = ">=0.10.0" +colorama = ">=0.4.6" +keyring = ">=25.7.0" +# JSON & Serialization +orjson = ">=3.11.0" +msgpack = ">=1.1.2" +python-multipart = ">=0.0.27" +# Logging & Monitoring +structlog = ">=25.1.0" +sentry-sdk = ">=2.20.0" +# Utilities +python-dateutil = ">=2.9.0" +pytz = ">=2026.1" +schedule = ">=1.2.2" +aiofiles = ">=25.1.0" +pyyaml = ">=6.0.2" +# Async Support +asyncio-mqtt = ">=0.16.2" +websockets = ">=14.1.0" +# Image Processing (for AI services) +pillow = ">=11.1.0" +opencv-python = ">=4.11.0" +# Additional Dependencies +redis = ">=5.2.1" +psutil = ">=6.1.0" +tenseal = ">=0.3.0" +idna = ">=3.7" +hypothesis = "^6.152.4" + +[tool.poetry.group.dev.dependencies] +pytest = "9.0.3" +pytest-asyncio = "1.3.0" +pytest-timeout = "2.4.0" +black = "24.4.2" +flake8 = "7.3.0" +ruff = "0.15.10" +mypy = "2.0.0" +isort = "8.0.1" +pre-commit = "4.5.1" +bandit = "1.9.4" +pydocstyle = "6.3.0" +pyupgrade = "3.21.2" +safety = "3.7.0" +pytest-cov = "6.0.0" +types-requests = ">=2.32.0" +types-PyYAML = ">=6.0.0" +types-python-dateutil = ">=2.9.0" + +[tool.black] +line-length = 127 +target-version = ['py313'] +include = '\.pyi?$' +extend-exclude = ''' +/( + # directories + \.eggs + | \.git + | \.hg + | \.mypy_cache + | \.tox + | \.venv + | build + | dist +)/ +''' + +[tool.isort] +profile = "black" +line_length = 127 +multi_line_output = 3 +include_trailing_comma = true +force_grid_wrap = 0 +use_parentheses = true +ensure_newline_before_comments = true + +[tool.mypy] +python_version = "3.13" +warn_return_any = true +warn_unused_configs = true +# Start with less strict mode and gradually increase +check_untyped_defs = false +disallow_incomplete_defs = true +disallow_untyped_defs = true +disallow_untyped_decorators = false +no_implicit_optional = false +warn_redundant_casts = true +warn_unused_ignores = true +warn_no_return = true +warn_unreachable = false +strict_equality = false + +[[tool.mypy.overrides]] +module = [ + "torch.*", + "cv2.*", + "pandas.*", + "numpy.*", + "web3.*", + "eth_account.*", + "sqlalchemy.*", + "alembic.*", + "uvicorn.*", + "fastapi.*", +] +ignore_missing_imports = true + +[[tool.mypy.overrides]] +module = [ + "apps.coordinator-api.src.app.routers.*", + "apps.coordinator-api.src.app.services.*", + "apps.coordinator-api.src.app.storage.*", + "apps.coordinator-api.src.app.utils.*", + "apps.coordinator-api.src.app.domain.global_marketplace", + "apps.coordinator-api.src.app.domain.cross_chain_reputation", + "apps.coordinator-api.src.app.domain.agent_identity", +] +ignore_errors = true + +[tool.ruff] +line-length = 127 +target-version = "py313" + +[tool.ruff.lint] +select = [ + "E", # pycodestyle errors + "W", # pycodestyle warnings + "F", # pyflakes + "I", # isort + "B", # flake8-bugbear + "C4", # flake8-comprehensions + "UP", # pyupgrade + "E722", # bare except (explicitly enforce) + "G", # logging-string-format (enforce f-strings in logging) + "LOG", # logging best practices +] +ignore = [ + "E501", # line too long, handled by black + "B008", # do not perform function calls in argument defaults + "C901", # too complex + "G001", # logging-string-format (allow for now, migration in progress) + "G002", # logging-string-format (allow for now, migration in progress) +] + +[tool.ruff.lint.per-file-ignores] +"__init__.py" = ["F401"] +"tests/*" = ["B011"] + +[tool.pydocstyle] +convention = "google" +add_ignore = ["D100", "D101", "D102", "D103", "D104", "D105", "D106", "D107"] + +[tool.pytest.ini_options] +asyncio_mode = "auto" +asyncio_default_fixture_loop_scope = "function" +minversion = "8.0" +addopts = "-ra -q --strict-markers --strict-config --cov=apps --cov=packages --cov=cli --cov-report=term-missing --cov-report=html --cov-fail-under=50" +testpaths = ["tests"] +python_files = ["test_*.py", "*_test.py"] +python_classes = ["Test*"] +python_functions = ["test_*"] +markers = [ + "slow: marks tests as slow (deselect with '-m \"not slow\"')", + "integration: marks tests as integration tests", + "unit: marks tests as unit tests", +] + +[tool.coverage.run] +source = ["apps", "packages", "cli"] +omit = [ + "*/tests/*", + "*/test_*.py", + "*/__pycache__/*", + "*/migrations/*", + "*/venv/*", +] + +[tool.coverage.report] +exclude_lines = [ + "pragma: no cover", + "def __repr__", + "raise AssertionError", + "raise NotImplementedError", + "if __name__ == .__main__.:", + "if TYPE_CHECKING:", + "@abstractmethod", +] + +[build-system] +requires = ["poetry-core>=1.0.0"] +build-backend = "poetry.core.masonry.api"