Substrate Interface

1.8.1 · active · verified Thu Apr 16

The `substrate-interface` library provides a Pythonic way to interact with Substrate-based blockchain nodes, including Polkadot and Kusama. It supports both traditional RPC connections and lightweight client functionality via Smoldot integration introduced in v1.8.0. The library enables querying chain state, submitting extrinsics, and managing subscriptions. It is actively maintained with frequent updates, currently at version 1.8.1.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart connects to a public Polkadot RPC endpoint, queries the chain and node information, and then retrieves the balance for a well-known test address. It demonstrates basic connection and state querying. Ensure you have network access to the specified node URL.

import os
from substrateinterface import SubstrateInterface

# Connect to a public Polkadot node by default
# Override with environment variable SUBSTRATE_NODE_URL if needed
node_url = os.environ.get('SUBSTRATE_NODE_URL', 'wss://rpc.polkadot.io')

try:
    substrate = SubstrateInterface(
        url=node_url
    )

    print(f"Connected to chain: {substrate.chain}")
    print(f"Node name: {substrate.node_name}")
    print(f"Node version: {substrate.node_version}")
    print(f"Current block number: {substrate.chain_head}")

    # Example: Query account balance for a well-known test address (Alice)
    # Override with environment variable POLKADOT_ALICE_ADDRESS if needed
    alice_address = os.environ.get('POLKADOT_ALICE_ADDRESS', '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY')
    
    # The 'System' module and 'Account' storage map are standard across Substrate chains.
    # The exact structure of the account info might vary slightly by chain/runtime version.
    result = substrate.query(
        module='System',
        function='Account',
        params=[alice_address]
    )
    
    # Accessing the free balance, typically found under 'data' and 'free'.
    # Assuming 10 decimal places for Polkadot for display purposes.
    # The '.value' attribute extracts the raw integer.
    free_balance = result['data']['free'].value
    print(f"Balance for {alice_address}: {free_balance / 10**10} DOT")

except ConnectionRefusedError:
    print(f"Error: Connection refused. Is the node running or accessible at {node_url}?")
except Exception as e:
    print(f"An unexpected error occurred: {e}")
finally:
    if 'substrate' in locals() and substrate.is_connected:
        substrate.close()

view raw JSON →