subxt

repository·master·Indexed 19 days ago

https://github.com/paritytech/subxt

A high-performance Rust library for interacting with Polkadot-based chains. It supports statically typed and dynamic interfaces for submitting extrinsics, querying storage, and subscribing to block updates. The ecosystem includes subxt-cli for metadata downloading and code generation, subxt-rpcs for structured RPC interaction, and support for WASM and C-ABI facades for non-Rust clients.

Tokens
55.3K
Snippets
190
Records
251
Agent score
67%

What's inside subxt

  1. Overview of Subxt capabilities

    master

    Subxt is a Rust library designed for interacting with chains in the Polkadot network. It provides several core capabilities for blockchain interaction:

    • Submit Extrinsics: Send transactions to the network.
    • Access Chain Information: Retrieve storage values, constants, Runtime APIs, and View Functions at any specific block.
    • Subscribe to Blocks: Listen for new blocks to trigger automated logic.
    • Flexible Interfaces: Use a safe, statically typed interface (via code generation) or a flexible dynamic interface.
    • Trustless Interaction: Use a built-in light client to interact with chains without relying on a full node.
    • Multi-runtime Support: Compiles to WASM for browser execution or can be called via FFI in other languages.
    • Offline Support: Provides a subset of functionality that can be used entirely offline.
  2. Use Subxt-signer for WASM-compatible transaction signing

    master

    Subxt-signer provides a lightweight, WASM-compatible signer implementation designed to work with subxt. It allows you to sign transactions in environments where standard cryptographic libraries might not be available or where WASM compatibility is required.

    By default, the library is integrated with subxt via the subxt feature flag. If you need to use the signer as a standalone library without the subxt dependency, you must disable the subxt feature flag during installation.

  3. Expose Subxt functionality via a C-ABI facade library

    master

    To allow non-Rust clients (Python, Node.js, Swift, Kotlin, etc.) to interact with Substrate-based nodes, you can build a thin facade crate. This crate wraps subxt calls and exposes them via pub extern "C" fn functions, creating a C-ABI compatible dynamic library (.so, .dylib, or .dll).

    Pattern for FFI functions

    When defining functions in your facade, only pass pointers and primitive types (e.g., u64, i32, *const c_char) across the boundary to ensure FFI safety.

    Example function signature:

    pub extern "C" fn do_transfer(dest_hex: *const c_char, amount: u64) -> i32
    • Returns: 0 on success, -1 on error (e.g., decode error, RPC error).
    • Input: A pointer to a C-style string for the destination hex and a u64 for the amount.
    pub extern "C" fn do_transfer(dest_hex: *const c_char, amount: u64) -> i32
  4. Setup the parachain-example environment

    master

    To run the parachain-example, you must set up a local blockchain network using zombienet, a Polkadot relay chain, and a parachain binary (Asset Hub). This environment allows you to test subxt interactions with a locally deployed parachain.

    Prerequisites

    1. Install zombienet: Follow the installation guide in the zombienet GitHub repository.
    2. Build polkadot: Clone and install the Polkadot binary to your path:
      git clone https://github.com/paritytech/polkadot.git
      cd polkadot
      cargo install --path .
    3. Build polkadot-parachain: Clone the Cumulus repository and install the polkadot-parachain binary:
      git clone https://github.com/paritytech/cumulus.git
      cd cumulus
      cargo install --path polkadot-parachain
    # See prerequisites in content
  5. Build the Rust facade library

    master

    Compile the facade crate to produce a dynamic library that can be loaded by foreign language runtimes.

    cargo build

    Output locations:

    • macOS: target/debug/libsubxt_ffi.dylib
    • Linux: target/debug/libsubxt_ffi.so
    • Windows: target/debug/subxt_ffi.dll

    (Note: Use --release flag to output to target/release/ instead.)

    cargo build
  6. Configure a dev account for the signing example

    master

    The signing example uses the @polkadot/extension-dapp NPM package to interact with browser wallet extensions. To sign and submit transactions to a local polkadot --dev node, you must create a development account in your browser wallet using the following credentials:

    • Recovery Phrase: bottom drive obey lake curtain smoke basket hold race lonely fit walk
    • Derivation Path: //Alice
  7. Use subxt-cli to download substrate metadata

    master

    The metadata subcommand allows you to download metadata from a running substrate node. This metadata can be used for inspection or as an input for subxt codegen and macros. You can specify the output format using the -f or --format flag, with options being json (default), hex, or bytes.

    subxt metadata -f bytes > metadata.scale
  8. Run the local parachain with Zombienet

    master

    Use zombienet to spin up a local Asset Hub. This command starts at least 2 validator nodes (via the polkadot binary) and an Asset Hub node (via the polkadot-parachain binary), and handles parachain registration.

    Run the following command using the asset-hub-zombienet.toml configuration file. The -p native flag is used to run without Kubernetes:

    zombienet -p native spawn asset-hub-zombienet.toml

    Note: The parachain is only registered after the first epoch. For the rococo-local configuration used in this example, you must wait approximately 2 minutes before the parachain becomes interactive and starts producing blocks.

    zombienet -p native spawn asset-hub-zombienet.toml
  9. Interact with Substrate nodes via subxt-rpcs

    master

    The subxt-rpcs crate provides a structured interface for interacting with Substrate nodes using their available RPC methods. You can use RpcClient to establish a connection to a node via a WebSocket URL and then wrap that client in a specific RPC methods struct (such as ChainHeadRpcMethods) to access categorized RPC calls, including subscriptions.

    use subxt_rpcs::{RpcClient, ChainHeadRpcMethods};
    
    // Connect to a local node:
    let client = RpcClient::from_url("ws://127.0.0.1:9944").await?;
    
    // Use a set of methods, here the V2 "chainHead" ones:
    let methods = ChainHeadRpcMethods::new(client);
    
    // Call some RPC methods (in this case a subscription):
    let mut follow_subscription = methods.chainhead_v1_follow(false).await.unwrap();
    while let Some(follow_event) = follow_subscription.next().await {
        // do something with events..
    }
  10. Explore Subxt examples

    master

    The examples/ directory contains complete, multi-file projects demonstrating various ways to use subxt.

    • For comprehensive, multi-file project examples, look in the root of the examples/ folder.
    • For smaller, single-file code snippets and simpler demonstrations, refer to the ./subxt/examples directory.
  11. Run the WASM UI example with Trunk

    master

    The wasm-example is a small application built with the Yew UI framework that demonstrates how to use subxt features within a WebAssembly (WASM) environment.

    To run this example locally, you must install trunk, a WASM bundler, and have a local Substrate node running with the JSON-RPC HTTP server enabled at 127.0.0.1:9933.

    # Install the WASM bundler
    cargo install --locked trunk
    
    # Run the app locally
    trunk serve --open