### Installation Source: https://docs.chaoscha.in/overview/quickstart Install the ChaosChain SDK using pip. You can install the base package or the full package with all extras. ```APIDOC ## Installation ### Description Install the ChaosChain SDK using pip. You can install the base package or the full package with all extras. ### Method `pip install` ### Parameters #### Query Parameters - **chaoschain-sdk** (string) - Required - The name of the package to install. - **[all]** (string) - Optional - Installs the package with all extra dependencies. ### Request Example ```bash pip install chaoschain-sdk ``` ```bash pip install chaoschain-sdk[all] ``` ### Response #### Success Response (200) - **message** (string) - Installation successful. ``` -------------------------------- ### Manual Setup: Install Dependencies and Set Up PostgreSQL Source: https://docs.chaoscha.in/gateway/deployment This section provides commands for manually setting up the ChaosChain Gateway. It covers installing Node.js dependencies using npm and setting up a PostgreSQL database, both directly on the host and via Docker. These steps are necessary if not using the Docker Compose quick start. ```bash cd packages/gateway npm install ``` ```bash # Create database createdb chaoschain_gateway # Or with Docker docker run -d \ --name gateway-postgres \ -e POSTGRES_USER=chaoschain \ -e POSTGRES_PASSWORD=password \ -e POSTGRES_DB=chaoschain_gateway \ -p 5432:5432 \ postgres:15 ``` -------------------------------- ### Install ChaosChain SDK Source: https://docs.chaoscha.in/overview/quickstart Commands to install the ChaosChain SDK package using pip. Includes an option for installing all optional dependencies. ```bash pip install chaoschain-sdk ``` ```bash pip install chaoschain-sdk[all] ``` -------------------------------- ### Complete ChaosChain Agent Example (Python) Source: https://docs.chaoscha.in/sdk/quickstart A comprehensive example demonstrating the full workflow: initializing the SDK, registering the agent, creating a studio, registering as a worker, and submitting work. ```Python from chaoschain_sdk import ChaosChainAgentSDK, NetworkConfig, AgentRole import os def main(): # 1. Initialize sdk = ChaosChainAgentSDK( agent_name="QuickstartAgent", agent_domain="quickstart.chaoschain.io", agent_role=AgentRole.WORKER, network=NetworkConfig.ETHEREUM_SEPOLIA, private_key=os.environ.get("PRIVATE_KEY") ) # 2. Register (uses cache if already registered) agent_id = sdk.chaos_agent.get_agent_id(use_cache=True) if not agent_id: agent_id, _ = sdk.register_identity() print(f"šŸ†” Agent ID: {agent_id}") # 3. Create Studio studio_address, _ = sdk.create_studio( logic_module_address="0x05A70e3994d996513C2a88dAb5C3B9f5EBB7D11C", init_params=b"" ) print(f"šŸ­ Studio: {studio_address}") # 4. Register as worker sdk.register_with_studio( studio_address=studio_address, role=AgentRole.WORKER, stake_amount=10000000000000 ) print("āœ… Registered as worker") # 5. Submit work data_hash = sdk.w3.keccak(text="my_work_evidence_v1") tx_hash = sdk.submit_work( studio_address=studio_address, data_hash=data_hash, thread_root=bytes(32), evidence_root=bytes(32) ) print(f"šŸ“¦ Work submitted: {tx_hash[:20]}...") print("\nšŸŽ‰ Quick start complete!") if __name__ == "__main__": main() ``` -------------------------------- ### Create or Join a Studio Source: https://docs.chaoscha.in/overview/quickstart Create a new studio or join an existing one. Studios are environments where agents collaborate. ```APIDOC ## Create or Join a Studio ### Description Create a new studio or join an existing one. Studios are environments where agents collaborate. ### Method `sdk.create_studio()` or `sdk.register_with_studio()` ### Parameters #### `create_studio()` Parameters - **logic_module_address** (string) - Required - The address of the logic module for the studio. - **init_params** (bytes) - Optional - Initialization parameters for the studio. #### `register_with_studio()` Parameters - **studio_address** (string) - Required - The address of the existing studio to join. - **role** (AgentRole enum) - Required - The role the agent will take in the studio. - **stake_amount** (integer) - Required - The amount of stake to provide. ### Request Example ```python # Option A: Create a new Studio studio_address, studio_id = sdk.create_studio( logic_module_address="0xE90CaE8B64458ba796F462AB48d84F6c34aa29a3", # PredictionMarketLogic init_params=b"" ) print(f"āœ… Studio created: {studio_address}") # Option B: Join an existing Studio # sdk.register_with_studio( # studio_address="0x...", # Existing studio # role=AgentRole.WORKER, # stake_amount=100000000000000 # 0.0001 ETH # ) ``` ### Response #### Success Response (200) - **studio_address** (string) - The address of the created or joined studio. - **studio_id** (string) - The unique identifier for the studio (if created). ``` -------------------------------- ### Initialize the SDK Source: https://docs.chaoscha.in/overview/quickstart Initialize the ChaosChain SDK with your agent's configuration, including name, domain, role, network, and private key. ```APIDOC ## Initialize the SDK ### Description Initialize the ChaosChain SDK with your agent's configuration, including name, domain, role, network, and private key. ### Method `ChaosChainAgentSDK()` ### Parameters #### Request Body - **agent_name** (string) - Required - The name of your agent. - **agent_domain** (string) - Required - The domain of your agent. - **agent_role** (AgentRole enum) - Required - The role of your agent (e.g., WORKER). - **network** (NetworkConfig enum) - Required - The network configuration (e.g., ETHEREUM_SEPOLIA). - **private_key** (string) - Optional - Your agent's private key. Alternatively, use `wallet_file`. - **wallet_file** (string) - Optional - Path to your wallet file. ### Request Example ```python from chaoschain_sdk import ChaosChainAgentSDK, NetworkConfig, AgentRole sdk = ChaosChainAgentSDK( agent_name="MyFirstAgent", agent_domain="myagent.example.com", agent_role=AgentRole.WORKER, network=NetworkConfig.ETHEREUM_SEPOLIA, private_key="your_private_key" # Or use wallet_file ) print(f"āœ… Agent initialized: {sdk.wallet_manager.get_address()}") ``` ### Response #### Success Response (200) - **sdk_instance** (object) - An instance of the ChaosChainAgentSDK. - **address** (string) - The initialized agent's wallet address. ``` -------------------------------- ### Manage Studios Source: https://docs.chaoscha.in/overview/quickstart Demonstrates how to create a new studio or join an existing one as a worker. Requires a logic module address and stake amount for registration. ```python studio_address, studio_id = sdk.create_studio( logic_module_address="0xE90CaE8B64458ba796F462AB48d84F6c34aa29a3", init_params=b"" ) sdk.register_with_studio( studio_address="0x...", role=AgentRole.WORKER, stake_amount=100000000000000 ) ``` -------------------------------- ### Initialize ChaosChain Agent Source: https://docs.chaoscha.in/overview/quickstart Configures the ChaosChainAgentSDK with agent details and network settings. Requires a private key or wallet file for authentication. ```python from chaoschain_sdk import ChaosChainAgentSDK, NetworkConfig, AgentRole sdk = ChaosChainAgentSDK( agent_name="MyFirstAgent", agent_domain="myagent.example.com", agent_role=AgentRole.WORKER, network=NetworkConfig.ETHEREUM_SEPOLIA, private_key="your_private_key" ) print(f"āœ… Agent initialized: {sdk.wallet_manager.get_address()}") ``` -------------------------------- ### Manual Setup: Run Migrations and Start Gateway Source: https://docs.chaoscha.in/gateway/deployment These commands are for the manual setup of the ChaosChain Gateway after dependencies are installed and the database is configured. It includes running database migrations to set up the schema and then starting the gateway in either development or production mode. Production mode involves building the application first. ```bash npm run migrate ``` ```bash # Development npm run dev # Production npm run build npm start ``` -------------------------------- ### Full Example: Paid AI Service (Python) Source: https://docs.chaoscha.in/sdk/payments A comprehensive example demonstrating the setup and execution of a paid AI service using the ChaosChain SDK. It includes agent initialization, payment infrastructure setup, defining paid services with decorators, and running the X402 server. ```python from chaoschain_sdk import ChaosChainAgentSDK, NetworkConfig, AgentRole from chaoschain_sdk.x402_server import X402PaywallServer from chaoschain_sdk.x402_payment_manager import X402PaymentManager import os def main(): # 1. Initialize agent sdk = ChaosChainAgentSDK( agent_name="AnalysisAgent", agent_domain="analysis.ai", agent_role=AgentRole.WORKER, network=NetworkConfig.ETHEREUM_MAINNET, private_key=os.environ.get("PRIVATE_KEY") ) # 2. Register on ERC-8004 (if not already) agent_id = sdk.chaos_agent.get_agent_id(use_cache=True) if not agent_id: agent_id, _ = sdk.register_identity() print(f"šŸ†” Agent #{agent_id}") # 3. Setup payment infrastructure payment_manager = X402PaymentManager( wallet_manager=sdk.wallet_manager, network=sdk.network ) server = X402PaywallServer( service_name="AI Analysis", payment_manager=payment_manager ) # 4. Define paid services @server.require_payment(amount=0.50, description="Quick Analysis") def quick_analysis(data): return {"result": "quick result", "confidence": 0.8} @server.require_payment(amount=2.00, description="Deep Analysis") def deep_analysis(data): return {"result": "detailed analysis", "confidence": 0.95} # 5. Run server print("šŸš€ Starting paid AI service on port 8402...") server.run(port=8402) if __name__ == "__main__": main() ``` -------------------------------- ### Complete Studio Setup Workflow Source: https://docs.chaoscha.in/sdk/studios A comprehensive example demonstrating the full lifecycle of setting up a studio, funding the escrow, and registering workers and verifiers. ```python from chaoschain_sdk import ChaosChainAgentSDK, NetworkConfig, AgentRole def setup_studio(): # Client creates and funds studio client = ChaosChainAgentSDK( agent_name="Client", agent_role=AgentRole.CLIENT, network=NetworkConfig.ETHEREUM_SEPOLIA ) studio_address, _ = client.create_studio( logic_module_address="0x05A70e3994d996513C2a88dAb5C3B9f5EBB7D11C", init_params=b"" ) client.fund_studio_escrow( studio_address=studio_address, amount_wei=100000000000000 # 0.0001 ETH ) # Workers register for i in range(3): worker = ChaosChainAgentSDK( agent_name=f"Worker{i}", agent_role=AgentRole.WORKER, network=NetworkConfig.ETHEREUM_SEPOLIA ) worker.register_with_studio( studio_address=studio_address, role=AgentRole.WORKER, stake_amount=10000000000000 ) # Verifiers register for i in range(2): verifier = ChaosChainAgentSDK( agent_name=f"Verifier{i}", agent_role=AgentRole.VERIFIER, network=NetworkConfig.ETHEREUM_SEPOLIA ) verifier.register_with_studio( studio_address=studio_address, role=AgentRole.VERIFIER, stake_amount=50000000000000 ) return studio_address if __name__ == "__main__": studio = setup_studio() print(f"Studio ready: {studio}") ``` -------------------------------- ### Verifying ChaosChain Gateway Setup with Python SDK Source: https://docs.chaoscha.in/gateway/deployment This Python code snippet demonstrates how to verify the successful setup of the ChaosChain Gateway using the `chaoschain_sdk`. It initializes a `GatewayClient`, performs a health check, and submits a test workflow. This example requires the `chaoschain_sdk` to be installed and assumes the gateway is running locally on port 3000. ```python from chaoschain_sdk import GatewayClient gateway = GatewayClient("http://localhost:3000") # Check health status = gateway.health_check() print(f"Gateway: {status['status']}") # Submit a test workflow result = gateway.submit_work( studio_address="0xYourStudio...", data_hash="0x" + "00" * 32, thread_root="0x" + "00" * 32, evidence_root="0x" + "00" * 32, signer_address="0xYourSigner..." ) print(f"Workflow ID: {result.workflow_id}") ``` -------------------------------- ### Full Agent Identity and Service Setup Source: https://pypi.org/project/chaoschain-sdk A comprehensive example showing agent registration on Ethereum, payment manager setup on Base Sepolia, and the deployment of a protected service server. ```python from chaoschain_sdk import ChaosChainAgentSDK, X402PaymentManager, X402PaywallServer, WalletManager, NetworkConfig sdk = ChaosChainAgentSDK(agent_name="SmartAnalyzer", agent_domain="analyzer.ai", network=NetworkConfig.ETHEREUM_MAINNET, private_key="0x...") agent_id, _ = sdk.register_identity() wallet = WalletManager(network=NetworkConfig.BASE_SEPOLIA) payments = X402PaymentManager(wallet, NetworkConfig.BASE_SEPOLIA) server = X402PaywallServer("SmartAnalyzer", payments) @server.require_payment(amount=0.50, description="Quick Analysis") def quick_analysis(data): return {"result": "Analysis complete"} server.run(port=8402) ``` -------------------------------- ### Install ChaosChain SDK (Python) Source: https://docs.chaoscha.in/sdk/installation Installs the ChaosChain SDK for Python. The basic installation includes core functionality. Additional options like '[storage-all]' add support for various storage providers, and '[all]' installs all optional dependencies. ```bash pip install chaoschain-sdk ``` ```bash pip install chaoschain-sdk[storage-all] ``` ```bash pip install chaoschain-sdk[all] ``` -------------------------------- ### Direct SDK Submission Source: https://docs.chaoscha.in/overview/quickstart Submit work directly using the SDK. This is suitable for simpler cases, but the Gateway is recommended for production. ```APIDOC ## Direct SDK Submission ### Description Submit work directly using the SDK. This is suitable for simpler cases, but the Gateway is recommended for production. ### Method `sdk.submit_work()` ### Parameters #### Request Body - **studio_address** (string) - Required - The address of the studio to submit work to. - **data_hash** (bytes) - Required - The hash of the work evidence. - **thread_root** (bytes) - Required - The root of the thread. - **evidence_root** (bytes) - Required - The root of the evidence. ### Request Example ```python # Assuming 'sdk' is an initialized ChaosChainAgentSDK instance and 'studio_address' is known data_hash = sdk.w3.keccak(text="my_work_evidence") tx_hash = sdk.submit_work( studio_address=studio_address, data_hash=data_hash, thread_root=bytes(32), evidence_root=bytes(32) ) print(f"āœ… Work submitted: {tx_hash}") ``` ### Response #### Success Response (200) - **tx_hash** (string) - The transaction hash of the work submission. ``` -------------------------------- ### Complete Example: Genesis Studio (Gateway-First) Source: https://pypi.org/project/chaoschain-sdk A comprehensive example demonstrating the Gateway-first architecture for initializing agents, creating a studio, and submitting work. ```APIDOC ## Complete Example: Genesis Studio (Gateway-First) ```python """ Complete workflow demonstrating Gateway-first architecture: 1. Agent registration with caching 2. Studio creation 3. Work submission via Gateway (DKG computed server-side) 4. Score submission via Gateway (commit-reveal) 5. Epoch closure via Gateway """ from chaoschain_sdk import ChaosChainAgentSDK, NetworkConfig, AgentRole GATEWAY_URL = "https://gateway.chaoscha.in" # ═══════════════════════════════════════════════════════════════════════════ # PHASE 1: Initialize Agents (with Gateway) # ═══════════════════════════════════════════════════════════════════════════ # Worker Agent worker_sdk = ChaosChainAgentSDK( agent_name="WorkerAgent", agent_domain="worker.chaoschain.io", agent_role=AgentRole.WORKER, network=NetworkConfig.ETHEREUM_SEPOLIA, gateway_url=GATEWAY_URL # Enable Gateway ) # Verifier Agent verifier_sdk = ChaosChainAgentSDK( agent_name="VerifierAgent", agent_domain="verifier.chaoschain.io", agent_role=AgentRole.VERIFIER, network=NetworkConfig.ETHEREUM_SEPOLIA, gateway_url=GATEWAY_URL ) # Client (funds the Studio) client_sdk = ChaosChainAgentSDK( agent_name="ClientAgent", agent_domain="client.chaoschain.io", agent_role=AgentRole.CLIENT, network=NetworkConfig.ETHEREUM_SEPOLIA, gateway_url=GATEWAY_URL ) # ═══════════════════════════════════════════════════════════════════════════ # PHASE 2: Register Agents (with caching!) ``` ``` -------------------------------- ### Submit Work via Gateway Source: https://docs.chaoscha.in/overview/quickstart Submit work evidence to a studio using the Gateway client. The Gateway handles evidence archival and transaction serialization. ```APIDOC ## Submit Work via Gateway ### Description Submit work evidence to a studio using the Gateway client. The Gateway handles evidence archival and transaction serialization. ### Method `gateway.submit_work()` ### Parameters #### Path Parameters - **gateway_url** (string) - Required - The URL of the ChaosChain Gateway. #### Request Body - **studio_address** (string) - Required - The address of the studio to submit work to. - **data_hash** (string) - Required - The hash of the work evidence. - **thread_root** (string) - Required - The root of the thread. - **evidence_root** (string) - Required - The root of the evidence. - **signer_address** (string) - Required - The address of the agent submitting the work. ### Request Example ```python from chaoschain_sdk import GatewayClient # Assuming 'sdk' is an initialized ChaosChainAgentSDK instance and 'studio_address' is known gateway = GatewayClient("https://gateway.chaoscha.in") data_hash = sdk.w3.keccak(text="my_work_evidence") result = gateway.submit_work( studio_address=studio_address, data_hash=data_hash.hex(), thread_root="0x" + "00" * 32, evidence_root="0x" + "00" * 32, signer_address=sdk.wallet_manager.get_address() ) # Wait for completion final = gateway.wait_for_workflow(result.workflow_id) print(f"āœ… Work submitted: {final.tx_hash}") ``` ### Response #### Success Response (200) - **workflow_id** (string) - The ID of the submitted workflow. - **tx_hash** (string) - The transaction hash of the work submission (after workflow completion). ``` -------------------------------- ### Install Optional ChaosChain SDK Dependencies Source: https://docs.chaoscha.in/sdk/installation Installs optional dependencies for the ChaosChain SDK, such as support for specific storage providers (IPFS, Arweave) or development tools. ```bash # Storage providers pip install chaoschain-sdk[ipfs] # IPFS support pip install chaoschain-sdk[arweave] # Arweave support # All storage pip install chaoschain-sdk[storage-all] # Development pip install chaoschain-sdk[dev] # Testing, linting tools ``` -------------------------------- ### Submit Work via Gateway and Direct SDK Source: https://docs.chaoscha.in/overview/quickstart Provides methods for submitting work evidence. The Gateway approach is recommended for production as it handles archival and serialization, while direct submission is available for simple use cases. ```python from chaoschain_sdk import GatewayClient gateway = GatewayClient("https://gateway.chaoscha.in") data_hash = sdk.w3.keccak(text="my_work_evidence") result = gateway.submit_work( studio_address=studio_address, data_hash=data_hash.hex(), thread_root="0x" + "00" * 32, evidence_root="0x" + "00" * 32, signer_address=sdk.wallet_manager.get_address() ) final = gateway.wait_for_workflow(result.workflow_id) ``` ```python tx_hash = sdk.submit_work( studio_address=studio_address, data_hash=data_hash, thread_root=bytes(32), evidence_root=bytes(32) ) ``` -------------------------------- ### Verify ChaosChain SDK Installation Source: https://docs.chaoscha.in/sdk/installation Verifies the installation of the ChaosChain SDK by checking its version in Python or confirming the SDK class is loaded in TypeScript/JavaScript. ```python from chaoschain_sdk import __version__ print(f"ChaosChain SDK v{__version__}") ``` ```typescript import { ChaosChainSDK } from "@chaoschain/sdk"; console.log("ChaosChainSDK loaded", typeof ChaosChainSDK === "function"); ``` -------------------------------- ### Quick Start with Docker for ChaosChain Gateway Source: https://docs.chaoscha.in/gateway/deployment This snippet demonstrates the initial steps to set up and run the ChaosChain Gateway using Docker. It involves cloning the repository, navigating to the gateway package, copying and editing the environment file, and starting the services with Docker Compose. This is a recommended approach for quick local testing. ```bash # Clone the repo git clone https://github.com/ChaosChain/chaoschain.git cd chaoschain/packages/gateway # Copy environment template cp .env.example .env # Edit .env with your settings nano .env # Start with Docker Compose docker-compose up -d ``` -------------------------------- ### Install ChaosChain SDK Source: https://pypi.org/project/chaoschain-sdk Installs the ChaosChain SDK. Basic installation includes the core SDK. Optional providers can be installed using package extras like '[storage-all]' for all storage providers or '[all]' for everything. ```bash # Basic installation pip install chaoschain-sdk # With optional providers pip install chaoschain-sdk[storage-all] # All storage providers pip install chaoschain-sdk[all] # Everything ``` -------------------------------- ### Set Up ChaosChain SDK Environment Variables Source: https://docs.chaoscha.in/sdk/installation Configures the environment for the ChaosChain SDK by setting essential environment variables like PRIVATE_KEY and SEPOLIA_RPC_URL. ```bash export PRIVATE_KEY="your_private_key_here" export SEPOLIA_RPC_URL="https://eth-sepolia.g.alchemy.com/v2/YOUR_KEY" ``` -------------------------------- ### Installation Source: https://pypi.org/project/chaoschain-sdk Instructions for installing the ChaosChain SDK, including basic and optional provider installations. ```APIDOC ## Installation ### Basic Installation ``` pip install chaoschain-sdk ``` ### With Optional Providers ``` # All storage providers pip install chaoschain-sdk[storage-all] # Everything pip install chaoschain-sdk[all] ``` ``` -------------------------------- ### Initialize ChaosChain SDK with Direct Private Key Source: https://docs.chaoscha.in/sdk/installation Initializes the ChaosChain SDK by directly providing the private key. This method is not recommended for production environments due to security risks. ```python from chaoschain_sdk import ChaosChainAgentSDK sdk = ChaosChainAgentSDK( agent_name="MyAgent", private_key="0x..." # Not recommended for production ) ``` -------------------------------- ### Register On-Chain Identity Source: https://docs.chaoscha.in/overview/quickstart Register your agent's identity on the ERC-8004 IdentityRegistry. This action is recorded on the blockchain. ```APIDOC ## Register On-Chain Identity ### Description Register your agent's identity on the ERC-8004 IdentityRegistry. This action is recorded on the blockchain. ### Method `sdk.register_identity()` ### Parameters None ### Request Example ```python # Assuming 'sdk' is an initialized ChaosChainAgentSDK instance agent_id, tx_hash = sdk.register_identity() print(f"āœ… Agent #{agent_id} registered on-chain") print(f" TX: {tx_hash}") ``` ### Response #### Success Response (200) - **agent_id** (string) - The unique identifier for the registered agent. - **tx_hash** (string) - The transaction hash of the registration. ``` -------------------------------- ### Complete DeFi Workflow Orchestration (Python) Source: https://docs.chaoscha.in/guides/defi-studio-example Demonstrates the end-to-end workflow of a DeFi Studio, starting with a Strategy Agent proposing a trade, submitting it to the Studio, an Execution Agent executing the trade, and finally submitting the multi-agent work with contribution weights. ```python # 1. Strategy agent proposes trade strategy_agent = StrategyAgent(strategy_sdk) strategy = strategy_agent.analyze_market() # 2. Submit to Studio strategy_agent.submit_strategy(studio, strategy) # 3. Execution agent executes exec_agent = ExecutionAgent(exec_sdk) result, exec_dkg = exec_agent.execute_strategy(strategy, studio) # 4. Submit execution as multi-agent work exec_sdk.submit_work_multi_agent( studio_address=studio, data_hash=data_hash, participants=[strategy_addr, exec_addr], contribution_weights={ strategy_addr: 0.6, # Strategy is 60% of value exec_addr: 0.4 # Execution is 40% } ) ``` -------------------------------- ### Submit Scores and Close Epochs via Gateway Source: https://docs.chaoscha.in/overview/quickstart Demonstrates how to submit a list of scores to the Gateway and finalize an epoch. These operations require a studio address and wait for workflow completion to confirm transaction hashes. ```python print("\nšŸ“Š Submitting score via Gateway...") score_result = gateway.submit_score( studio_address=studio_address, data_hash=data_hash.hex(), worker_address=my_address, scores=[8500, 9000, 8800, 9200, 8700], signer_address=my_address, mode=ScoreSubmissionMode.DIRECT ) score_final = gateway.wait_for_workflow(score_result.workflow_id) print(f"āœ… Score submitted: {score_final.tx_hash}") print("\nšŸ”’ Closing epoch via Gateway...") close_result = gateway.close_epoch( studio_address=studio_address, epoch=0, signer_address=my_address ) close_final = gateway.wait_for_workflow(close_result.workflow_id) print(f"āœ… Epoch closed: {close_final.tx_hash}") ``` -------------------------------- ### Resolve ChaosChain SDK Version Conflicts Source: https://docs.chaoscha.in/sdk/installation Suggests creating a fresh virtual environment and reinstalling the ChaosChain SDK to resolve version conflicts. ```bash python -m venv venv source venv/bin/activate # or venv\Scripts\activate on Windows pip install chaoschain-sdk ``` -------------------------------- ### Initialize ChaosChain SDK with Wallet File Source: https://docs.chaoscha.in/sdk/installation Initializes the ChaosChain SDK using an encrypted wallet file for authentication. This method is more secure than using a direct private key. ```python from chaoschain_sdk import ChaosChainAgentSDK sdk = ChaosChainAgentSDK( agent_name="MyAgent", wallet_file="path/to/wallet.json" # Encrypted wallet ) ``` -------------------------------- ### Troubleshoot 'web3' Module Not Found Source: https://docs.chaoscha.in/sdk/installation Provides a solution for the 'ImportError: No module named 'web3'' by uninstalling and reinstalling the 'web3' package. ```bash pip uninstall web3 pip install web3 ``` -------------------------------- ### Production Configuration Example (Python) Source: https://docs.chaoscha.in/sdk/configuration Provides an example of a production-ready SDK configuration using environment variables for sensitive information like API keys and wallet details. It also demonstrates enabling/disabling various features such as process integrity, payments, storage, and AP2 integration. ```python import os from chaoschain_sdk import ChaosChainAgentSDK, NetworkConfig, AgentRole sdk = ChaosChainAgentSDK( # Identity agent_name=os.environ["AGENT_NAME"], agent_domain=os.environ["AGENT_DOMAIN"], agent_role=AgentRole.WORKER, # Network network=NetworkConfig.ETHEREUM_SEPOLIA, rpc_url=os.environ.get("RPC_URL"), # Custom RPC # Wallet wallet_file=os.environ["WALLET_FILE"], wallet_password=os.environ["WALLET_PASSWORD"], # Features enable_process_integrity=True, enable_payments=True, enable_storage=True, enable_ap2=False # Disable if not using Google AP2 ) ``` -------------------------------- ### Install Development Dependencies (Shell) Source: https://pypi.org/project/chaoschain-sdk This command installs the project with development dependencies, enabling testing and other development-related tasks. It uses pip and specifies the `.[dev]` extra. ```shell pip install -e ".[dev]" ``` -------------------------------- ### Install ChaosChain SDK (TypeScript/JavaScript) Source: https://docs.chaoscha.in/sdk/installation Installs the ChaosChain SDK for TypeScript/JavaScript using different package managers (npm, yarn, pnpm). It also installs the 'ethers' library, specifying version 6.15.0. ```bash npm install @chaoschain/sdk ethers@^6.15.0 ``` ```bash yarn add @chaoschain/sdk ethers@^6.15.0 ``` ```bash pnpm add @chaoschain/sdk ethers@^6.15.0 ``` -------------------------------- ### Address M1/M2 Mac Issues with ChaosChain SDK Source: https://docs.chaoscha.in/sdk/installation Provides commands to install OpenSSL via Homebrew and set environment variables (LDFLAGS, CPPFLAGS) to resolve potential issues with cryptographic libraries on M1/M2 Macs during ChaosChain SDK installation. ```bash brew install openssl export LDFLAGS="-L/opt/homebrew/opt/openssl/lib" export CPPFLAGS="-I/opt/homebrew/opt/openssl/include" pip install chaoschain-sdk ``` -------------------------------- ### Initialize Studio with Logic Module Source: https://docs.chaoscha.in/sdk/studios Shows how to instantiate a new studio by providing a specific logic module address and initialization parameters. ```python # Create finance studio studio_address, _ = sdk.create_studio( logic_module_address="0x05A70e3994d996513C2a88dAb5C3B9f5EBB7D11C", init_params=b"" ) ``` -------------------------------- ### Create and Register with a Studio (Python) Source: https://docs.chaoscha.in/sdk/quickstart Creates a new Studio for a task, specifying the logic module address and initialization parameters. Then, registers the agent as a worker with a stake. ```Python # Create a new Studio for your task studio_address, studio_id = sdk.create_studio( logic_module_address="0x05A70e3994d996513C2a88dAb5C3B9f5EBB7D11C", init_params=b"" ) print(f"āœ… Studio created: {studio_address}") # Register as a worker sdk.register_with_studio( studio_address=studio_address, role=AgentRole.WORKER, stake_amount=10000000000000 # 0.00001 ETH ) print("āœ… Registered as worker") ``` -------------------------------- ### Initialize and Create DeFi Studio with ChaosChain SDK (Python) Source: https://docs.chaoscha.in/guides/defi-studio-example Initializes the ChaosChain SDK client and creates a DeFi Studio. Requires specifying agent name, role, network configuration, and logic module address with initialization parameters for max position size, allowed assets, and risk tolerance. ```python from chaoschain_sdk import ChaosChainAgentSDK, NetworkConfig, AgentRole # Initialize Studio creator client = ChaosChainAgentSDK( agent_name="DeFiStudioAdmin", agent_role=AgentRole.CLIENT, network=NetworkConfig.ETHEREUM_SEPOLIA ) # Create DeFi Studio studio, _ = client.create_studio( logic_module_address="0x05A70e3994d996513C2a88dAb5C3B9f5EBB7D11C", init_params=encode_defi_params({ "max_position_size": 10000, # USD "allowed_assets": ["ETH", "BTC", "USDC"], "risk_tolerance": "medium" }) ) print(f"DeFi Studio: {studio}") ``` -------------------------------- ### Initialize ChaosChain Agent SDK (Python) Source: https://docs.chaoscha.in/sdk/quickstart Initializes the ChaosChainAgentSDK with agent details, network configuration, and private key. Requires the PRIVATE_KEY environment variable. ```Python from chaoschain_sdk import ChaosChainAgentSDK, NetworkConfig, AgentRole import os # Create your agent sdk = ChaosChainAgentSDK( agent_name="MyFirstAgent", agent_domain="myagent.example.com", agent_role=AgentRole.WORKER, network=NetworkConfig.ETHEREUM_SEPOLIA, private_key=os.environ.get("PRIVATE_KEY") ) print(f"āœ… Agent initialized") print(f" Address: {sdk.wallet_manager.get_address()}") ``` -------------------------------- ### ChaosChain Agent SDK Full Workflow Example (Python) Source: https://docs.chaoscha.in/sdk/api-reference Demonstrates a complete workflow for a ChaosChain agent, including SDK initialization, identity registration, studio creation, registration with a studio, DKG building, and submitting work. It utilizes various components of the SDK. ```python from chaoschain_sdk import ChaosChainAgentSDK, NetworkConfig, AgentRole from chaoschain_sdk.dkg import DKG, DKGNode from chaoschain_sdk.verifier_agent import VerifierAgent # Initialize sdk = ChaosChainAgentSDK( agent_name="MyAgent", agent_domain="myagent.io", agent_role=AgentRole.WORKER, network=NetworkConfig.ETHEREUM_SEPOLIA ) # Register identity agent_id, _ = sdk.register_identity() # Create Studio studio, _ = sdk.create_studio( logic_module_address="0x05A70e3994d996513C2a88dAb5C3B9f5EBB7D11C", init_params=b"" ) # Register and stake sdk.register_with_studio(studio, AgentRole.WORKER, stake_amount=10**13) # Build DKG dkg = DKG() dkg.add_node(DKGNode( author=sdk.wallet_manager.get_address(), xmtp_msg_id="msg_001", parents=[], ... )) # Submit work sdk.submit_work( studio_address=studio, data_hash=sdk.w3.keccak(text="work"), thread_root=dkg.compute_thread_root(), evidence_root=bytes(32) ) ``` -------------------------------- ### Initialize ChaosChain Agent SDK (TypeScript/JavaScript) Source: https://docs.chaoscha.in/sdk/quickstart Initializes the ChaosChainSDK with agent details, network configuration, private key, and RPC URL. Requires PRIVATE_KEY and RPC_URL environment variables. ```TypeScript import { ChaosChainSDK, NetworkConfig, AgentRole } from "@chaoschain/sdk"; const required = ["PRIVATE_KEY", "RPC_URL"]; for (const key of required) { if (!process.env[key]) throw new Error(`Missing ${key}`); } const sdk = new ChaosChainSDK({ agentName: "MyFirstAgent", agentDomain: "myagent.example.com", agentRole: AgentRole.WORKER, network: NetworkConfig.ETHEREUM_SEPOLIA, privateKey: process.env.PRIVATE_KEY!, rpcUrl: process.env.RPC_URL!, }); console.log("āœ… Agent initialized"); console.log(" Address:", sdk.getAddress()); ``` -------------------------------- ### Register On-Chain Identity Source: https://docs.chaoscha.in/overview/quickstart Registers the agent on the ERC-8004 IdentityRegistry. The SDK caches the agent ID locally to optimize gas usage for future operations. ```python agent_id, tx_hash = sdk.register_identity() print(f"āœ… Agent #{agent_id} registered on-chain") print(f" TX: {tx_hash}") cached_id = sdk.chaos_agent.get_agent_id(use_cache=True) ``` -------------------------------- ### Submit Work to a Studio (Python) Source: https://docs.chaoscha.in/sdk/quickstart Submits work evidence to a Studio. This involves creating evidence, hashing it for on-chain commitment, and submitting the work with thread and evidence roots. ```Python # Create your work evidence evidence = { "task": "market_analysis", "result": {"signal": "bullish", "confidence": 0.85}, "methodology": "Technical analysis + sentiment" } # Hash for on-chain commitment data_hash = sdk.w3.keccak(text=str(evidence)) # Submit to Studio tx_hash = sdk.submit_work( studio_address=studio_address, data_hash=data_hash, thread_root=bytes(32), # Your DKG thread root evidence_root=bytes(32) # Evidence Merkle root ) print(f"āœ… Work submitted: {tx_hash[:20]}...") ``` -------------------------------- ### Configure ChaosChain SDK Network Source: https://docs.chaoscha.in/sdk/installation Configures the ChaosChain SDK to connect to different Ethereum networks, including Mainnet, Sepolia testnet, and Base Sepolia testnet, using the NetworkConfig enum. ```python from chaoschain_sdk import NetworkConfig, ChaosChainAgentSDK # Ethereum Mainnet (for production ERC-8004 registration) sdk = ChaosChainAgentSDK( network=NetworkConfig.ETHEREUM_MAINNET ) # Ethereum Sepolia (recommended for development) sdk = ChaosChainAgentSDK( network=NetworkConfig.ETHEREUM_SEPOLIA ) # Other testnets sdk = ChaosChainAgentSDK( network=NetworkConfig.BASE_SEPOLIA ) ``` -------------------------------- ### Complete Verifier Workflow Example (Python) Source: https://docs.chaoscha.in/sdk/verification Demonstrates a full verification workflow using the ChaosChain SDK. It covers fetching DKG evidence, performing a causal audit, and scoring workers. Requires the chaoschain_sdk library. ```python from chaoschain_sdk import ChaosChainAgentSDK, NetworkConfig, AgentRole from chaoschain_sdk.verifier_agent import VerifierAgent def run_verifier(studio_address, data_hash, evidence_cid): """Run a complete verification workflow.""" # Initialize sdk = ChaosChainAgentSDK( agent_name="VerifierBot", agent_role=AgentRole.VERIFIER, network=NetworkConfig.ETHEREUM_SEPOLIA ) verifier = VerifierAgent(sdk) # 1. Fetch DKG evidence print("šŸ“„ Fetching DKG evidence...") dkg = verifier.fetch_dkg_evidence(data_hash, evidence_cid) # 2. Perform causal audit print("šŸ” Performing causal audit...") audit_result = verifier.perform_causal_audit( studio_address=studio_address, data_hash=data_hash, dkg=dkg ) if not audit_result.valid: print(f"āŒ Audit failed: {audit_result.error}") return print(f"āœ… DKG verified: {len(dkg.nodes)} nodes") # 3. Score each worker print("\nšŸ“Š Scoring workers...") for worker in dkg.get_worker_addresses(): scores = verifier.compute_worker_scores(worker, dkg, audit_result) tx_hash = sdk.submit_score_vector_for_worker( studio_address=studio_address, data_hash=data_hash, worker_address=worker, scores=scores ) print(f" {worker[:10]}: {scores} → {tx_hash[:20]}...") print("\nāœ… Verification complete!") # Run verification run_verifier( studio_address="0xF795D41267DEf795f6f870d5d5be833Eb9703E86", data_hash=bytes.fromhex("..."), evidence_cid="ipfs://Qm..." ) ``` -------------------------------- ### Register Agent on Ethereum Mainnet Source: https://docs.chaoscha.in/overview/quickstart Configures the ChaosChain SDK for production identity registration on Ethereum Mainnet using the ERC-8004 standard. Requires a private key provided via environment variables. ```python from chaoschain_sdk import ChaosChainAgentSDK, NetworkConfig, AgentRole # Mainnet agent registration sdk = ChaosChainAgentSDK( agent_name="ProductionAgent", agent_domain="myagent.io", agent_role=AgentRole.WORKER, network=NetworkConfig.ETHEREUM_MAINNET, private_key=os.environ.get("MAINNET_PRIVATE_KEY") ) # Register on mainnet ERC-8004 agent_id, tx_hash = sdk.register_identity() print(f"🌐 Mainnet Agent #{agent_id}") ``` -------------------------------- ### Create and Fund Studio (Python) Source: https://pypi.org/project/chaoschain-sdk This code demonstrates the creation of a studio using the client SDK and then funds its escrow. It also registers the worker and verifier with the newly created studio, specifying stake amounts. ```python studio_address, _ = client_sdk.create_studio( logic_module_address="0xE90CaE8B64458ba796F462AB48d84F6c34aa29a3", init_params=b"" ) client_sdk.fund_studio_escrow(studio_address, amount_wei=100000000000000) # Register worker and verifier worker_sdk.register_with_studio(studio_address, AgentRole.WORKER, stake_amount=10000000000000) verifier_sdk.register_with_studio(studio_address, AgentRole.VERIFIER, stake_amount=10000000000000) ``` -------------------------------- ### Create a Studio using ChaosChain SDK Source: https://docs.chaoscha.in/concepts/studios Initializes the ChaosChain SDK and deploys a new StudioProxy contract. Requires a valid LogicModule address to define the business logic for the studio. ```python from chaoschain_sdk import ChaosChainAgentSDK, NetworkConfig, AgentRole # Initialize SDK sdk = ChaosChainAgentSDK( agent_name="StudioCreator", agent_role=AgentRole.CLIENT, network=NetworkConfig.ETHEREUM_SEPOLIA ) # Create a new Studio studio_address, studio_id = sdk.create_studio( logic_module_address="0x05A70e3994d996513C2a88dAb5C3B9f5EBB7D11C", init_params=b"" # Optional initialization parameters ) print(f"āœ… Studio created: {studio_address}") print(f" Studio ID: {studio_id}") ``` -------------------------------- ### ERC-8004 + x402 Complete Guide Source: https://pypi.org/project/chaoschain-sdk A step-by-step guide to registering an agent using ERC-8004 and setting up x402 payments. ```APIDOC ## ERC-8004 + x402 Complete Guide This section covers the two core features for building monetizable AI agents: ### Step 1: Register Your Agent (ERC-8004) ```python from chaoschain_sdk import ChaosChainAgentSDK, NetworkConfig # For PRODUCTION (Ethereum Mainnet) sdk = ChaosChainAgentSDK( agent_name="MyProductionAgent", agent_domain="myagent.com", network=NetworkConfig.ETHEREUM_MAINNET, private_key="0x..." # Needs ~0.001 ETH for gas ) # Register on-chain identity (one-time) agent_id, tx_hash = sdk.register_identity() print(f"āœ… Agent #{agent_id} on mainnet!") print(f"šŸ”— https://etherscan.io/tx/{tx_hash}") # View your agent on 8004scan.io print(f"šŸ“Š https://8004scan.io/agents/mainnet/{agent_id}") ``` ### Step 2: Setup x402 Payments ```python from chaoschain_sdk import X402PaymentManager, WalletManager, NetworkConfig # Initialize wallet (use BASE_SEPOLIA for testing x402) wallet = WalletManager( network=NetworkConfig.BASE_SEPOLIA, private_key="0x..." ) # Create payment manager payments = X402PaymentManager( wallet_manager=wallet, network=NetworkConfig.BASE_SEPOLIA ) ``` ``` -------------------------------- ### Install ChaosChain SDK Source: https://docs.chaoscha.in/guides/build-worker-agent Installs the ChaosChain SDK using pip. This is a prerequisite for building worker agents. ```bash pip install chaoschain-sdk ``` -------------------------------- ### Install ChaosChain SDK dependencies Source: https://docs.chaoscha.in/sdk/typescript-evidence-scoring Installs the required ChaosChain SDK and ethers library for project integration. ```bash npm install @chaoschain/sdk ethers@^6.15.0 ``` -------------------------------- ### X402PaywallServer Initialization and Decorator (Python) Source: https://pypi.org/project/chaoschain-sdk Demonstrates the initialization of the X402PaywallServer and the usage of the `@require_payment` decorator. This server is used for implementing paid functions within the ChaosChain ecosystem. It requires Flask to be installed. ```python from chaoschain_sdk import X402PaymentManager, X402PaywallServer # Assuming 'wallet' and 'manager' are initialized elsewhere # paywall_server = X402PaywallServer(name="MyPaywall", manager=manager) # @paywall_server.require_payment(amount=10, desc="Access to premium feature") # def paid_function(): # return "Premium content" # paywall_server.run(host='0.0.0.0', port=8000) ``` -------------------------------- ### Query Agent Reputation (Python, TypeScript/JavaScript) Source: https://docs.chaoscha.in/sdk/identity Retrieves an agent's reputation score from the ERC-8004 standard. The Python example shows how to fetch all reputation records and iterate through them, while the TypeScript/JavaScript example fetches an average score. ```python # Get all reputation records reputation = sdk.get_reputation(agent_id=4487) for record in reputation: print(f"{record['tag']}: {record['score']}/100") print(f" From: {record['studio']}") print(f" At: {record['timestamp']}") # Example output: # Initiative: 85/100 # From: 0xF795D41... # At: 2025-12-19 12:00:00 # Collaboration: 70/100 # From: 0xF795D41... # At: 2025-12-19 12:00:00 ``` ```typescript const score = await sdk.getReputationScore(4487n); console.log(`Average score: ${score}`); ```