Skip to content

Commit dc3b90c

Browse files
committed
Replace code with snippets
1 parent 0b40df1 commit dc3b90c

File tree

3 files changed

+129
-112
lines changed

3 files changed

+129
-112
lines changed

.snippets/code/develop/toolkit/api-libraries/subxt/subxt.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,10 @@ use subxt::utils::AccountId32;
33
use subxt::{OnlineClient, PolkadotConfig};
44
use subxt_signer::{bip39::Mnemonic,sr25519::Keypair};
55

6+
// Generate an interface that we can use from the node's metadata.
7+
#[subxt::subxt(runtime_metadata_path = "./polkadot_metadata.scale")]
8+
pub mod polkadot {}
9+
610
#[tokio::main(flavor = "current_thread")]
711
async fn main() -> Result<(), Box<dyn std::error::Error>> {
812
// Define the node URL.

develop/toolkit/api-libraries/subxt.md

Lines changed: 20 additions & 79 deletions
Original file line numberDiff line numberDiff line change
@@ -56,15 +56,7 @@ These dependencies are essential for interacting with the blockchain:
5656
After adding the dependencies, your `Cargo.toml` should look like this:
5757

5858
```toml
59-
[package]
60-
name = "my_project"
61-
version = "0.1.0"
62-
edition = "2021"
63-
64-
[dependencies]
65-
subxt = "0.39.0"
66-
subxt-signer = "0.39.0"
67-
tokio = { version = "1.43.0", features = ["rt", "macros"] }
59+
--8<-- 'code/develop/toolkit/api-libraries/subxt/Cargo.toml'
6860
```
6961

7062
## Get Started
@@ -84,33 +76,28 @@ subxt metadata --url INSERT_NODE_URL > polkadot_metadata.scale
8476
Use the `#[subxt::subxt]` macro to generate a type-safe Rust interface from the downloaded metadata:
8577

8678
```rust
87-
// Generate an interface that we can use from the node's metadata.
88-
#[subxt::subxt(runtime_metadata_path = "./polkadot_metadata.scale")]
89-
pub mod polkadot {}
79+
--8<-- 'code/develop/toolkit/api-libraries/subxt/subxt.rs:6:8'
9080
```
9181

82+
Once subxt interfaces are generated, you can interact with your node in the following ways:
83+
84+
- **Transactions** - builds and submits transactions, monitors their inclusion in blocks, and retrieves associated events
85+
- **Storage** - enables querying of node storage data
86+
- **Events** - retrieves events emitted from recent blocks
87+
- **Constants** - accesses constant values stored in nodes that remain unchanged across a specific runtime version.
88+
- **Blocks** - loads recent blocks or subscribes to new/finalized blocks, allowing examination of extrinsics, events, and storage at those blocks
89+
- **Runtime APIs** - makes calls into pallet runtime APIs to fetch data
90+
- **Custom values** - accesses "custom values" contained within metadata
91+
- **Raw RPC calls** - facilitates raw RPC requests to compatible nodes
92+
9293
### Initializing the Subxt client
9394

9495
To interact with a blockchain node using Subxt, create an asynchronous main function and initialize the client. Replace `INSERT_NODE_URL` with the URL of your target node:
9596

9697
```rust
97-
use std::str::FromStr;
98-
use subxt::utils::AccountId32;
99-
use subxt::{OnlineClient, PolkadotConfig};
100-
use subxt_signer::{bip39::Mnemonic,sr25519::Keypair};
101-
102-
#[tokio::main(flavor = "current_thread")]
103-
async fn main() -> Result<(), Box<dyn std::error::Error>> {
104-
// Define the node URL.
105-
const NODE_URL: &str = "INSERT_NODE_URL";
106-
107-
// Initialize the Subxt client for interacting with the blockchain.
108-
let api = OnlineClient::<PolkadotConfig>::from_url(NODE_URL).await?;
109-
98+
--8<-- 'code/develop/toolkit/api-libraries/subxt/subxt.rs::17'
11099
// Your code here...
111-
112-
Ok(())
113-
}
100+
--8<-- 'code/develop/toolkit/api-libraries/subxt/subxt.rs:73:75'
114101
```
115102

116103
### Reading Chain Data
@@ -120,35 +107,17 @@ Subxt provides multiple ways to access on-chain data:
120107
- Constants - constants are predefined values in the runtime that remain unchanged unless modified by a runtime upgrade
121108

122109
For example, to retrieve the existential deposit, use:
110+
123111
```rust
124-
// A query to obtain some contant:
125-
let constant_query = polkadot::constants().balances().existential_deposit();
126-
127-
// Obtain the value:
128-
let value = api.constants().at(&constant_query)?;
112+
--8<-- 'code/develop/toolkit/api-libraries/subxt/subxt.rs:18:24'
129113
```
130114

131115
- State - state refers to the current chain data, which updates with each block
132116

133117
To fetch account information, use:
118+
134119
```rust
135-
// Define the target account address.
136-
const ADDRESS: &str = "INSERT_ADDRESS";
137-
let account = AccountId32::from_str(ADDRESS).unwrap();
138-
139-
// Build a storage query to access account information.
140-
let storage_query = polkadot::storage().system().account(&account.into());
141-
142-
// Fetch the latest state for the account.
143-
let result = api
144-
.storage()
145-
.at_latest()
146-
.await?
147-
.fetch(&storage_query)
148-
.await?
149-
.unwrap();
150-
151-
println!("Account info: {:?}", result);
120+
--8<-- 'code/develop/toolkit/api-libraries/subxt/subxt.rs:26:42'
152121
```
153122

154123
### Submitting Transasctions
@@ -158,35 +127,7 @@ To submit a transaction, you need to construct an extrinsic, sign it with your p
158127
For example, to transfer funds to another account:
159128

160129
```rust
161-
// Define the recipient address and transfer amount.
162-
const DEST_ADDRESS: &str = "INSERT_DEST_ADDRESS";
163-
const AMOUNT: u128 = INSERT_AMOUNT;
164-
165-
// Convert the recipient address into an `AccountId32`.
166-
let dest = AccountId32::from_str(DEST_ADDRESS).unwrap();
167-
168-
// Build the balance transfer extrinsic.
169-
let balance_transfer_tx = polkadot::tx()
170-
.balances()
171-
.transfer_allow_death(dest.into(), AMOUNT);
172-
173-
// Load the sender's keypair from a mnemonic phrase.
174-
const SECRET_PHRASE: &str = "INSERT_SECRET_PHRASE";
175-
let mnemonic = Mnemonic::parse(SECRET_PHRASE).unwrap();
176-
let sender_keypair = Keypair::from_phrase(&mnemonic, None).unwrap();
177-
178-
// Sign and submit the extrinsic, then wait for it to be finalized.
179-
let events = api
180-
.tx()
181-
.sign_and_submit_then_watch_default(&balance_transfer_tx, &sender_keypair)
182-
.await?
183-
.wait_for_finalized_success()
184-
.await?;
185-
186-
// Check for a successful transfer event.
187-
if let Some(event) = events.find_first::<polkadot::balances::events::Transfer>()? {
188-
println!("Balance transfer successful: {:?}", event);
189-
}
130+
--8<-- 'code/develop/toolkit/api-libraries/subxt/subxt.rs:44:72'
190131
```
191132

192133
## Where to Go Next

llms.txt

Lines changed: 105 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -7823,7 +7823,7 @@ After adding the dependencies, your `Cargo.toml` should look like this:
78237823

78247824
```toml
78257825
[package]
7826-
name = "my_project"
7826+
name = "my-project"
78277827
version = "0.1.0"
78287828
edition = "2021"
78297829

@@ -7850,11 +7850,21 @@ subxt metadata --url INSERT_NODE_URL > polkadot_metadata.scale
78507850
Use the `#[subxt::subxt]` macro to generate a type-safe Rust interface from the downloaded metadata:
78517851

78527852
```rust
7853-
// Generate an interface that we can use from the node's metadata.
78547853
#[subxt::subxt(runtime_metadata_path = "./polkadot_metadata.scale")]
78557854
pub mod polkadot {}
78567855
```
78577856

7857+
Once subxt interfaces are generated, you can interact with your node in the following ways:
7858+
7859+
- **Transactions** - builds and submits transactions, monitors their inclusion in blocks, and retrieves associated events
7860+
- **Storage** - enables querying of node storage data
7861+
- **Events** - retrieves events emitted from recent blocks
7862+
- **Constants** - accesses constant values stored in nodes that remain unchanged across a specific runtime version.
7863+
- **Blocks** - loads recent blocks or subscribes to new/finalized blocks, allowing examination of extrinsics, events, and storage at those blocks
7864+
- **Runtime APIs** - makes calls into pallet runtime APIs to fetch data
7865+
- **Custom values** - accesses "custom values" contained within metadata
7866+
- **Raw RPC calls** - facilitates raw RPC requests to compatible nodes
7867+
78587868
### Initializing the Subxt client
78597869

78607870
To interact with a blockchain node using Subxt, create an asynchronous main function and initialize the client. Replace `INSERT_NODE_URL` with the URL of your target node:
@@ -7865,6 +7875,10 @@ use subxt::utils::AccountId32;
78657875
use subxt::{OnlineClient, PolkadotConfig};
78667876
use subxt_signer::{bip39::Mnemonic,sr25519::Keypair};
78677877

7878+
// Generate an interface that we can use from the node's metadata.
7879+
#[subxt::subxt(runtime_metadata_path = "./polkadot_metadata.scale")]
7880+
pub mod polkadot {}
7881+
78687882
#[tokio::main(flavor = "current_thread")]
78697883
async fn main() -> Result<(), Box<dyn std::error::Error>> {
78707884
// Define the node URL.
@@ -7873,9 +7887,66 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
78737887
// Initialize the Subxt client for interacting with the blockchain.
78747888
let api = OnlineClient::<PolkadotConfig>::from_url(NODE_URL).await?;
78757889

7876-
// Your code here...
7890+
// A query to obtain some contant:
7891+
let constant_query = polkadot::constants().balances().existential_deposit();
7892+
7893+
// Obtain the value:
7894+
let value = api.constants().at(&constant_query)?;
7895+
7896+
println!("Existential deposit: {:?}", value);
7897+
7898+
// Define the target account address.
7899+
const ADDRESS: &str = "INSERT_ADDRESS";
7900+
let account = AccountId32::from_str(ADDRESS).unwrap();
7901+
7902+
// Build a storage query to access account information.
7903+
let storage_query = polkadot::storage().system().account(&account.into());
7904+
7905+
// Fetch the latest state for the account.
7906+
let result = api
7907+
.storage()
7908+
.at_latest()
7909+
.await?
7910+
.fetch(&storage_query)
7911+
.await?
7912+
.unwrap();
7913+
7914+
println!("Account info: {:?}", result);
7915+
7916+
// Define the recipient address and transfer amount.
7917+
const DEST_ADDRESS: &str = "INSERT_DEST_ADDRESS";
7918+
const AMOUNT: u128 = INSERT_AMOUNT;
7919+
7920+
// Convert the recipient address into an `AccountId32`.
7921+
let dest = AccountId32::from_str(DEST_ADDRESS).unwrap();
7922+
7923+
// Build the balance transfer extrinsic.
7924+
let balance_transfer_tx = polkadot::tx()
7925+
.balances()
7926+
.transfer_allow_death(dest.into(), AMOUNT);
7927+
7928+
// Load the sender's keypair from a mnemonic phrase.
7929+
const SECRET_PHRASE: &str = "INSERT_SECRET_PHRASE";
7930+
let mnemonic = Mnemonic::parse(SECRET_PHRASE).unwrap();
7931+
let sender_keypair = Keypair::from_phrase(&mnemonic, None).unwrap();
7932+
7933+
// Sign and submit the extrinsic, then wait for it to be finalized.
7934+
let events = api
7935+
.tx()
7936+
.sign_and_submit_then_watch_default(&balance_transfer_tx, &sender_keypair)
7937+
.await?
7938+
.wait_for_finalized_success()
7939+
.await?;
7940+
7941+
// Check for a successful transfer event.
7942+
if let Some(event) = events.find_first::<polkadot::balances::events::Transfer>()? {
7943+
println!("Balance transfer successful: {:?}", event);
7944+
}
78777945

78787946
Ok(())
7947+
}
7948+
// Your code here...
7949+
Ok(())
78797950
}
78807951
```
78817952

@@ -7886,19 +7957,21 @@ Subxt provides multiple ways to access on-chain data:
78867957
- Constants - constants are predefined values in the runtime that remain unchanged unless modified by a runtime upgrade
78877958

78887959
For example, to retrieve the existential deposit, use:
7960+
78897961
```rust
7890-
// A query to obtain some contant:
78917962
let constant_query = polkadot::constants().balances().existential_deposit();
78927963

