### Setup development environment Source: https://github.com/allora-network/allora-sdk-py/blob/dev/README.md Sets up the Python virtual environment and installs development dependencies using uv and the Makefile. This is a crucial first step for development. ```bash uv venv source .venv/bin/activate make dev ``` -------------------------------- ### Quick Start ML Inference Worker Source: https://github.com/allora-network/allora-sdk-py/blob/dev/README.md A simple example to get started with the Allora inference worker. It automatically handles network onboarding and configuration, then submits inferences. Suitable for Jupyter notebooks or Python files. ```python from allora_sdk import AlloraNetworkConfig, AlloraWorker, RunContext async def run_model(context: RunContext) -> float: # your ML model prediction logic return 123.45 async def main(): worker = AlloraWorker.inferer( topic_id=69, network=AlloraNetworkConfig.testnet(), run=run_model, ) async for result in worker.run(): if isinstance(result, Exception): print(f"Inference worker error: {result}") else: print(f"Prediction submitted to Allora: {result.submission}") # IF YOU'RE RUNNING IN A PYTHON FILE: import asyncio asyncio.run(main()) # IF YOU'RE RUNNING IN A NOTEBOOK: await main() ``` -------------------------------- ### Install Project with Development Dependencies Source: https://github.com/allora-network/allora-sdk-py/blob/dev/CLAUDE.md Install the project in editable mode along with development dependencies, specified using `.[dev]`. This is useful for setting up a complete development environment. ```bash pip install -e .[dev] ``` -------------------------------- ### Public Function Documentation Example Source: https://github.com/allora-network/allora-sdk-py/blob/dev/CLAUDE.md Example of documenting a public function with arguments, return values, and a detailed explanation. ```python def subscribe_new_block_events( self, event_name: str, conditions: List[EventAttributeCondition], callback: Callable[[Dict[str, Any], Optional[int]], None], ) -> str: """ Subscribe to specific blockchain events with filtering. This method creates a WebSocket subscription that filters events by name and attributes, calling the provided callback for each matching event. Args: event_name: The specific event type (e.g., "emissions.v9.EventScoresSet") conditions: List of attribute filters to apply callback: Function called for each event (event_data, block_height) Returns: Subscription ID for managing the subscription """ ``` ```python def _parse_websocket_message(self, raw_message: str) -> Optional[ParsedMessage]: """Parse incoming WebSocket message into structured data.""" ``` -------------------------------- ### Install Allora Python SDK Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/10-quick-reference.md Install the Allora Python SDK using pip. This is the first step before using any of the SDK's functionalities. ```bash pip install allora_sdk ``` -------------------------------- ### Full development workflow Source: https://github.com/allora-network/allora-sdk-py/blob/dev/README.md A comprehensive sequence of commands for initial setup, regenerating clients after proto changes, running tests, and building a distribution wheel. ```bash # Initial setup uv venv source .venv/bin/activate make dev # After changes to .proto files rm -rf src/allora_sdk/rpc_client/rest rm -rf src/allora_sdk/rpc_client/grpc rm -rf src/allora_sdk/rpc_client/interfaces rm -rf src/allora_sdk/rpc_client/protos make dev # Run tests tox # Build wheel for distribution make wheel # or: uv build ``` -------------------------------- ### Accessing Blockchain Modules Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/01-allora-rpc-client.md Examples of how to access and use different modules provided by the AlloraRPCClient. ```APIDOC ## Module Access The client provides access to specific blockchain modules: ```python client = AlloraRPCClient.testnet() # Auth module - account and authentication queries await client.auth.query.get_account_info(request) # Bank module - balance and token transfers await client.bank.query.get_balance(request) await client.bank.tx.send(to_address, coins) # Emissions module - Allora-specific queries and transactions await client.emissions.query.get_latest_regret_std_norm(request) await client.emissions.tx.insert_worker_payload(topic_id, inference_value, nonce) # Staking module - validator delegation await client.staking.query.get_delegations(request) # Tendermint module - blockchain info await client.tendermint.query.get_node_info(request) # Mint module - inflation and supply await client.mint.query.get_inflation(request) # Fee market module - gas price queries await client.feemarket.query.get_gas_price(request) # TX module - transaction queries await client.tx.query.get_tx(tx_hash) # Events module - WebSocket subscriptions subscription_id = await client.events.subscribe_new_block_events_typed( EventType, [EventAttributeCondition("topic_id", "=", "1")], callback ) ``` ``` -------------------------------- ### Complete Allora Worker Example Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/09-utilities.md This example demonstrates how to use various Allora SDK utilities within a worker's prediction callback. It includes fetching block time, network inference, and checking the worker's balance. ```python from allora_sdk import ( AlloraWorker, AlloraNetworkConfig, RunContext, get_block_time, get_network_inference, ) from allora_sdk.utils.format import format_allo_from_uallo async def predict(context: RunContext) -> float: # Use utilities in worker callback block_time = await get_block_time(context.client, context.nonce) print(f"Processing for block at {block_time}") # Get network inference for sanity checking bundle = await get_network_inference( context.client, context.topic_id, context.nonce ) if bundle: consensus = float(bundle.inference_value) print(f"Network consensus: {consensus}") # Check balance balance_resp = await context.client.bank.query.get_balance( QueryBalanceRequest( address=context.client.address, denom="uallo" ) ) balance = format_allo_from_uallo(balance_resp.balance.amount) print(f"Current balance: {balance}") return 123.45 async def main(): worker = AlloraWorker.inferer( topic_id=69, network=AlloraNetworkConfig.testnet(), run=predict ) async for result in worker.run(): if isinstance(result, Exception): print(f"Error: {result}") else: print(f"✓ Submitted: {result.submission}") import asyncio asyncio.run(main()) ``` -------------------------------- ### Initialize SDK from Environment Variables Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/07-worker-features.md Initialize AlloraRPCClient and AlloraWorker using environment variables for wallet and network configuration. This simplifies setup by avoiding hardcoded credentials. ```python from allora_sdk import AlloraWorker, AlloraRPCClient # Set environment variables: # MNEMONIC="word1 word2 ..." # RPC_ENDPOINT="grpc+https://..." # WEBSOCKET_ENDPOINT="wss://..." client = AlloraRPCClient.from_env() # Workers use from_env defaults worker = AlloraWorker.inferer( topic_id=69, run=predict # wallet and network default to from_env() ) ``` -------------------------------- ### Install uv with curl Source: https://github.com/allora-network/allora-sdk-py/blob/dev/README.md Installs the uv package manager using curl. Ensure you have curl installed. ```bash curl -LsSf https://astral.sh/uv/install.sh | sh ``` -------------------------------- ### Install uv with pip Source: https://github.com/allora-network/allora-sdk-py/blob/dev/README.md Installs the uv package manager using pip. This is an alternative to the curl installation method. ```bash pip install uv ``` -------------------------------- ### Install Project in Development Mode Source: https://github.com/allora-network/allora-sdk-py/blob/dev/CLAUDE.md Install the project in editable mode using `pip install -e .`. This allows changes in the source code to be reflected immediately without reinstallation. ```bash pip install -e . ``` -------------------------------- ### Direct RPC Query for Balance Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/INDEX.md Illustrates how to query an account balance using the AlloraRPCClient. This example connects to the testnet and retrieves the balance in 'uallo'. ```python client = AlloraRPCClient.testnet() balance = await client.bank.query.get_balance( QueryBalanceRequest(address=client.address, denom="uallo") ) print(f"Balance: {balance.balance.amount} uallo") ``` -------------------------------- ### Get All Topics - Python Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/10-quick-reference.md Fetches all available topics from the Allora network. Requires an initialized AlloraAPIClient. ```python from allora_sdk import AlloraAPIClient client = AlloraAPIClient() topics = await client.get_all_topics() for topic in topics: print(f"{topic.topic_id}: {topic.topic_name}") ``` -------------------------------- ### Create Subscription Function Example Source: https://github.com/allora-network/allora-sdk-py/blob/dev/CLAUDE.md Illustrates creating a new event subscription with input validation for WebSocket connection and event filter. ```python def create_subscription(self, event_filter: EventFilter) -> str: """Create new event subscription, returning subscription ID.""" if not self.websocket_connected: raise SubscriptionError("WebSocket not connected") if not event_filter.conditions: raise SubscriptionError("Event filter cannot be empty") subscription_id = self._generate_subscription_id() # ... rest of implementation return subscription_id ``` -------------------------------- ### Simple Reputer Setup Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/10-quick-reference.md Set up a basic reputer worker. This worker evaluates predictions based on a truth function and a loss function. The reputer function needs to be created using `make_reputer_function`. ```python from allora_sdk import AlloraWorker, make_reputer_function, RunContext async def get_truth(context: RunContext) -> float: return 100.0 def loss(truth: float, pred: float) -> float: return (truth - pred) ** 2 worker = AlloraWorker.reputer( topic_id=69, network=AlloraNetworkConfig.testnet(), reputer_fn=make_reputer_function(get_truth, loss) ) async for result in worker.run(): if not isinstance(result, Exception): print(f"✓ Loss: {result.submission}") ``` -------------------------------- ### Basic Inferer Example Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/INDEX.md Demonstrates how to set up and run a basic inferer worker. This worker predicts a value and prints the submission result. Ensure you have the necessary imports and configurations. ```python async def predict(context: RunContext) -> float: return 123.45 worker = AlloraWorker.inferer( topic_id=69, network=AlloraNetworkConfig.testnet(), run=predict ) async for result in worker.run(): if not isinstance(result, Exception): print(f"✓ {result.submission}") ``` -------------------------------- ### Simple Inferer Setup Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/10-quick-reference.md Set up a basic inferer worker. This worker submits predictions for a given topic to the network. Ensure your prediction function is correctly defined. ```python from allora_sdk import AlloraWorker, AlloraNetworkConfig, RunContext import asyncio async def predict(context: RunContext) -> float: # Your ML model prediction return 123.45 async def main(): worker = AlloraWorker.inferer( topic_id=69, network=AlloraNetworkConfig.testnet(), run=predict ) async for result in worker.run(): if isinstance(result, Exception): print(f"Error: {result}") else: print(f"✓ Submitted: {result.submission}") asyncio.run(main()) ``` -------------------------------- ### Example: Waiting for Transaction Confirmation Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/06-transaction-management.md Demonstrates how to insert a worker payload and wait for the transaction to be confirmed, then print the confirmation block height. ```python tx = await client.emissions.tx.insert_worker_payload(...) result = await tx.wait() print(f"Confirmed at block {result.height}") ``` -------------------------------- ### Submit Transactions with Allora RPC Client Source: https://github.com/allora-network/allora-sdk-py/blob/dev/README.md Example of submitting a transaction to the Allora network using the RPC client. This requires the client to be initialized with wallet parameters. ```python # Submit transactions response = await client.emissions.tx.insert_worker_payload( topic_id=1, inference_value="55000.0", nonce=12345 ) ``` -------------------------------- ### Run Integration Tests Source: https://github.com/allora-network/allora-sdk-py/blob/dev/CLAUDE.md Execute integration tests, which require API access and network connectivity. Ensure you have the necessary credentials and network setup. ```bash pytest tests/test_api_client_integration.py ``` -------------------------------- ### Create Reputer Function with Default Loss Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/05-loss-methods.md Example of setting up an AlloraWorker as a reputer using `make_reputer_function`. It demonstrates fetching ground truth and using a default loss function like squared error. ```python from allora_sdk import AlloraWorker, make_reputer_function, get_default_loss_fn, RunContext async def get_ground_truth(context: RunContext) -> float: # Fetch from data source return 100.0 # Use default squared error loss loss_fn = get_default_loss_fn("sqe") worker = AlloraWorker.reputer( topic_id=69, network=AlloraNetworkConfig.testnet(), reputer_fn=make_reputer_function(get_ground_truth, loss_fn) ) ``` -------------------------------- ### Implement Prediction Logic with RunContext Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/03-allora-worker.md This example shows how to use the `RunContext` within an async prediction function. Access `context.nonce` and `context.client` to perform necessary blockchain queries for inference. ```python async def predict(context: RunContext) -> float: # Use context.nonce and context.client to make queries block_time = await get_block_time(context.client, context.nonce) inference_data = await get_network_inference(context.client, context.topic_id, context.nonce) return 123.45 ``` -------------------------------- ### Reputer with Ground Truth Example Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/INDEX.md Shows how to configure a reputer worker that uses ground truth data to evaluate predictions. It requires a function to fetch the ground truth and a loss function. ```python async def get_truth(context: RunContext) -> float: return 100.0 worker = AlloraWorker.reputer( topic_id=69, reputer_fn=make_reputer_function(get_truth, lambda t, p: (t-p)**2) ) ``` -------------------------------- ### Advanced ML Inference Worker Configuration Source: https://github.com/allora-network/allora-sdk-py/blob/dev/README.md An example demonstrating advanced configuration options for the Allora inference worker. This includes detailed wallet and network settings, fee tiers, autostaking, and sanity check configurations. ```python from allora_sdk import AlloraWorker, FeeTier, AlloraWalletConfig, AlloraNetworkConfig from allora_sdk.worker.autostake import AutoStakeConfig, AutoStakeTargetType from allora_sdk.worker import SanityCheckConfig inference_worker = AlloraWorker.inferer( # # Wallet config # # Initialize with a mnemonic wallet=AlloraWalletConfig(mnemonic="..."), # # Networking config # # Helpers for common networks/environments # network = AlloraNetworkConfig.testnet(), # network = AlloraNetworkConfig.mainnet(), # network = AlloraNetworkConfig.local(), # Specify network options directly network=AlloraNetworkConfig( chain_id = "allora-testnet-1", url = "grpc+https://allora-grpc.testnet.allora.network:443", websocket_url = "wss://allora-rpc.testnet.allora.network/websocket", fee_denom = "uallo", fee_minimum_gas_price = 250_000_000.0, congestion_aware_fees = True, use_dynamic_gas_price = True, ), # Topic ID (see https://explorer.allora.network for the full list) topic_id=1, # Specify the inference function directly run=my_model, # Allora API key -- see https://developer.allora.network for a free key. # This is a convenience feature that allows the worker to fetch ALLO for gas fees on testnet. api_key="UP-…", # `fee_tier` controls how much you pay to ensure your inferences are included within # an epoch. The options are ECO, STANDARD, or PRIORITY -- default is STANDARD. fee_tier=FeeTier.PRIORITY, # `debug` enables debug logging -- very noisy. debug=True, # Optional: auto-stake this worker's rewards to a reputer (Allora emissions module) autostake=AutoStakeConfig( target_type=AutoStakeTargetType.REPUTER, target_address="allo1...reputer", ), # Or: auto-stake to a Cosmos validator (staking MsgDelegate) # autostake = AutoStakeConfig( # target_type=AutoStakeTargetType.VALIDATOR, # target_address="allovaloper1...validator", # ), # Optional sanity check (default: enabled, 60s throttle) # sanity_check=SanityCheckConfig(enabled=False), # disable # sanity_check=SanityCheckConfig(throttle_interval_seconds=30.0), ) ``` -------------------------------- ### Initialize AlloraRPCClient Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/01-allora-rpc-client.md Demonstrates various ways to initialize the AlloraRPCClient, including using default testnet/mainnet configurations, custom network settings, and environment variables. Ensure wallet configuration is provided for mainnet or custom networks. ```python from allora_sdk import AlloraRPCClient, AlloraWalletConfig, AlloraNetworkConfig # Testnet with default configuration client = AlloraRPCClient.testnet() # Mainnet with custom wallet client = AlloraRPCClient.mainnet( wallet=AlloraWalletConfig(mnemonic="word1 word2 ...") ) # Custom network client = AlloraRPCClient( network=AlloraNetworkConfig( chain_id="custom-chain-1", url="grpc+https://custom-grpc:443", websocket_url="wss://custom-ws/websocket", ), wallet=AlloraWalletConfig(private_key="0x...") ) # From environment client = AlloraRPCClient.from_env() ``` -------------------------------- ### Minimal Inferer Example Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/README.md Sets up a basic inferer to submit single predictions to a specified topic on the testnet. It defines an asynchronous prediction function and iterates over the worker's results, printing submission details. ```python from allora_sdk import AlloraWorker, AlloraNetworkConfig, RunContext async def predict(context: RunContext) -> float: return 123.45 worker = AlloraWorker.inferer( topic_id=69, network=AlloraNetworkConfig.testnet(), run=predict ) async for result in worker.run(): if not isinstance(result, Exception): print(f"✓ Submitted: {result.submission}") ``` -------------------------------- ### Query Blockchain Data Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/README.md Demonstrates how to interact with the Allora blockchain using AlloraRPCClient. Examples include checking account balances, verifying worker registration in a topic, and retrieving network inferences at a specific block. ```python from allora_sdk import AlloraRPCClient client = AlloraRPCClient.testnet() # Check balance balance = await client.bank.query.get_balance(...) # Check registration is_registered = await client.emissions.query.is_worker_registered_in_topic_id(...) # Get network inference bundle = await client.emissions.query.get_network_inferences_at_block(...) ``` -------------------------------- ### Initialize AlloraRPCClient with Mainnet Defaults Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/01-allora-rpc-client.md Create an AlloraRPCClient instance configured for the mainnet. Similar to the testnet method, it uses preset defaults and allows for optional wallet and network configuration overrides. ```python client = AlloraRPCClient.mainnet() ``` -------------------------------- ### Initialize Allora RPC Client Source: https://github.com/allora-network/allora-sdk-py/blob/dev/README.md Demonstrates various ways to initialize the AlloraRPCClient, including manual configuration, using preset defaults for testnet, overriding defaults, and initializing from environment variables. Wallet configuration is optional and only needed for sending transactions. ```python from allora_sdk import AlloraRPCClient, AlloraWalletConfig, AlloraNetworkConfig # Initialize client manually client = AlloraRPCClient( wallet=AlloraWalletConfig( mnemonic="...", # wallet config is optional, only needed for sending transactions prefix="allo", # bech32 prefix (default is "allo" for Allora Network) ), network=AlloraNetworkConfig( url="...", # RPC url websocket_url="...", # websocket url is optional, only needed for subscribing to events ) ) ``` ```python # Initialize client with preset network config defaults (testnet in this case) client = AlloraRPCClient.testnet() ``` ```python # Initialize client with preset network config, but some defaults overridden client = AlloraRPCClient.testnet( wallet=AlloraWalletConfig(mnemonic="..."), # optional, only needed for sending transactions websocket_url="...", # optional, only needed for subscribing to events ) ``` ```python # Alternatively, initialize client from environment variables: # - PRIVATE_KEY # - MNEMONIC # - MNEMONIC_FILE # - ADDRESS_PREFIX # - CHAIN_ID # - RPC_ENDPOINT # - WEBSOCKET_ENDPOINT # - FAUCET_URL # - FEE_DENOM # - FEE_MIN_GAS_PRICE client = AlloraRPCClient.from_env() ``` -------------------------------- ### AlloraRPCClient Initialization Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/01-allora-rpc-client.md Initialize the AlloraRPCClient with optional wallet, network, and debug configurations. ```APIDOC ## Constructor ```python def __init__( self, wallet: Optional[AlloraWalletConfig] = None, network: AlloraNetworkConfig = AlloraNetworkConfig.testnet(), debug: bool = False ) ``` ### Parameters | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | wallet | `Optional[AlloraWalletConfig]` | None | Wallet configuration for signing transactions | | network | `AlloraNetworkConfig` | testnet | Network configuration (testnet/mainnet/custom) | | debug | `bool` | False | Enable debug logging | **Throws:** - `ValueError`: If wallet credentials are invalid ``` -------------------------------- ### Initialize Client from Environment Variables Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/02-configuration.md Configure and initialize the RPC client by reading network and wallet information from environment variables. Ensure MNEMONIC_FILE and RPC/WEBSOCKET ENDPOINTS are set. ```python # Set environment variables: # MNEMONIC_FILE=~/.allora_key # RPC_ENDPOINT=grpc+https://allora-grpc.testnet.allora.network:443 # WEBSOCKET_ENDPOINT=wss://allora-rpc.testnet.allora.network/websocket client = AlloraRPCClient.from_env() ``` -------------------------------- ### Initialize and Use Allora API Client Source: https://github.com/allora-network/allora-sdk-py/blob/dev/README.md Demonstrates how to initialize the AlloraAPIClient and fetch active topics and the latest inference data. Requires an API key. ```python import asyncio from allora_sdk.api_client import AlloraAPIClient client = AlloraAPIClient() async def main(): # Get all active topics topics = await client.get_all_topics() print(f"Found {len(topics)} topics") # Get latest inference inference = await client.get_inference_by_topic_id(13) print(f"ETH price in 5 minutes: ${inference.inference_data.network_inference_normalized}") asyncio.run(main()) ``` -------------------------------- ### Initialize AlloraRPCClient with Testnet Defaults Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/01-allora-rpc-client.md Create an AlloraRPCClient instance configured for the testnet. This method uses preset defaults for network and WebSocket endpoints. An optional wallet configuration can be provided to override the default. ```python client = AlloraRPCClient.testnet() ``` -------------------------------- ### Initialize AlloraRPCClient from Environment Variables Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/01-allora-rpc-client.md Create an AlloraRPCClient instance by loading configuration from environment variables. This is useful for deploying applications in environments where sensitive information like private keys and endpoints are managed via environment variables. ```python client = AlloraRPCClient.from_env() ``` -------------------------------- ### Mint Module - Get Annual Provisions Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/08-blockchain-modules.md Retrieves the total amount of tokens provided annually. ```APIDOC #### get_annual_provisions() Get annual token provisions. ```python request = QueryAnnualProvisionsRequest() response = await client.mint.query.get_annual_provisions(request) # response.annual_provisions: str # Total ALLO provided annually ``` ``` -------------------------------- ### Initialize AlloraAPIClient with Custom API Key and Base URL Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/04-api-client.md Demonstrates how to initialize the AlloraAPIClient with a custom API key and a different base API URL for specific network configurations. ```python client = AlloraAPIClient( api_key="UP-your-custom-key", base_api_url="https://custom-api.example.com/v2" ) topics = await client.get_all_topics() ``` -------------------------------- ### Mint Module - Get Inflation Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/08-blockchain-modules.md Queries the current annual inflation rate of the native token. ```APIDOC ## Mint Module Token supply and inflation. ### Query Methods #### get_inflation() Get current inflation rate. ```python request = QueryInflationRequest() response = await client.mint.query.get_inflation(request) # response.inflation: str # Annual inflation rate ``` ``` -------------------------------- ### Staking Module - Get Delegations Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/08-blockchain-modules.md Retrieves all current delegations made by a specific delegator address. ```APIDOC ## get_delegations() ### Description Get all delegations for an address. ### Method Signature ```python request = QueryDelegatorDelegationsRequest(delegator_addr: str) response = await client.staking.query.get_delegations(request) # response.delegation_responses: List[DelegationResponse] ``` ``` -------------------------------- ### Get Block Time by Height Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/10-quick-reference.md Fetch the timestamp of a block given its height. Requires importing get_block_time. ```python from allora_sdk import get_block_time block_time = await get_block_time(client, height=12345) print(f"Block timestamp: {block_time}") ``` -------------------------------- ### Initialize AlloraRPCClient and AlloraWorker from Environment Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/10-quick-reference.md Initialize the AlloraRPCClient and an AlloraWorker using settings from environment variables. The worker can be configured for inference tasks, automatically reading wallet and network configurations from the environment. ```python # Use from environment from allora_sdk import AlloraRPCClient, AlloraWorker client = AlloraRPCClient.from_env() worker = AlloraWorker.inferer( topic_id=69, run=predict # Wallet and network read from environment ) ``` -------------------------------- ### get_block_time() Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/07-worker-features.md Fetches the timestamp of a block at a specified height. Useful for determining the start time of an epoch or for time-sensitive logic. ```APIDOC ## get_block_time() ### Description Fetch the timestamp of a block at the given height. ### Parameters #### Path Parameters - **client** (`AlloraRPCClient`) - Required - RPC client for queries - **height** (`int`) - Required - Block height to look up ### Returns - `datetime` - datetime object with block timestamp ### Request Example ```python from allora_sdk import get_block_time, RunContext async def predict(context: RunContext) -> float: # Get block time for this nonce/epoch block_time = await get_block_time(context.client, context.nonce) print(f"Epoch started at: {block_time}") # Use in prediction logic return 123.45 ``` ``` -------------------------------- ### Configure Wallet from Environment Variables Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/10-quick-reference.md Initialize an Allora wallet configuration by loading credentials from environment variables. Ensure the MNEMONIC environment variable is set before calling this. ```python # Set MNEMONIC environment variable first wallet = AlloraWalletConfig.from_env() ``` -------------------------------- ### Get All Topics Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/10-quick-reference.md Retrieves a list of all available topics from the Allora network. It iterates through the topics and prints their IDs and names. ```APIDOC ## Get All Topics ### Description Retrieves a list of all available topics from the Allora network. This method is useful for discovering topics and their associated metadata. ### Method `get_all_topics()` ### Parameters None ### Response - **topics** (list): A list of topic objects, where each topic has `topic_id` and `topic_name` attributes. ### Request Example ```python from allora_sdk import AlloraAPIClient client = AlloraAPIClient() topics = await client.get_all_topics() for topic in topics: print(f"{topic.topic_id}: {topic.topic_name}") ``` ``` -------------------------------- ### Tendermint Module - Get Node Info Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/08-blockchain-modules.md Fetches node information, including the network identifier (Chain ID). ```APIDOC ## Tendermint Module Blockchain metadata and block information. ### Query Methods #### get_node_info() Get node information including chain ID. ```python request = GetNodeInfoRequest() response = await client.tendermint.query.get_node_info(request) # response.default_node_info.network: str # Chain ID ``` ``` -------------------------------- ### Connect to Mainnet with Private Key Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/02-configuration.md Initialize the RPC client for the mainnet using a private key for wallet authentication. Ensure your private key is kept secure. ```python client = AlloraRPCClient( network=AlloraNetworkConfig.mainnet(), wallet=AlloraWalletConfig( private_key="0x1234567890abcdef..." ) ) ``` -------------------------------- ### Auth Module - Get Account Info Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/08-blockchain-modules.md Retrieves account information, including the sequence number necessary for transaction signing. ```APIDOC ## Auth Module Account and authentication information. ### Query Methods #### get_account_info() Get account information including sequence number for signing. ```python request = QueryAccountInfoRequest(address: str) response = await client.auth.query.get_account_info(request) # response.account: BaseAccount # .address: str # .pub_key: PublicKey # .account_number: int # .sequence: int ``` ``` -------------------------------- ### Get Unfulfilled Reputer Nonces Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/08-blockchain-modules.md Retrieves unfulfilled nonces specifically for reputer submissions to a topic. Requires only the topic ID. ```python request = GetUnfulfilledReputerNoncesRequest(topic_id: int) response = await client.emissions.query.get_unfulfilled_reputer_nonces(request) # response.nonces: Nonces # Contains list of unfulfilled nonces ``` -------------------------------- ### AlloraWalletConfig.from_env() Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/02-configuration.md Creates an AlloraWalletConfig instance by reading wallet credentials from environment variables. ```APIDOC ## AlloraWalletConfig.from_env() ### Description Creates an AlloraWalletConfig instance by reading wallet credentials from environment variables. It looks for environment variables prefixed by `env_prefix`. ### Method `classmethod` ### Parameters #### Method Parameters - **env_prefix** (Optional[str]) - None - Prefix for environment variable names ### Environment Variables Read - `{env_prefix}PRIVATE_KEY` - `{env_prefix}MNEMONIC` - `{env_prefix}MNEMONIC_FILE` - `{env_prefix}ADDRESS_PREFIX` (defaults to "allo") ``` -------------------------------- ### Handle TxError Exception Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/06-transaction-management.md Example of how to catch and extract details from a TxError exception during transaction waiting. This helps in diagnosing transaction failures. ```python try: result = await tx.wait() except TxError as e: print(f"Module: {e.codespace}") print(f"Code: {e.code}") print(f"Message: {e.message}") print(f"TX: {e.tx_hash}") ``` -------------------------------- ### Tendermint Module - Get Block By Height Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/08-blockchain-modules.md Retrieves block details for a specific block height, useful for obtaining the block timestamp. ```APIDOC #### get_block_by_height() Get block details at a specific height (used to fetch block timestamp). ```python request = GetBlockByHeightRequest(height: int) response = await client.tendermint.query.get_block_by_height(request) # response.sdk_block.header.time: datetime ``` ``` -------------------------------- ### AlloraRPCClient Instance Methods Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/01-allora-rpc-client.md Core instance methods for interacting with the blockchain client. ```APIDOC ## Instance Methods ### raise_for_chain_id_mismatch() ```python async def raise_for_chain_id_mismatch(self) -> str ``` Verify configured chain_id matches network-reported chain ID. **Returns:** Chain ID from network **Throws:** - `ValueError`: If configuration chain_id doesn't match network chain ID ### chain_id() ```python async def chain_id(self) -> str ``` Fetch the chain ID from the connected network. **Returns:** Chain ID string ### close() ```python async def close(self) ``` Close client and cleanup resources (gRPC connections, WebSocket subscriptions). ``` -------------------------------- ### Query Inflation Rate Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/08-blockchain-modules.md Get the current annual inflation rate of the network's tokens. A simple request object is used. ```python request = QueryInflationRequest() response = await client.mint.query.get_inflation(request) # response.inflation: str # Annual inflation rate ``` -------------------------------- ### Worker Callback Example Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/09-utilities.md Demonstrates how to use the RunContext within a worker's predict callback to access chain data and context information. ```python async def predict(context: RunContext) -> float: # Access the RPC client response = await context.client.emissions.query.get_latest_regret_std_norm( GetLatestRegretStdNormRequest(topic_id=context.topic_id) ) # Use topic_id and nonce print(f"Topic {context.topic_id}, nonce {context.nonce}") return 123.45 ``` -------------------------------- ### Configure Wallet from Mnemonic File Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/10-quick-reference.md Initialize an Allora wallet configuration by providing the path to a file containing the mnemonic phrase. The file should only contain the mnemonic. ```python wallet = AlloraWalletConfig( mnemonic_file="/path/to/mnemonic.txt" ) ``` -------------------------------- ### Create AlloraWalletConfig from Environment Variables Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/02-configuration.md Instantiates AlloraWalletConfig using environment variables. Specify an optional prefix to customize environment variable names. ```python @classmethod def from_env(cls, env_prefix: str | None = None) -> 'AlloraWalletConfig': # Implementation would read environment variables like # os.environ.get(f'{env_prefix}PRIVATE_KEY') etc. pass ``` -------------------------------- ### Query Bank Balance Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/08-blockchain-modules.md Use this to get the balance of a specific token denomination for an account. Requires the account's bech32 address and the denomination. ```python request = QueryBalanceRequest( address: str, #Bech32 address denom: str = "uallo" #Token denomination ) response = await client.bank.query.get_balance(request) # response.balance: Coin # {denom: "uallo", amount: "1000000"} ``` -------------------------------- ### Get Latest Regret Standard Normalization Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/08-blockchain-modules.md Retrieves the latest standard normalized regret metric for a given topic. Requires only the topic ID. ```python request = GetLatestRegretStdNormRequest(topic_id: int) response = await client.emissions.query.get_latest_regret_std_norm(request) # response.std_norm_value: str # Latest standard normalized regret ``` -------------------------------- ### Configure Wallet from Private Key Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/10-quick-reference.md Initialize an Allora wallet configuration using a private key. Private keys are sensitive and should be handled with extreme care. ```python wallet = AlloraWalletConfig( private_key="1234567890abcdef..." ) ``` -------------------------------- ### Default Fetcher Implementation Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/04-api-client.md Provides a default implementation for the Fetcher protocol using aiohttp to perform HTTP GET requests and return JSON. ```python import aiohttp class DefaultFetcher: async def fetch(self, url: str, headers: dict) -> Any: async with aiohttp.ClientSession() as session: async with session.get(url, headers=headers) as response: response.raise_for_status() return await response.json() ``` -------------------------------- ### AlloraWalletConfig Constructor Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/02-configuration.md Initializes the AlloraWalletConfig with various credential sources and an address prefix. ```APIDOC ## AlloraWalletConfig Constructor ### Description Initializes the AlloraWalletConfig with various credential sources and an address prefix. At least one credential source (private_key, mnemonic, mnemonic_file, or wallet) must be provided. ### Parameters #### Constructor Parameters - **private_key** (Optional[str]) - None - Hex-encoded private key (64 hex characters) - **mnemonic** (Optional[str]) - None - BIP39 mnemonic phrase (12-24 words) - **mnemonic_file** (Optional[str]) - None - Path to file containing mnemonic phrase - **wallet** (Optional[LocalWallet]) - None - Pre-initialized LocalWallet instance - **prefix** (str) - "allo" - Bech32 address prefix ``` -------------------------------- ### Custom Fetcher with Additional Headers Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/04-api-client.md An example of a custom fetcher that adds a custom header before making the HTTP request. Instantiate the AlloraAPIClient with this custom fetcher. ```python import aiohttp class CustomFetcher: async def fetch(self, url: str, headers: dict) -> Any: # Add custom headers or logic headers["Custom-Header"] = "value" async with aiohttp.ClientSession() as session: async with session.get(url, headers=headers) as response: response.raise_for_status() return await response.json() client = AlloraAPIClient(fetcher=CustomFetcher()) ``` -------------------------------- ### Initialize AlloraAPIClient Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/04-api-client.md Instantiate the AlloraAPIClient with optional parameters for chain ID, API key, base API URL, and a custom fetcher. A free API key can be obtained from the developer portal. ```python def __init__( self, chain_id: Optional[ChainID] = ChainID.TESTNET, api_key: Optional[str] = "UP-8cbc632a67a84ac1b4078661", base_api_url: Optional[str] = "https://api.allora.network/v2", fetcher: Fetcher = DefaultFetcher() ) ``` -------------------------------- ### Get Inference for Topic Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/10-quick-reference.md Fetches the latest inference data for a specific topic ID. It then prints the normalized network inference value, such as the ETH price. ```APIDOC ## Get Inference for Topic ### Description Fetches the latest inference data for a specific topic ID. This is useful for retrieving real-time or recent data predictions for a given topic. ### Method `get_inference_by_topic_id(topic_id: int)` ### Parameters #### Path Parameters - **topic_id** (int) - Required - The unique identifier of the topic for which to retrieve inference data. ### Response - **inference** (object): An object containing inference data. It includes `inference_data.network_inference_normalized` which provides the normalized inference value. ### Request Example ```python inference = await client.get_inference_by_topic_id(13) print(f"ETH price: ${inference.inference_data.network_inference_normalized}") ``` ``` -------------------------------- ### Access Auth Module Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/01-allora-rpc-client.md Demonstrates how to access the Auth module to query account information. ```python await client.auth.query.get_account_info(request) ``` -------------------------------- ### Get Unfulfilled Worker Nonces Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/08-blockchain-modules.md Retrieves a list of all unfulfilled (open) nonces for a topic's worker submission window. Requires only the topic ID. ```python request = GetUnfulfilledWorkerNoncesRequest(topic_id: int) response = await client.emissions.query.get_unfulfilled_worker_nonces(request) # response.nonces: Nonces # Contains list of unfulfilled nonces ``` -------------------------------- ### Simple Transaction Submission Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/06-transaction-management.md Demonstrates how to register as a worker and wait for transaction confirmation using AlloraRPCClient. ```python from allora_sdk import AlloraRPCClient, FeeTier client = AlloraRPCClient.testnet() # Register as a worker tx = await client.emissions.tx.register( topic_id=1, owner_addr=client.address, sender_addr=client.address, is_reputer=False, fee_tier=FeeTier.STANDARD ) # Wait for confirmation result = await tx.wait() print(f"Registered: {result.txhash}") ``` -------------------------------- ### AlloraRPCClient Class Methods Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/01-allora-rpc-client.md Factory methods to create an AlloraRPCClient instance configured for specific networks or environments. ```APIDOC ## Class Methods ### testnet() ```python @classmethod def testnet( cls, wallet: Optional[AlloraWalletConfig] = None, network: Optional[AlloraNetworkConfig] = None, websocket_url: Optional[str] = None ) -> AlloraRPCClient ``` Create a client configured for testnet with preset defaults. ### Parameters | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | wallet | `Optional[AlloraWalletConfig]` | None | Override wallet configuration | | network | `Optional[AlloraNetworkConfig]` | None | Override network configuration | | websocket_url | `Optional[str]` | None | Override WebSocket endpoint | **Returns:** `AlloraRPCClient` instance configured for testnet ### mainnet() ```python @classmethod def mainnet( cls, wallet: Optional[AlloraWalletConfig] = None, network: Optional[AlloraNetworkConfig] = None, websocket_url: Optional[str] = None ) -> AlloraRPCClient ``` Create a client configured for mainnet with preset defaults. ### from_env() ```python @classmethod def from_env(cls) -> AlloraRPCClient ``` Create a client from environment variables: - `PRIVATE_KEY`: Hex-encoded private key - `MNEMONIC`: Mnemonic phrase - `MNEMONIC_FILE`: Path to mnemonic file - `ADDRESS_PREFIX`: Bech32 address prefix (default: "allo") - `CHAIN_ID`: Chain ID - `RPC_ENDPOINT`: gRPC URL - `WEBSOCKET_ENDPOINT`: WebSocket URL - `FAUCET_URL`: Faucet endpoint - `FEE_DENOM`: Fee token denomination - `FEE_MIN_GAS_PRICE`: Minimum gas price ``` -------------------------------- ### Setup Forecast Worker Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/10-quick-reference.md Defines and configures a forecast worker. The `forecast` function should return a dictionary mapping inferer IDs to their predicted float values. ```python async def forecast(context: RunContext) -> dict[str, float]: return { "allo1inferer1": 123.45, "allo1inferer2": 124.50, "allo1inferer3": 123.90, } worker = AlloraWorker.forecaster( topic_id=69, network=AlloraNetworkConfig.testnet(), run=forecast ) ``` -------------------------------- ### Access Bank Module for Balance Query Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/01-allora-rpc-client.md Shows how to use the Bank module to query an account's balance. ```python await client.bank.query.get_balance(request) ``` -------------------------------- ### Accessing Blockchain Modules with AlloraRPCClient Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/08-blockchain-modules.md Demonstrates the standard pattern for interacting with blockchain modules using the AlloraRPCClient. Initialize the client and then access modules via dot notation for query or transaction methods. ```python client = AlloraRPCClient.testnet() # Pattern: client...(request) response = await client..query.(request) tx = await client..tx.(args) ``` -------------------------------- ### Use Priority Fee Tier with AlloraWorker Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/02-configuration.md Example of configuring an AlloraWorker to use the 'priority' fee tier for faster transaction inclusion. This is useful for time-sensitive operations. ```python from allora_sdk import AlloraWorker, FeeTier worker = AlloraWorker.inferer( topic_id=69, network=AlloraNetworkConfig.testnet(), run=my_model, fee_tier=FeeTier.PRIORITY # Use priority fees ) ``` -------------------------------- ### Get Inference by Topic ID - Python Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/10-quick-reference.md Retrieves the latest inference data for a specific topic ID. Ensure the topic ID exists and inferences are available. ```python inference = await client.get_inference_by_topic_id(13) print(f"ETH price: ${inference.inference_data.network_inference_normalized}") ``` -------------------------------- ### Import Wallet from Mnemonic File Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/02-configuration.md Configure the Allora wallet by providing the path to a file containing the mnemonic phrase. The file should contain only the mnemonic. ```python wallet_config = AlloraWalletConfig( mnemonic_file="/path/to/mnemonic.txt" ) ``` -------------------------------- ### Import Wallet from Environment Variables Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/02-configuration.md Configure the Allora wallet by loading credentials from environment variables. Supports private key, mnemonic string, or mnemonic file paths. ```python # Set in environment: # export PRIVATE_KEY="1234567890abcdef..." # or # export MNEMONIC="word1 word2 ..." # or # export MNEMONIC_FILE="/path/to/mnemonic" wallet_config = AlloraWalletConfig.from_env() ``` -------------------------------- ### Get Default Loss Function Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/10-quick-reference.md Retrieve a default loss function by its method name (e.g., 'sqe' for squared error or 'mse' for mean squared error). ```python from allora_sdk import get_default_loss_fn # Squared error loss_fn = get_default_loss_fn("sqe") # or loss_fn = get_default_loss_fn("mse") # Alias loss = loss_fn(100.0, 95.0) # Returns 25.0 ``` -------------------------------- ### Get Network Inference Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/10-quick-reference.md Retrieve network inference data for a given topic ID and nonce. Returns a bundle object if inference is available, otherwise None. ```python from allora_sdk import get_network_inference bundle = await get_network_inference(client, topic_id=69, nonce=12345) if bundle: print(f"Network inference: {bundle.inference_value}") ``` -------------------------------- ### Access Fee Market Module Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/01-allora-rpc-client.md Demonstrates querying gas price information from the Fee market module. ```python await client.feemarket.query.get_gas_price(request) ``` -------------------------------- ### get_default_loss_fn() Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/05-loss-methods.md Get the default loss function for a named loss method. This function returns a callable that computes the loss between a ground truth value and a predicted value. ```APIDOC ## get_default_loss_fn(loss_method: str) -> LossFn ### Description Get the default loss function for a named loss method. This function returns a callable that computes the loss between a ground truth value and a predicted value. ### Parameters #### Path Parameters - **loss_method** (str) - Required - Loss method name (case-insensitive, aliases supported) ### Returns Callable with signature `(ground_truth: float, predicted: float) -> float` ### Throws - `UnsupportedLossMethodError`: If loss method not supported ### Supported methods: | Canonical Name | Aliases | |---|---| | sqe | mse, squared_error, se | | abse | mae, absolute_error, ae | | huber | huber_loss | | logcosh | log_cosh, logcosh_loss | | bce | binary_cross_entropy, bce_loss | | poisson | poisson_loss | | ztae | ztae_loss, z_transformed_absolute_error | | zptae | zptae_loss, z_power_tanh_absolute_error | ### Example: ```python from allora_sdk import get_default_loss_fn # Get squared error loss loss_fn = get_default_loss_fn("sqe") loss = loss_fn(100.0, 95.0) # Returns 25.0 # Alias also works loss_fn = get_default_loss_fn("mse") # Same as "sqe" loss = loss_fn(100.0, 95.0) # Returns 25.0 ``` ``` -------------------------------- ### Visualize Allora Topic Lifecycle Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/09-utilities.md Use this command-line tool to analyze worker logs and visualize topic phase transitions. Specify the path to your AlloraWorker log file using the --log_file argument. ```bash allora-topic-lifecycle-visualizer --log_file worker.log ``` ```bash # Analyze worker logs allora-topic-lifecycle-visualizer --log_file ./worker.log # Output: visualization image and analysis data ``` -------------------------------- ### Connect to Testnet with Mnemonic Source: https://github.com/allora-network/allora-sdk-py/blob/dev/_autodocs/02-configuration.md Use this snippet to initialize the RPC client for the testnet using a mnemonic phrase for wallet authentication. ```python from allora_sdk import AlloraRPCClient, AlloraWalletConfig, AlloraNetworkConfig client = AlloraRPCClient( network=AlloraNetworkConfig.testnet(), wallet=AlloraWalletConfig( mnemonic="word1 word2 ... word12" ) ) ```