This document explains how to generate and use typed metadata for type-safe Substrate transactions.
cargo install subxt-cli
subxt metadata --url wss://rpc.polkadot.io > polkadot-metadata.scale
subxt metadata --url wss://kusama-rpc.polkadot.io > kusama-metadata.scale
subxt metadata --url ws://localhost:9944 > local-metadata.scale
subxt codegen --file polkadot-metadata.scale | rustfmt --edition 2021 > src/generated/polkadot.rs
Or for multiple chains:
mkdir -p src/generated
subxt codegen --file polkadot-metadata.scale | rustfmt --edition 2021 > src/generated/polkadot.rs
subxt codegen --file kusama-metadata.scale | rustfmt --edition 2021 > src/generated/kusama.rs
Add to src/lib.rs or create a new module:
#[cfg(feature = "polkadot-metadata")]
pub mod polkadot {
include!("generated/polkadot.rs");
}
#[cfg(feature = "kusama-metadata")]
pub mod kusama {
include!("generated/kusama.rs");
}
Dynamic API (current):
use subxt::dynamic;
let tx = dynamic::tx(
"Balances",
"transfer_keep_alive",
vec![
dynamic::Value::from_bytes(&recipient_bytes),
dynamic::Value::u128(amount),
],
);
Typed API (with generated metadata):
use crate::polkadot;
let tx = polkadot::tx().balances().transfer_keep_alive(
recipient_account,
amount,
);
Dynamic API:
let tx = dynamic::tx(
"Staking",
"bond",
vec![
dynamic::Value::from_bytes(&controller),
dynamic::Value::u128(value),
dynamic::Value::variant("Staked"),
],
);
Typed API:
let tx = polkadot::tx().staking().bond(
controller,
value,
RewardDestination::Staked,
);
Substrate chains upgrade their runtime periodically. After a runtime upgrade:
Add feature flags to your Cargo.toml to enable specific chain support:
[features]
default = []
polkadot-metadata = []
kusama-metadata = []
westend-metadata = []
Build with specific features:
cargo build --features polkadot-metadata
Problem: Unable to connect to RPC endpoint
Solutions:
Problem: subxt codegen produces errors
Solutions:
subxt-cli to latest versionProblem: Type errors in generated code
Solutions:
subxt version matches the version used by subxt-cli| Metric | Dynamic API | Typed API |
|---|---|---|
| Compilation Time | Faster | Slower (more code to compile) |
| Runtime Performance | ~same | ~same (minor improvements) |
| Type Safety | Runtime only | Compile-time |
| Code Maintainability | Lower | Higher |
| Binary Size | Smaller | Larger |