subxt 0.50.0

Interact with Substrate based chains on the Polkadot Network
Documentation
// Copyright 2019-2026 Parity Technologies (UK) Ltd.
// This file is dual-licensed as Apache-2.0 or GPL-3.0.
// see LICENSE for license details.

//! Subxt is a library for interacting with Substrate based nodes. Here's what it looks like:
//!
//! ```rust,ignore
#![doc = include_str!("../examples/submit_transaction.rs")]
//! ```
//!
//! Take a look at
#![doc = concat!("[the examples](https://github.com/paritytech/subxt/tree/", env!("SUBXT_REF"), "/subxt/examples)")]
//! to get off to a quick start, or check out [the introduction](introduction) for a more in depth introduction to Subxt.
//!
//! In addition to the single-file examples above, we have a few self contained project examples to show off specific
//! use cases:
#![doc = concat!("- [The parachain example](https://github.com/paritytech/subxt/tree/", env!("SUBXT_REF"), "/examples/parachain-example)")]
//!   is an example which uses Zombienet to spawn a parachain locally, and then connects to it using Subxt.
#![doc = concat!("- [The WASM example](https://github.com/paritytech/subxt/tree/", env!("SUBXT_REF"), "/examples/wasm-example)")]
//!   is an example of writing a Rust web application which uses Subxt to interact with a chain entirely in the browser.
#![doc = concat!("- [The FFI example](https://github.com/paritytech/subxt/tree/", env!("SUBXT_REF"), "/examples/ffi-example)")]
//!   shows off how Subxt can be called via FFI from Node.JS and Python.

#[cfg(all(feature = "web", feature = "native"))]
compile_error!(
    "subxt: exactly one of the 'web' and 'native' features should be used, but both have been enabled."
);
#[cfg(not(any(feature = "web", feature = "native")))]
compile_error!(
    "subxt: exactly one of the 'web' and 'native' features should be used, but none have been enabled."
);

// This is exposed so that the code generated by subxt-codegen can avoid
// relying on std things. Given that it relies on subxt, it _must_ use std,
// but this may change if we move things back to a no-std core/common crate.
// that it can point at.
//
// Undocumented and **should not be depended on by anybody else**.
#[doc(hidden)]
pub extern crate alloc;

pub mod backend;
pub mod client;
pub mod config;
pub mod constants;
pub mod custom_values;
pub mod dynamic;
pub mod error;
pub mod events;
pub mod extrinsics;
pub mod introduction;
pub mod runtime_apis;
pub mod storage;
pub mod transactions;
pub mod utils;
pub mod view_functions;

// Re-export the [`subxt_metadata`] crate.
pub use subxt_metadata as metadata;

// Re-export the [`subxt_rpcs`] crate.
pub use subxt_rpcs as rpcs;

// A shorthand to match previous versions and the
// tx shorthand in other places.
pub use transactions as tx;

// Expose a few of the most common types at root,
// but leave most types behind their respective modules.
pub use crate::{
    client::{OfflineClient, OfflineClientAtBlock, OnlineClient, OnlineClientAtBlock},
    config::{Config, PolkadotConfig, SubstrateConfig},
    error::Error,
    metadata::{ArcMetadata, Metadata},
};

// Expose light client bits
#[cfg(feature = "light-client")]
pub use subxt_lightclient as lightclient;

/// Re-export external crates that are made use of in the subxt API.
pub mod ext {
    pub use codec;
    pub use frame_decode;
    pub use frame_metadata;
    pub use futures;
    pub use scale_bits;
    pub use scale_decode;
    pub use scale_encode;
    pub use scale_type_resolver;
    pub use scale_value;

    #[cfg(feature = "jsonrpsee")]
    pub use jsonrpsee;
}