78937964
// Obtain the value:
78947965
let value = api.constants().at(&constant_query)?;
7966+
7967+
println!("Existential deposit: {:?}", value);
78957968
```
78967969

78977970
- State - state refers to the current chain data, which updates with each block
78987971

78997972
To fetch account information, use:
7973+
79007974
```rust
7901-
// Define the target account address.
79027975
const ADDRESS: &str = "INSERT_ADDRESS";
79037976
let account = AccountId32::from_str(ADDRESS).unwrap();
79047977

@@ -7924,35 +7997,34 @@ To submit a transaction, you need to construct an extrinsic, sign it with your p
79247997
For example, to transfer funds to another account:
79257998

79267999
```rust
7927-
// Define the recipient address and transfer amount.
79288000
const DEST_ADDRESS: &str = "INSERT_DEST_ADDRESS";
7929-
const AMOUNT: u128 = INSERT_AMOUNT;
7930-
7931-
// Convert the recipient address into an `AccountId32`.
7932-
let dest = AccountId32::from_str(DEST_ADDRESS).unwrap();
7933-
7934-
// Build the balance transfer extrinsic.
7935-
let balance_transfer_tx = polkadot::tx()
7936-
.balances()
7937-
.transfer_allow_death(dest.into(), AMOUNT);
7938-
7939-
// Load the sender's keypair from a mnemonic phrase.
7940-
const SECRET_PHRASE: &str = "INSERT_SECRET_PHRASE";
7941-
let mnemonic = Mnemonic::parse(SECRET_PHRASE).unwrap();
7942-
let sender_keypair = Keypair::from_phrase(&mnemonic, None).unwrap();
7943-
7944-
// Sign and submit the extrinsic, then wait for it to be finalized.
7945-
let events = api
7946-
.tx()
7947-
.sign_and_submit_then_watch_default(&balance_transfer_tx, &sender_keypair)
7948-
.await?
7949-
.wait_for_finalized_success()
7950-
.await?;
7951-
7952-
// Check for a successful transfer event.
7953-
if let Some(event) = events.find_first::<polkadot::balances::events::Transfer>()? {
7954-
println!("Balance transfer successful: {:?}", event);
7955-
}
8001+
const AMOUNT: u128 = INSERT_AMOUNT;
8002+
8003+
// Convert the recipient address into an `AccountId32`.
8004+
let dest = AccountId32::from_str(DEST_ADDRESS).unwrap();
8005+
8006+
// Build the balance transfer extrinsic.
8007+
let balance_transfer_tx = polkadot::tx()
8008+
.balances()
8009+
.transfer_allow_death(dest.into(), AMOUNT);
8010+
8011+
// Load the sender's keypair from a mnemonic phrase.
8012+
const SECRET_PHRASE: &str = "INSERT_SECRET_PHRASE";
8013+
let mnemonic = Mnemonic::parse(SECRET_PHRASE).unwrap();
8014+
let sender_keypair = Keypair::from_phrase(&mnemonic, None).unwrap();
8015+
8016+
// Sign and submit the extrinsic, then wait for it to be finalized.
8017+
let events = api
8018+
.tx()
8019+
.sign_and_submit_then_watch_default(&balance_transfer_tx, &sender_keypair)
8020+
.await?
8021+
.wait_for_finalized_success()
8022+
.await?;
8023+
8024+
// Check for a successful transfer event.
8025+
if let Some(event) = events.find_first::<polkadot::balances::events::Transfer>()? {
8026+
println!("Balance transfer successful: {:?}", event);
8027+
}
79568028
```
79578029

79588030
## Where to Go Next

0 commit comments

Comments
 (0)