Runtime API Calls
Introduction
Section titled “Introduction”Polkadot SDK runtime APIs provide direct access to the blockchain's WebAssembly (Wasm) runtime, enabling specialized queries and computations that go beyond simple storage reads. Unlike storage queries that fetch static data, runtime APIs execute logic within the runtime to compute results dynamically.
Common runtime APIs include:
- AccountNonceApi: Retrieves the current transaction nonce for an account.
- Metadata: Queries available metadata versions and runtime information.
- TransactionPaymentApi: Estimates transaction fees before submission.
- NominationPoolsApi: Retrieves staking pool information and pending rewards.
- StakingApi: Accesses staking-related computations.
Call Runtime APIs
Section titled “Call Runtime APIs”This section demonstrates how to call runtime APIs using the following SDKs:
- Polkadot API (PAPI): Modern TypeScript library with type-safe APIs.
- Polkadot.js API: Comprehensive JavaScript library (maintenance mode).
- Dedot: Lightweight TypeScript library optimized for performance.
- Python Substrate Interface: Python library for Substrate chains.
- Subxt: Rust library with compile-time type safety.
Select your preferred SDK below to see complete, runnable examples that query Polkadot Hub TestNet for account nonces and metadata information.
Prerequisites
- Node.js v18 or higher
- npm, pnpm, or yarn package manager
Environment Setup
-
Create and initialize a new project:
Terminal window mkdir papi-runtime-api-example && cd papi-runtime-api-example && \npm init -y && npm pkg set type=module -
Install dependencies:
Terminal window npm install polkadot-api@3.3.0 && \npm install --save-dev @types/node tsx typescript -
Generate types for Polkadot Hub TestNet:
Terminal window npx papi add polkadotTestNet -w wss://asset-hub-paseo.dotters.network
Call Runtime APIs
The following example demonstrates calling several runtime APIs:
AccountNonceApi.account_nonce: Gets the current nonce for an account.Metadata.metadata_versions: Retrieves supported metadata versions.
Create a file named runtime-apis.ts and add the following code:
import { createClient } from 'polkadot-api';import { getWsProvider } from 'polkadot-api/ws';import { polkadotTestNet } from '@polkadot-api/descriptors';
const POLKADOT_TESTNET_RPC = 'INSERT_WS_ENDPOINT';
// Example address to queryconst ADDRESS = 'INSERT_ADDRESS';
async function main() { // Create the client connection const client = createClient(getWsProvider(POLKADOT_TESTNET_RPC));
// Get the typed API for Polkadot Hub TestNet const api = client.getTypedApi(polkadotTestNet);
console.log('Connected to Polkadot Hub TestNet'); console.log(`Querying runtime APIs for: ${ADDRESS}\n`);
// Call AccountNonceApi to get the account nonce const nonce = await api.apis.AccountNonceApi.account_nonce(ADDRESS); console.log('AccountNonceApi Results:'); console.log(` Account Nonce: ${nonce}`);
// Query metadata versions using Metadata runtime API const metadataVersions = await api.apis.Metadata.metadata_versions(); console.log('\nMetadata API Results:'); console.log(` Supported Metadata Versions: [${metadataVersions.join(', ')}]`);
// Disconnect the client client.destroy();}
main().catch(console.error);Ensure to replace INSERT_WS_ENDPOINT with a valid WebSocket endpoint (e.g., wss://asset-hub-paseo.dotters.network) and INSERT_ADDRESS with the account address you want to query.
Run the script:
npx tsx runtime-apis.tsYou should see output similar to:
Prerequisites
- Node.js v18 or higher
- npm, pnpm, or yarn package manager
Environment Setup
-
Create and initialize a new project:
Terminal window mkdir pjs-runtime-api-example && cd pjs-runtime-api-example && \npm init -y && npm pkg set type=module -
Install dependencies:
Terminal window npm install @polkadot/api
Call Runtime APIs
The following example demonstrates calling several runtime APIs:
accountNonceApi.accountNonce: Gets the current nonce for an account.metadata.metadataVersions: Retrieves supported metadata versions.
Create a file named runtime-apis.js and add the following code:
import { ApiPromise, WsProvider } from '@polkadot/api';
const POLKADOT_TESTNET_RPC = 'INSERT_WS_ENDPOINT';
// Example address to queryconst ADDRESS = 'INSERT_ADDRESS';
async function main() { // Create a WebSocket provider const wsProvider = new WsProvider(POLKADOT_TESTNET_RPC);
// Initialize the API const api = await ApiPromise.create({ provider: wsProvider });
console.log('Connected to Polkadot Hub TestNet'); console.log(`Querying runtime APIs for: ${ADDRESS}\n`);
// Call AccountNonceApi to get the account nonce const nonce = await api.call.accountNonceApi.accountNonce(ADDRESS); console.log('AccountNonceApi Results:'); console.log(` Account Nonce: ${nonce.toString()}`);
// Query metadata versions using Metadata runtime API const metadataVersions = await api.call.metadata.metadataVersions(); console.log('\nMetadata API Results:'); console.log( ` Supported Metadata Versions: [${metadataVersions.map((v) => v.toString()).join(', ')}]` );
// Disconnect from the node await api.disconnect();}
main().catch(console.error);Ensure to replace INSERT_WS_ENDPOINT with a valid WebSocket endpoint (e.g., wss://asset-hub-paseo.dotters.network) and INSERT_ADDRESS with the account address you want to query.
Run the script:
node runtime-apis.jsYou should see output similar to:
Prerequisites
- Node.js v18 or higher
- npm, pnpm, or yarn package manager
Environment Setup
-
Create and initialize a new project:
Terminal window mkdir dedot-runtime-api-example && cd dedot-runtime-api-example && \npm init -y && npm pkg set type=module -
Install dependencies:
Terminal window npm install dedot && \npm install --save-dev @dedot/chaintypes @types/node tsx typescript
Call Runtime APIs
The following example demonstrates calling several runtime APIs:
accountNonceApi.accountNonce: Gets the current nonce for an account.metadata.metadataVersions: Retrieves supported metadata versions.
Create a file named runtime-apis.ts and add the following code:
import { DedotClient, WsProvider } from 'dedot';import type { PolkadotAssetHubApi } from '@dedot/chaintypes';
const POLKADOT_TESTNET_RPC = 'INSERT_WS_ENDPOINT';
// Example address to queryconst ADDRESS = 'INSERT_ADDRESS';
async function main() { // Initialize provider and client with Polkadot TestNet types const provider = new WsProvider(POLKADOT_TESTNET_RPC); const client = await DedotClient.new<PolkadotAssetHubApi>(provider);
console.log('Connected to Polkadot Hub TestNet'); console.log(`Querying runtime APIs for: ${ADDRESS}\n`);
// Call AccountNonceApi to get the account nonce const nonce = await client.call.accountNonceApi.accountNonce(ADDRESS); console.log('AccountNonceApi Results:'); console.log(` Account Nonce: ${nonce}`);
// Query metadata versions using Metadata runtime API const metadataVersions = await client.call.metadata.metadataVersions(); console.log('\nMetadata API Results:'); console.log(` Supported Metadata Versions: [${metadataVersions.join(', ')}]`);
// Disconnect the client await client.disconnect();}
main().catch(console.error);Ensure to replace INSERT_WS_ENDPOINT with a valid WebSocket endpoint (e.g., wss://asset-hub-paseo.dotters.network) and INSERT_ADDRESS with the account address you want to query.
Run the script:
npx tsx runtime-apis.tsYou should see output similar to:
Prerequisites
- Python 3.8 or higher
- pip package manager
Environment Setup
-
Create a new project directory and set up a virtual environment:
Terminal window mkdir psi-runtime-api-example && cd psi-runtime-api-example && \python3 -m venv venv && source venv/bin/activate -
Install the substrate-interface package:
Terminal window pip install substrate-interface
Call Runtime APIs
The following example demonstrates calling several runtime APIs:
AccountNonceApi.account_nonce: Gets the current nonce for an account.Core.version: Retrieves runtime version information.
Create a file named runtime_apis.py and add the following code:
from substrateinterface import SubstrateInterface
POLKADOT_TESTNET_RPC = "INSERT_WS_ENDPOINT"
# Example address to queryADDRESS = "INSERT_ADDRESS"
def main(): # Connect to Polkadot Hub TestNet substrate = SubstrateInterface(url=POLKADOT_TESTNET_RPC)
print("Connected to Polkadot Hub TestNet") print(f"Querying runtime APIs for: {ADDRESS}\n")
# Call AccountNonceApi to get the account nonce nonce = substrate.runtime_call("AccountNonceApi", "account_nonce", [ADDRESS]) print("AccountNonceApi Results:") print(f" Account Nonce: {nonce.value}")
# Query runtime version using Core runtime API version = substrate.runtime_call("Core", "version", []) print("\nCore API Results:") print(f" Spec Name: {version.value['spec_name']}") print(f" Spec Version: {version.value['spec_version']}") print(f" Impl Version: {version.value['impl_version']}")
# Close connection substrate.close()
if __name__ == "__main__": main()Ensure to replace INSERT_WS_ENDPOINT with a valid WebSocket endpoint (e.g., wss://asset-hub-paseo.dotters.network) and INSERT_ADDRESS with the account address you want to query.
Run the script:
python runtime_apis.pyYou should see output similar to:
Subxt is a Rust library that provides compile-time type safety through code generation from chain metadata.
Prerequisites
- Rust toolchain (latest stable)
- Cargo package manager
Environment Setup
-
Create a new Rust project:
Terminal window cargo new subxt-runtime-api-example && cd subxt-runtime-api-example -
Install the Subxt CLI:
Terminal window cargo install subxt-cli@0.50.1 -
Download the Polkadot Hub TestNet metadata:
Terminal window subxt metadata --url INSERT_WS_ENDPOINT -o polkadot_testnet_metadata.scaleEnsure to replace
INSERT_WS_ENDPOINTwith the proper WebSocket endpoint, such aswss://asset-hub-paseo.dotters.networkfor Polkadot Hub TestNet. -
Update
Cargo.tomlwith the required dependencies:Cargo.toml [package]name = "subxt-runtime-api-example"version = "0.1.0"edition = "2021"[[bin]]name = "runtime_apis"path = "src/bin/runtime_apis.rs"[dependencies]subxt = "0.50.0"tokio = { version = "1", features = ["rt", "macros"] }
Call Runtime APIs
The following example demonstrates calling several runtime APIs:
AccountNonceApi.account_nonce: Gets the current nonce using the static interface.Metadata.metadata_versions: Retrieves supported metadata versions using the dynamic interface.
Create a file at src/bin/runtime_apis.rs and add the following code:
use std::str::FromStr;use subxt::dynamic::Value;use subxt::utils::AccountId32;use subxt::{OnlineClient, PolkadotConfig};
// Generate an interface from the node's metadata#[subxt::subxt(runtime_metadata_path = "polkadot_testnet_metadata.scale")]pub mod polkadot_testnet {}
const POLKADOT_TESTNET_RPC: &str = "INSERT_WS_ENDPOINT";
// Example address to queryconst 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(POLKADOT_TESTNET_RPC).await?;
// Anchor to the current block let at_block = api.at_current_block().await?;
println!("Connected to Polkadot Hub TestNet"); println!("Querying runtime APIs for: {}\n", ADDRESS);
// Parse the address let account = AccountId32::from_str(ADDRESS)?;
// Call AccountNonceApi using static interface let nonce_call = polkadot_testnet::runtime_apis() .account_nonce_api() .account_nonce(account.clone()); let nonce = at_block.runtime_apis().call(nonce_call).await?; println!("AccountNonceApi Results:"); println!(" Account Nonce: {}", nonce);
// Call Metadata API to get supported versions using dynamic call let metadata_versions_call = subxt::dynamic::runtime_api_call::<_, Value>("Metadata", "metadata_versions", ()); let versions_result = at_block .runtime_apis() .call(metadata_versions_call) .await?; println!("\nMetadata API Results:"); println!( " Supported Metadata Versions: {}", versions_result );
Ok(())}Ensure to replace INSERT_WS_ENDPOINT with a valid WebSocket endpoint (e.g., wss://asset-hub-paseo.dotters.network) and INSERT_ADDRESS with the account address you want to query.
Run the script:
cargo run --bin runtime_apisYou should see output similar to:
Available Runtime APIs
Section titled “Available Runtime APIs”The following runtime APIs are commonly available on Polkadot SDK-based chains:
| API | Description |
|---|---|
AccountNonceApi | Get current transaction nonce for an account |
TransactionPaymentApi | Query transaction fees and weight information |
TransactionPaymentCallApi | Estimate fees for a call without creating an extrinsic |
Metadata | Query metadata versions and runtime metadata |
BlockBuilder | Access block building functionality |
Core | Core runtime version and execution |
TaggedTransactionQueue | Validate transactions in the pool |
OffchainWorkerApi | Offchain worker functionality |
SessionKeys | Session key management |
GrandpaApi | GRANDPA finality information |
BabeApi | BABE consensus information |
NominationPoolsApi | Nomination pools data and pending rewards |
StakingApi | Staking-related computations |
Where to Go Next
Section titled “Where to Go Next”Now that you understand how to call runtime APIs to execute logic within the runtime, explore these related topics:
-
Query with SDKs
Use TypeScript, Python, or Rust SDKs for programmatic access.
-
Query On-Chain State with Sidecar REST API
Learn how to query on-chain state using the Sidecar REST API
-
Send Transactions
Learn to construct and submit transactions.