Skip to main content

A Python SDK for Somnia data streams with first class reactivity support

Project description

Somnia Data Streams Python SDK

The Somnia Data Streams Python SDK enables streaming data on-chain, integrated with off-chain reactivity to unlock new paradigms in the blockchain ecosystem.

PyPI Version

Features

  • Easy and intuitive interface and flow
  • Consistent with Somnia Data Streams JS/TS SDK
  • Schema encoding and decoding for structured data
  • Type-safe API with comprehensive type definitions
  • Asynchronized architecture for better CPU utilization on high load
  • Extensive unit tests and integration tests

Installation

pip install somnia-data-streams-sdk

Quick Start

Initialize the SDK

from somnia_data_streams_sdk import SDK, SOMNIA_TESTNET

# Read-only access (no private key needed)
sdk = SDK.create_for_chain(SOMNIA_TESTNET["id"])

# With write access (provide private key for transaction signing)
sdk = SDK.create_for_chain(SOMNIA_TESTNET["id"], private_key="0x...")

Get All Registered Schemas

schemas = await sdk.streams.get_all_schemas()
for i, schema in enumerate(schemas):
    print(f"{i+1}. {schema}")

Compute Schema ID

test_schema = "uint256 balance, address owner"
schema_id = await sdk.streams.compute_schema_id(test_schema)
print(f"\nSchema ID for '{test_schema}': {schema_id}")

Check if Schema is Registered

is_registered = await sdk.streams.is_data_schema_registered(schema_id)
print(f"Schema registered: {is_registered}")

Schema Encoding/Decoding

from somnia_data_streams_sdk import SchemaEncoder, SchemaItem

encoder = SchemaEncoder("uint256 balance, address owner")
encoded = encoder.encode_data([
    SchemaItem(name="balance", type="uint256", value=666),
    SchemaItem(name="owner", type="address", value="0x7e5f4552091a69125d5dfcb7b8c2659029395bdf"),
])
print(f"Encoded Schema: {encoded}")

decoded = encoder.decode_data(encoded)
print("Decoded Schema:")
for item in decoded:
    print(f"  {item.name} ({item.type}): {item.value.value}")

Register a Schema (Consumes Gas)

from somnia_data_streams_sdk import DataSchemaRegistration

registrations = [
    DataSchemaRegistration(
        schema_name="your-unique-id-here-otherwise-wont-register",
        schema=test_schema,
        parent_schema_id=None
    )
]
tx_hash = await sdk.streams.register_data_schemas(registrations)
if tx_hash and isinstance(tx_hash, str) and tx_hash.startswith("0x"):
    print(f"Schema registered! TX: {tx_hash}")
else:
    print("Schema already registered or registration error")

Publish Data (Consumes Gas)

from eth_utils import to_hex, keccak
from somnia_data_streams_sdk import DataStream

data_id = to_hex(keccak(text="your-unique-id-here-for-this-data"))
data_streams = [
    DataStream(
        id=data_id,
        schema_id=schema_id,
        data=encoded,
    )
]
tx_hash = await sdk.streams.set(data_streams)
if tx_hash:
    print(f"Data published! TX: {tx_hash}")
else:
    print("Data publishing failed")

Read Data

data = await sdk.streams.get_all_publisher_data_for_schema(
    schema_id=schema_id,
    publisher=sdk.streams.web3_client.client.account.address,
)
    
if data:
    print(f"Found {len(data)} data points")
    if isinstance(data[0], list):  # Decoded data
        for i, decoded_items in enumerate(data):
            print(f"\nData point {i+1}:")
            for item in decoded_items:
                print(f"  {item.name}: {item.value.value}")
    else:  # Raw data
        print("Raw data (schema not public):", data)

Register and Emit Events (Consumes Gas)

from somnia_data_streams_sdk import EventSchema, EventParameter, EventStream
from eth_utils import to_hex, keccak

# First, register an event schema
event_signature = "Transfer(address,uint256,uint256)"
event_topic = to_hex(keccak(text=event_signature))  # Compute keccak256 hash

event_schemas = [
    EventSchema(
        params=[
            EventParameter(name="user", param_type="address", is_indexed=True),
            EventParameter(name="amount", param_type="uint256", is_indexed=False),
            EventParameter(name="timestamp", param_type="uint256", is_indexed=False),
        ],
        event_topic=event_topic  # HexStr: keccak256 hash of event signature
    )
]

tx_hash = await sdk.streams.register_event_schemas(
    ids=["my-transfer-event"],
    schemas=event_schemas
)
if tx_hash and isinstance(tx_hash, str):
    print(f"Event schema registered! TX: {tx_hash}")
else:
    print("Event schema registration failed or already registered")

# Then emit events
from eth_abi import encode

event_data = encode(
    ["uint256", "uint256"],
    [1000, 1234567890]  # amount, timestamp
)

events = [
    EventStream(
        id="my-transfer-event",
        argument_topics=[to_hex(keccak(hexstr="0x" + "1234567890123456789012345678901234567890"))],  # indexed user address
        data=to_hex(event_data)
    )
]

tx_hash = await sdk.streams.emit_events(events)
if tx_hash and isinstance(tx_hash, str):
    print(f"Events emitted! TX: {tx_hash}")
else:
    print("Event emission failed")

API Reference

Main Classes

  • SDK - Main SDK class for interacting with Somnia Data Streams
  • SchemaEncoder - Encode and decode data schemas

Chain Configuration

  • SOMNIA_TESTNET - Testnet configuration (Chain ID: 50312)
  • SOMNIA_MAINNET - Mainnet configuration (Chain ID: 5031)
  • get_chain_config(chain_id) - Get chain configuration by ID
  • get_default_rpc_url(chain_id) - Get default RPC URL for a chain

Frequently Used Types

  • SubscriptionInitParams
  • SchemaItem, SchemaDecodedItem
  • EventParameter, EventSchema, EventStream
  • DataStream, DataSchemaRegistration

Contribution Guide

If it's bug fix or code improvement (i.e. not a new feature), please make sure your code passes all tests before submitting a PR.

pytest -v -s

If it's a new feature, don't forget to write unit tests and integration tests for it.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

somnia_data_streams_sdk-0.11.0.tar.gz (32.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

somnia_data_streams_sdk-0.11.0-py3-none-any.whl (30.6 kB view details)

Uploaded Python 3

File details

Details for the file somnia_data_streams_sdk-0.11.0.tar.gz.

File metadata

  • Download URL: somnia_data_streams_sdk-0.11.0.tar.gz
  • Upload date:
  • Size: 32.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.8

File hashes

Hashes for somnia_data_streams_sdk-0.11.0.tar.gz
Algorithm Hash digest
SHA256 2332b53f1ccca87f9148841b3a86a52925ff7839522aea52ab1ab81e235c6445
MD5 9309642c812a6b583232e943b4421e49
BLAKE2b-256 31c123de86a6276947adef5e9145c4b33f12d5964bb594c612f5be2fc019cddd

See more details on using hashes here.

File details

Details for the file somnia_data_streams_sdk-0.11.0-py3-none-any.whl.

File metadata

File hashes

Hashes for somnia_data_streams_sdk-0.11.0-py3-none-any.whl
Algorithm Hash digest
SHA256 eb1b8285876d4bca665571b5545eb51d7d168e10314e2c4083952b670c5fa5d6
MD5 ef1b9dab02fc9951f7dedc8de1157850
BLAKE2b-256 13d7c9ca47c4f86c1a3d3267770acd44584edb6b967331d1bea664ff06d39101

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page