subxt/
lib.rs

1// Copyright 2019-2025 Parity Technologies (UK) Ltd.
2// This file is dual-licensed as Apache-2.0 or GPL-3.0.
3// see LICENSE for license details.
4
5//! Subxt is a library for interacting with Substrate based nodes. Using it looks something like this:
6//!
7//! ```rust,ignore
8#![doc = include_str!("../examples/tx_basic.rs")]
9//! ```
10//!
11//! Take a look at [the Subxt guide](book) to learn more about how to use Subxt.
12
13#![cfg_attr(docsrs, feature(doc_cfg))]
14
15#[cfg(any(
16    all(feature = "web", feature = "native"),
17    not(any(feature = "web", feature = "native"))
18))]
19compile_error!("subxt: exactly one of the 'web' and 'native' features should be used.");
20
21// Internal helper macros
22#[macro_use]
23mod macros;
24
25// The guide is here.
26pub mod book;
27
28// Suppress an unused dependency warning because tokio is
29// only used in example code snippets at the time of writing.
30#[cfg(test)]
31mod only_used_in_docs_or_tests {
32    use subxt_signer as _;
33    use tokio as _;
34}
35
36// Suppress an unused dependency warning because tracing_subscriber is
37// only used in example code snippets at the time of writing.
38#[cfg(test)]
39use tracing_subscriber as _;
40
41pub mod backend;
42pub mod blocks;
43pub mod client;
44pub mod constants;
45pub mod custom_values;
46pub mod error;
47pub mod events;
48pub mod runtime_api;
49pub mod storage;
50pub mod tx;
51pub mod utils;
52pub mod view_functions;
53
54/// This module provides a [`Config`] type, which is used to define various
55/// types that are important in order to speak to a particular chain.
56/// [`SubstrateConfig`] provides a default set of these types suitable for the
57/// default Substrate node implementation, and [`PolkadotConfig`] for a
58/// Polkadot node.
59pub mod config {
60    pub use subxt_core::config::{
61        Config, DefaultExtrinsicParams, DefaultExtrinsicParamsBuilder, ExtrinsicParams,
62        ExtrinsicParamsEncoder, Hash, HashFor, Hasher, Header, PolkadotConfig,
63        PolkadotExtrinsicParams, SubstrateConfig, SubstrateExtrinsicParams, TransactionExtension,
64        polkadot, substrate, transaction_extensions,
65    };
66    pub use subxt_core::error::ExtrinsicParamsError;
67}
68
69/// Types representing the metadata obtained from a node.
70pub mod metadata {
71    pub use subxt_core::metadata::{DecodeWithMetadata, EncodeWithMetadata, Metadata};
72    // Expose metadata types under a sub module in case somebody needs to reference them:
73    pub use subxt_metadata as types;
74}
75
76/// Submit dynamic transactions.
77pub mod dynamic {
78    pub use subxt_core::dynamic::{
79        At, DecodedValue, DecodedValueThunk, Value, constant, runtime_api_call, storage, tx,
80        view_function_call,
81    };
82}
83
84// Expose light client bits
85cfg_unstable_light_client! {
86    pub use subxt_lightclient as lightclient;
87}
88
89// Expose a few of the most common types at root,
90// but leave most types behind their respective modules.
91pub use crate::{
92    client::{OfflineClient, OnlineClient},
93    config::{Config, PolkadotConfig, SubstrateConfig},
94    error::Error,
95    metadata::Metadata,
96};
97
98/// Re-export external crates that are made use of in the subxt API.
99pub mod ext {
100    pub use codec;
101    pub use frame_metadata;
102    pub use futures;
103    pub use scale_bits;
104    pub use scale_decode;
105    pub use scale_encode;
106    pub use scale_value;
107    pub use subxt_core;
108    pub use subxt_rpcs;
109
110    cfg_jsonrpsee! {
111        pub use jsonrpsee;
112    }
113}
114
115/// Generate a strongly typed API for interacting with a Substrate runtime from its metadata of WASM.
116///
117/// # Metadata
118///
119/// First, you'll need to get hold of some metadata for the node you'd like to interact with. One
120/// way to do this is by using the `subxt` CLI tool:
121///
122/// ```bash
123/// # Install the CLI tool:
124/// cargo install subxt-cli
125/// # Use it to download metadata (in this case, from a node running locally)
126/// subxt metadata > polkadot_metadata.scale
127/// ```
128///
129/// Run `subxt metadata --help` for more options.
130///
131/// # Basic usage
132///
133/// We can generate an interface to a chain given either:
134/// - A locally saved SCALE encoded metadata file (see above) for that chain,
135/// - The Runtime WASM for that chain, or
136/// - A URL pointing at the JSON-RPC interface for a node on that chain.
137///
138/// In each case, the `subxt` macro will use this data to populate the annotated module with all of the methods
139/// and types required for interacting with the chain that the Runtime/metadata was loaded from.
140///
141/// Let's look at each of these:
142///
143/// ## Using a locally saved metadata file
144///
145/// Annotate a Rust module with the `subxt` attribute referencing a metadata file like so:
146///
147/// ```rust,no_run,standalone_crate
148/// #[subxt::subxt(
149///     runtime_metadata_path = "../artifacts/polkadot_metadata_full.scale",
150/// )]
151/// mod polkadot {}
152/// ```
153///
154/// ## Using a WASM runtime via `runtime_path = "..."`
155///
156/// This requires the `runtime-wasm-path` feature flag.
157///
158/// Annotate a Rust module with the `subxt` attribute referencing some runtime WASM like so:
159///
160/// ```rust,ignore
161/// #[subxt::subxt(
162///     runtime_path = "../artifacts/westend_runtime.wasm",
163/// )]
164/// mod polkadot {}
165/// ```
166///
167/// ## Connecting to a node to download metadata via `runtime_metadata_insecure_url = "..."`
168///
169/// This will, at compile time, connect to the JSON-RPC interface for some node at the URL given,
170/// download the metadata from it, and use that. This can be useful in CI, but is **not recommended**
171/// in production code, because:
172///
173/// - The compilation time is increased since we have to download metadata from a URL each time. If
174///   the node we connect to is unresponsive, this will be slow or could fail.
175/// - The metadata may change from what is expected without notice, causing compilation to fail if
176///   it leads to changes in the generated interfaces that are being used.
177/// - The node that you connect to could be malicious and provide incorrect metadata for the chain.
178///
179/// ```rust,ignore
180/// #[subxt::subxt(
181///     runtime_metadata_insecure_url = "wss://rpc.polkadot.io:443"
182/// )]
183/// mod polkadot {}
184/// ```
185///
186/// # Configuration
187///
188/// This macro supports a number of attributes to configure what is generated:
189///
190/// ## `crate = "..."`
191///
192/// Use this attribute to specify a custom path to the `subxt_core` crate:
193///
194/// ```rust,standalone_crate
195/// # pub extern crate subxt_core;
196/// # pub mod path { pub mod to { pub use subxt_core; } }
197/// # fn main() {}
198/// #[subxt::subxt(
199///     runtime_metadata_path = "../artifacts/polkadot_metadata_full.scale",
200///     crate = "crate::path::to::subxt_core"
201/// )]
202/// mod polkadot {}
203/// ```
204///
205/// This is useful if you write a library which uses this macro, but don't want to force users to depend on `subxt`
206/// at the top level too. By default the path `::subxt` is used.
207///
208/// ## `substitute_type(path = "...", with = "...")`
209///
210/// This attribute replaces any reference to the generated type at the path given by `path` with a
211/// reference to the path given by `with`.
212///
213/// ```rust,standalone_crate
214/// #[subxt::subxt(
215///     runtime_metadata_path = "../artifacts/polkadot_metadata_full.scale",
216///     substitute_type(path = "sp_arithmetic::per_things::Perbill", with = "crate::Foo")
217/// )]
218/// mod polkadot {}
219///
220/// # #[derive(
221/// #     scale_encode::EncodeAsType,
222/// #     scale_decode::DecodeAsType,
223/// #     codec::Encode,
224/// #     codec::Decode,
225/// #     Clone,
226/// #     Debug,
227/// # )]
228/// // In reality this needs some traits implementing on
229/// // it to allow it to be used in place of Perbill:
230/// pub struct Foo(u32);
231/// # impl codec::CompactAs for Foo {
232/// #     type As = u32;
233/// #     fn encode_as(&self) -> &Self::As {
234/// #         &self.0
235/// #     }
236/// #     fn decode_from(x: Self::As) -> Result<Self, codec::Error> {
237/// #         Ok(Foo(x))
238/// #     }
239/// # }
240/// # impl From<codec::Compact<Foo>> for Foo {
241/// #     fn from(v: codec::Compact<Foo>) -> Foo {
242/// #         v.0
243/// #     }
244/// # }
245/// # fn main() {}
246/// ```
247///
248/// If the type you're substituting contains generic parameters, you can "pattern match" on those, and
249/// make use of them in the substituted type, like so:
250///
251/// ```rust,no_run,standalone_crate
252/// #[subxt::subxt(
253///     runtime_metadata_path = "../artifacts/polkadot_metadata_full.scale",
254///     substitute_type(
255///         path = "sp_runtime::multiaddress::MultiAddress<A, B>",
256///         with = "::subxt::utils::Static<sp_runtime::MultiAddress<A, B>>"
257///     )
258/// )]
259/// mod polkadot {}
260/// ```
261///
262/// The above is also an example of using the [`crate::utils::Static`] type to wrap some type which doesn't
263/// on it's own implement [`scale_encode::EncodeAsType`] or [`scale_decode::DecodeAsType`], which are required traits
264/// for any substitute type to implement by default.
265///
266/// ## `derive_for_all_types = "..."`
267///
268/// By default, all generated types derive a small set of traits. This attribute allows you to derive additional
269/// traits on all generated types:
270///
271/// ```rust,no_run,standalone_crate
272/// #[subxt::subxt(
273///     runtime_metadata_path = "../artifacts/polkadot_metadata_full.scale",
274///     derive_for_all_types = "Eq, PartialEq"
275/// )]
276/// mod polkadot {}
277/// ```
278///
279/// Any substituted types (including the default substitutes) must also implement these traits in order to avoid errors
280/// here.
281///
282/// ## `derive_for_type(path = "...", derive = "...")`
283///
284/// Unlike the above, which derives some trait on every generated type, this attribute allows you to derive traits only
285/// for specific types. Note that any types which are used inside the specified type may also need to derive the same traits.
286///
287/// ```rust,no_run,standalone_crate
288/// #[subxt::subxt(
289///     runtime_metadata_path = "../artifacts/polkadot_metadata_full.scale",
290///     derive_for_all_types = "Eq, PartialEq",
291///     derive_for_type(path = "frame_support::PalletId", derive = "Ord, PartialOrd"),
292///     derive_for_type(path = "sp_runtime::ModuleError", derive = "Hash"),
293/// )]
294/// mod polkadot {}
295/// ```
296///
297/// ## `generate_docs`
298///
299/// By default, documentation is not generated via the macro, since IDEs do not typically make use of it. This attribute
300/// forces documentation to be generated, too.
301///
302/// ```rust,no_run,standalone_crate
303/// #[subxt::subxt(
304///     runtime_metadata_path = "../artifacts/polkadot_metadata_full.scale",
305///     generate_docs
306/// )]
307/// mod polkadot {}
308/// ```
309///
310/// ## `runtime_types_only`
311///
312/// By default, the macro will generate various interfaces to make using Subxt simpler in addition with any types that need
313/// generating to make this possible. This attribute makes the codegen only generate the types and not the Subxt interface.
314///
315/// ```rust,no_run,standalone_crate
316/// #[subxt::subxt(
317///     runtime_metadata_path = "../artifacts/polkadot_metadata_full.scale",
318///     runtime_types_only
319/// )]
320/// mod polkadot {}
321/// ```
322///
323/// ## `no_default_derives`
324///
325/// By default, the macro will add all derives necessary for the generated code to play nicely with Subxt. Adding this attribute
326/// removes all default derives.
327///
328/// ```rust,no_run,standalone_crate
329/// #[subxt::subxt(
330///     runtime_metadata_path = "../artifacts/polkadot_metadata_full.scale",
331///     runtime_types_only,
332///     no_default_derives,
333///     derive_for_all_types="codec::Encode, codec::Decode"
334/// )]
335/// mod polkadot {}
336/// ```
337///
338/// **Note**: At the moment, you must derive at least one of `codec::Encode` or `codec::Decode` or `scale_encode::EncodeAsType` or
339/// `scale_decode::DecodeAsType` (because we add `#[codec(..)]` attributes on some fields/types during codegen), and you must use this
340/// feature in conjunction with `runtime_types_only` (or manually specify a bunch of defaults to make codegen work properly when
341/// generating the subxt interfaces).
342///
343/// ## `unstable_metadata`
344///
345/// This attribute works only in combination with `runtime_metadata_insecure_url`. By default, the macro will fetch the latest stable
346/// version of the metadata from the target node. This attribute makes the codegen attempt to fetch the unstable version of
347/// the metadata first. This is **not recommended** in production code, since the unstable metadata a node is providing is likely
348/// to be incompatible with Subxt.
349///
350/// ```rust,ignore
351/// #[subxt::subxt(
352///     runtime_metadata_insecure_url = "wss://rpc.polkadot.io:443",
353///     unstable_metadata
354/// )]
355/// mod polkadot {}
356/// ```
357pub use subxt_macro::subxt;