Skip to content

SDK Module (hierachain/sdk/*)

Overview

The SDK module provides a Python Software Development Kit that enables external applications to interact with HieraChain safely and reliably. Unlike calling REST APIs directly, the SDK includes built-in resiliency patterns to ensure applications do not hang when the network encounters issues or a node is in maintenance/lockdown mode.


Key Features

  • Dual Interface (Sync/Async)


    • Sync Client: Uses requests, suitable for simple scripts, sequential processing workers.
    • Async Client: Uses aiohttp, optimized for high-concurrency web applications (like FastAPI).
  • Smart & Flexible


    • Exponential Backoff: Automatically retries with increasing intervals on temporary network errors.
    • Circuit Breaker: Automatically "breaks the circuit" to avoid overloading the system when the service is failing.
  • System State Awareness


    • Lockdown Awareness: Automatically detects and handles errors when the Node is in lockdown mode (X-Lockdown-Mode).
    • Connection Pooling: Optimizes HTTP connection reuse to reduce latency.
    • Health Check: Checks the API's /api/ledger/health route.
  • Advanced Queries


    • Entity Tracing: Trace entity lifecycle across Sub-Chains.
    • CID Resolution: Block queries default to resolve_cid=False; with resolve_cid=True, the SDK asks the API to resolve CID data. The API resolves and decrypts details when IPFS is enabled. trace_entity() supports the same option.

Entity IDs are percent-encoded as one URL path segment for trace requests. When api_key is configured, both clients reject redirects for read requests; a 3xx response is returned as HieraChainAPIError so X-API-Key is never forwarded to a redirected origin.


Resiliency Architecture

The SDK uses a State Machine model to manage connections:

stateDiagram-v2
    [*] --> CLOSED: Normal Operation
    CLOSED --> OPEN: Failure Threshold Reached
    OPEN --> HALF_OPEN: Recovery Timeout Expired
    HALF_OPEN --> CLOSED: Success (Service Recovered)
    HALF_OPEN --> OPEN: Failure (Still Broken)

    note right of OPEN: Fails fast immediately\nwithout calling API

Usage Guide

1. Configure Client

from hierachain.sdk import HieraChainClientConfig, HieraChainClient

config = HieraChainClientConfig(
    base_url="https://api.hierachain.com",
    api_key="your_secret_key",
    max_retries=3,
    circuit_failure_threshold=5
)

2. Use Synchronous Client (For Scripts/CLI)

with HieraChainClient(config) as client:
    # Write event to supply chain
    result = client.submit_event(
        chain_name="supply_chain",
        event_data={
            "entity_id": "PRODUCT-123",
            "event_type": "quality_check",
            "details": {"status": "passed", "inspector": "QA-01"}
        }
    )
    print(f"Event ID: {result.event_id}")

3. Use Asynchronous Client (For Web/High-load)

from hierachain.sdk import HieraChainAsyncClient

async def track_product():
    async with HieraChainAsyncClient(config) as client:
        # Trace entity across chains
        trace = await client.trace_entity("PRODUCT-123")
        for event in trace.events:
            print(f"Timestamp: {event['timestamp']} - Action: {event['event']}")

Exception Handling

The SDK defines specific exception classes for applications to handle with distinct logic:

Exception Cause Handling Suggestion
CircuitOpenError System is continuously failing, SDK paused sending requests. Wait some time before retrying.
LockdownError Target node is in security lockdown mode. Check administrator notifications.
ServiceUnavailableError Server overloaded (503). GET may retry with backoff; POST is sent once.
HieraChainAPIError Logic error from the API or invalid data. Review payload and access permissions.