Skip to content

Query On-Chain State with SDKs

Introduction

Polkadot SDK-based blockchains store data in a key-value database that external applications can query. This on-chain state includes account information, balances, asset information, and any other data the runtime manages.

This guide uses Subxt, Parity's Rust library for Polkadot SDK-based chains, to query a local development node for account information and asset data. Subxt generates type-safe interfaces from chain metadata, so storage queries are checked at compile time. To query a chain without generated code, use Subxt's dynamic API instead; see Static and Dynamic APIs.

The same storage queries work with third-party client libraries, for example Polkadot API (PAPI), Dedot, Polkadot.js API, and Python Substrate Interface.

Prerequisites

  • Rust toolchain (latest stable) and Cargo.
  • A local development node listening on ws://127.0.0.1:9944, for example the parachain template node described in Run the Node Locally.

Set Up the Project

  1. Create a new Rust project:

    cargo new subxt-query-example && cd subxt-query-example
    
  2. Install the Subxt CLI:

    cargo install subxt-cli@0.50.1
    
  3. Download the metadata from your local node:

    subxt metadata --url ws://127.0.0.1:9944 -o metadata.scale
    

    To query a different chain, pass its WebSocket endpoint to --url and update the NODE_URL constant in the examples to match.

  4. Update Cargo.toml with the required dependencies:

    Cargo.toml
    [package]
    name = "subxt-query-example"
    version = "0.1.0"
    edition = "2021"
    
    [[bin]]
    name = "query_balance"
    path = "src/bin/query_balance.rs"
    
    [[bin]]
    name = "query_asset"
    path = "src/bin/query_asset.rs"
    
    [dependencies]
    subxt = "0.50.1"
    tokio = { version = "1", features = ["rt", "macros"] }
    

Query Account Information

The following example queries the System.Account storage item to retrieve an account's nonce, reference counters, and native token balances. By default, it queries Alice's development account.

Create a file at src/bin/query_balance.rs and add the following code to it:

src/bin/query_balance.rs
use std::str::FromStr;
use subxt::utils::AccountId32;
use subxt::{OnlineClient, PolkadotConfig};

// Generate an interface from the node's metadata
#[subxt::subxt(runtime_metadata_path = "metadata.scale")]
pub mod runtime {}

// WebSocket endpoint of your local development node
const NODE_URL: &str = "ws://127.0.0.1:9944";

// Address to query (Alice's development account by default)
const ADDRESS: &str = "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY";

#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Initialize the Subxt client
    let api = OnlineClient::<PolkadotConfig>::from_url(NODE_URL).await?;

    // Anchor to the current block
    let at_block = api.at_current_block().await?;

    println!("Connected to {}", NODE_URL);
    println!("Querying account: {}\n", ADDRESS);

    // Parse the address
    let account = AccountId32::from_str(ADDRESS)?;

    // Build storage entry for System.Account
    let account_storage = at_block
        .storage()
        .entry(runtime::storage().system().account())?;

    // Fetch the account information
    let info = account_storage
        .fetch((account,))
        .await?
        .decode()?;

    println!("Account Information:");
    println!("  Nonce: {}", info.nonce);
    println!("  Consumers: {}", info.consumers);
    println!("  Providers: {}", info.providers);
    println!("  Sufficients: {}", info.sufficients);

    println!("\nBalance Details:");
    println!("  Free: {}", info.data.free);
    println!("  Reserved: {}", info.data.reserved);
    println!("  Frozen: {}", info.data.frozen);
    println!("  Total (free + reserved): {}", info.data.free + info.data.reserved);

    Ok(())
}

Replace the ADDRESS value with any SS58 address you want to query. Then run the script:

cargo run --bin query_balance

The script prints the account information and balance details described in the next section. To read every account instead of a single one, iterate over the storage map as described in Iterate over Storage.

Account Data Fields

When you query System.Account, the result contains the following fields:

  • Nonce: The number of transactions sent from this account, used to prevent replay attacks.
  • Consumers: The number of modules depending on this account's existence.
  • Providers: The number of modules providing for this account's existence.
  • Sufficients: The number of modules that allow this account to exist on its own.
  • Free balance: The transferable balance available for transactions.
  • Reserved balance: Balance that is locked for specific purposes, such as deposits held by pallets.
  • Frozen balance: Balance that cannot be used for transfers but may be used for other operations.

The total balance is the sum of the free and reserved balances. Balances are returned in the chain's smallest unit.

Query Asset Information

The following example queries the Assets pallet to retrieve metadata, details, and an account's balance for a single asset. It requires a runtime that includes the Assets pallet and an asset that already exists on your chain. To add the pallet to your own runtime, see Add Existing Pallets to the Runtime.

Create a file at src/bin/query_asset.rs and add the following code to it:

src/bin/query_asset.rs
use std::str::FromStr;
use subxt::utils::AccountId32;
use subxt::{OnlineClient, PolkadotConfig};

// Generate an interface from the node's metadata
#[subxt::subxt(runtime_metadata_path = "metadata.scale")]
pub mod runtime {}

// WebSocket endpoint of your local development node
const NODE_URL: &str = "ws://127.0.0.1:9944";

// ID of an asset created with the Assets pallet on your chain
const ASSET_ID: u32 = INSERT_ASSET_ID;

// Example address to query asset balance
const ADDRESS: &str = "INSERT_ADDRESS";

#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Initialize the Subxt client
    let api = OnlineClient::<PolkadotConfig>::from_url(NODE_URL).await?;

    // Anchor to the current block
    let at_block = api.at_current_block().await?;

    println!("Connected to {}", NODE_URL);
    println!("Querying asset ID: {}\n", ASSET_ID);

    // Query asset metadata
    let metadata_storage = at_block
        .storage()
        .entry(runtime::storage().assets().metadata())?;
    let meta = metadata_storage
        .fetch((ASSET_ID,))
        .await?
        .decode()?;

    println!("Asset Metadata:");
    println!(
        "  Name: {}",
        String::from_utf8_lossy(&meta.name.0)
    );
    println!(
        "  Symbol: {}",
        String::from_utf8_lossy(&meta.symbol.0)
    );
    println!("  Decimals: {}", meta.decimals);

    // Query asset details
    let asset_storage = at_block
        .storage()
        .entry(runtime::storage().assets().asset())?;
    let details = asset_storage
        .fetch((ASSET_ID,))
        .await?
        .decode()?;

    println!("\nAsset Details:");
    println!("  Owner: {}", details.owner);
    println!("  Supply: {}", details.supply);
    println!("  Accounts: {}", details.accounts);
    println!("  Min Balance: {}", details.min_balance);

    // Query account's asset balance
    let account = AccountId32::from_str(ADDRESS)?;
    println!("\nQuerying asset balance for: {}", ADDRESS);

    let account_storage = at_block
        .storage()
        .entry(runtime::storage().assets().account())?;
    let asset_account = account_storage
        .fetch((ASSET_ID, account))
        .await?
        .decode()?;

    println!("\nAsset Account:");
    println!("  Balance: {}", asset_account.balance);

    Ok(())
}

Replace INSERT_ASSET_ID with the ID of an asset on your chain and INSERT_ADDRESS with the account address you want to query. Then run the script:

cargo run --bin query_asset

The script prints the asset's name, symbol, and decimals, followed by its owner, supply, number of holders, and minimum balance, and the queried account's balance of the asset.

Where to Go Next

  • Guide Runtime API Calls


    Execute runtime APIs for specialized queries.

    Get Started

  • Guide Send Transactions


    Learn how to construct and submit transactions.

    Get Started

Last update: November 17, 2026
| Created: November 17, 2026