/// Generate a strongly typed API for interacting with a Substrate runtime from its metadata of WASM.
///
/// # Metadata
///
/// First, you'll need to get hold of some metadata for the node you'd like to interact with. One
/// way to do this is by using the `subxt` CLI tool:
///
/// ```bash
/// # Install the CLI tool:
/// cargo install subxt-cli
/// # Use it to download metadata (in this case, from a node running locally)
/// subxt metadata > polkadot_metadata.scale
/// ```
///
/// Run `subxt metadata --help` for more options.
///
/// # Basic usage
///
/// We can generate an interface to a chain given either:
/// - A locally saved SCALE encoded metadata file (see above) for that chain,
/// - The Runtime WASM for that chain, or
/// - A URL pointing at the JSON-RPC interface for a node on that chain.
///
/// In each case, the `subxt` macro will use this data to populate the annotated module with all of the methods
/// and types required for interacting with the chain that the Runtime/metadata was loaded from.
///
/// Let's look at each of these:
///
/// ## Using a locally saved metadata file
///
/// Annotate a Rust module with the `subxt` attribute referencing a metadata file like so:
///
/// ```rust,no_run,standalone_crate
/// #[subxt::subxt(
///     runtime_metadata_path = "../artifacts/polkadot_metadata_full.scale",
/// )]
/// mod polkadot {}
/// ```
///
/// ## Using a WASM runtime via `runtime_path = "..."`
///
/// This requires the `runtime-wasm-path` feature flag.
///
/// Annotate a Rust module with the `subxt` attribute referencing some runtime WASM like so:
///
/// ```rust,no_run
/// #[subxt::subxt(
///     runtime_path = "../artifacts/westend_runtime.wasm",
/// )]
/// mod polkadot {}
/// ```
///
/// ## Connecting to a node to download metadata via `runtime_metadata_insecure_url = "..."`
///
/// This will, at compile time, connect to the JSON-RPC interface for some node at the URL given,
/// download the metadata from it, and use that. This can be useful in CI, but is **not recommended**
/// in production code, because:
///
/// - The compilation time is increased since we have to download metadata from a URL each time. If
///   the node we connect to is unresponsive, this will be slow or could fail.
/// - The metadata may change from what is expected without notice, causing compilation to fail if
///   it leads to changes in the generated interfaces that are being used.
/// - The node that you connect to could be malicious and provide incorrect metadata for the chain.
///
/// ```rust,ignore
/// #[subxt::subxt(
///     runtime_metadata_insecure_url = "wss://rpc.polkadot.io:443"
/// )]
/// mod polkadot {}
/// ```
///
/// # Configuration
///
/// This macro supports a number of attributes to configure what is generated:
///
/// ## `crate = "..."`
///
/// Use this attribute to specify a custom path to the `subxt` crate:
///
/// ```rust,standalone_crate
/// # pub extern crate subxt;
/// # pub mod path { pub mod to { pub use subxt; } }
/// # fn main() {}
/// #[subxt::subxt(
///     runtime_metadata_path = "../artifacts/polkadot_metadata_full.scale",
///     crate = "crate::path::to::subxt"
/// )]
/// mod polkadot {}
/// ```
///
/// This is useful if you write a library which uses this macro, but don't want to force users to depend on `subxt`
/// at the top level too. By default the path `::subxt` is used.
///
/// ## `substitute_type(path = "...", with = "...")`
///
/// This attribute replaces any reference to the generated type at the path given by `path` with a
/// reference to the path given by `with`.
///
/// ```rust,standalone_crate
/// #[subxt::subxt(
///     runtime_metadata_path = "../artifacts/polkadot_metadata_full.scale",
///     substitute_type(path = "sp_arithmetic::per_things::Perbill", with = "crate::Foo")
/// )]
/// mod polkadot {}
///
/// # #[derive(
/// #     scale_encode::EncodeAsType,
/// #     scale_decode::DecodeAsType,
/// #     codec::Encode,
/// #     codec::Decode,
/// #     Clone,
/// #     Debug,
/// # )]
/// // In reality this needs some traits implementing on
/// // it to allow it to be used in place of Perbill:
/// pub struct Foo(u32);
/// # impl codec::CompactAs for Foo {
/// #     type As = u32;
/// #     fn encode_as(&self) -> &Self::As {
/// #         &self.0
/// #     }
/// #     fn decode_from(x: Self::As) -> Result<Self, codec::Error> {
/// #         Ok(Foo(x))
/// #     }
/// # }
/// # impl From<codec::Compact<Foo>> for Foo {
/// #     fn from(v: codec::Compact<Foo>) -> Foo {
/// #         v.0
/// #     }
/// # }
/// # fn main() {}
/// ```
///
/// If the type you're substituting contains generic parameters, you can "pattern match" on those, and
/// make use of them in the substituted type, like so:
///
/// ```rust,no_run,standalone_crate
/// #[subxt::subxt(
///     runtime_metadata_path = "../artifacts/polkadot_metadata_full.scale",
///     substitute_type(
///         path = "sp_runtime::multiaddress::MultiAddress<A, B>",
///         with = "::subxt::utils::Static<sp_runtime::MultiAddress<A, B>>"
///     )
/// )]
/// mod polkadot {}
/// ```
///
/// The above is also an example of using the [`crate::utils::Static`] type to wrap some type which doesn't
/// on it's own implement [`scale_encode::EncodeAsType`] or [`scale_decode::DecodeAsType`], which are required traits
/// for any substitute type to implement by default.
///
/// ## `derive_for_all_types = "..."`
///
/// By default, all generated types derive a small set of traits. This attribute allows you to derive additional
/// traits on all generated types:
///
/// ```rust,no_run,standalone_crate
/// #[subxt::subxt(
///     runtime_metadata_path = "../artifacts/polkadot_metadata_full.scale",
///     derive_for_all_types = "Eq, PartialEq"
/// )]
/// mod polkadot {}
/// ```
///
/// Any substituted types (including the default substitutes) must also implement these traits in order to avoid errors
/// here.
///
/// ## `derive_for_type(path = "...", derive = "...")`
///
/// Unlike the above, which derives some trait on every generated type, this attribute allows you to derive traits only
/// for specific types. Note that any types which are used inside the specified type may also need to derive the same traits.
///
/// ```rust,no_run,standalone_crate
/// #[subxt::subxt(
///     runtime_metadata_path = "../artifacts/polkadot_metadata_full.scale",
///     derive_for_all_types = "Eq, PartialEq",
///     derive_for_type(path = "frame_support::PalletId", derive = "Ord, PartialOrd"),
///     derive_for_type(path = "sp_runtime::ModuleError", derive = "Hash"),
/// )]
/// mod polkadot {}
/// ```
///
/// ## `generate_docs`
///
/// By default, documentation is not generated via the macro, since IDEs do not typically make use of it. This attribute
/// forces documentation to be generated, too.
///
/// ```rust,no_run,standalone_crate
/// #[subxt::subxt(
///     runtime_metadata_path = "../artifacts/polkadot_metadata_full.scale",
///     generate_docs
/// )]
/// mod polkadot {}
/// ```
///
/// ## `runtime_types_only`
///
/// By default, the macro will generate various interfaces to make using Subxt simpler in addition with any types that need
/// generating to make this possible. This attribute makes the codegen only generate the types and not the Subxt interface.
///
/// ```rust,no_run,standalone_crate
/// #[subxt::subxt(
///     runtime_metadata_path = "../artifacts/polkadot_metadata_full.scale",
///     runtime_types_only
/// )]
/// mod polkadot {}
/// ```
///
/// ## `no_default_derives`
///
/// By default, the macro will add all derives necessary for the generated code to play nicely with Subxt. Adding this attribute
/// removes all default derives.
///
/// ```rust,no_run,standalone_crate
/// #[subxt::subxt(
///     runtime_metadata_path = "../artifacts/polkadot_metadata_full.scale",
///     runtime_types_only,
///     no_default_derives,
///     derive_for_all_types="codec::Encode, codec::Decode"
/// )]
/// mod polkadot {}
/// ```
///
/// **Note**: At the moment, you must derive at least one of `codec::Encode` or `codec::Decode` or `scale_encode::EncodeAsType` or
/// `scale_decode::DecodeAsType` (because we add `#[codec(..)]` attributes on some fields/types during codegen), and you must use this
/// feature in conjunction with `runtime_types_only` (or manually specify a bunch of defaults to make codegen work properly when
/// generating the subxt interfaces).
///
/// ## `unstable_metadata`
///
/// This attribute works only in combination with `runtime_metadata_insecure_url`. By default, the macro will fetch the latest stable
/// version of the metadata from the target node. This attribute makes the codegen attempt to fetch the unstable version of
/// the metadata first. This is **not recommended** in production code, since the unstable metadata a node is providing is likely
/// to be incompatible with Subxt.
///
/// ```rust,ignore
/// #[subxt::subxt(
///     runtime_metadata_insecure_url = "wss://rpc.polkadot.io:443",
///     unstable_metadata
/// )]
/// mod polkadot {}
/// ```
pub use subxt_macro::subxt;