Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Subxt Guide #890

Merged
merged 40 commits into from
May 4, 2023
Merged
Show file tree
Hide file tree
Changes from 30 commits
Commits
Show all changes
40 commits
Select commit Hold shift + click to select a range
ba43e7d
WIP Starting to write book; extrinsics first pass done
jsdw Mar 31, 2023
0e8fb4c
Merge branch 'master' into jsdw-book
jsdw Apr 3, 2023
058d892
cargo fmt
jsdw Apr 3, 2023
a86eb54
Merge branch 'master' into jsdw-book
jsdw Apr 5, 2023
24c06a6
Ongoing work; events, constants, wip blocks
jsdw Apr 11, 2023
e0f36ce
Merge branch 'master' into jsdw-book
jsdw Apr 11, 2023
99f1a8f
at_latest() and wip blocks
jsdw Apr 11, 2023
b5171ad
Merge branch 'master' into jsdw-book
jsdw Apr 12, 2023
61538f4
remove need to import parity-scale-codec crate with Subxt for macro t…
jsdw Apr 12, 2023
4860cd3
More docs; expanding on setup guide and finish pass of main sections
jsdw Apr 12, 2023
2a12fdf
Merge branch 'master' into jsdw-book
jsdw Apr 21, 2023
2a5a582
Merge branch 'jsdw-book' of github.com:paritytech/subxt into jsdw-book
jsdw Apr 21, 2023
24849bc
Tidy and remove example section for now
jsdw Apr 21, 2023
75a0ad1
format book lines to 100chars
jsdw Apr 21, 2023
45b56d8
Fix example code
jsdw Apr 21, 2023
1d78129
cargo fmt
jsdw Apr 21, 2023
074444c
cargo fmt
jsdw Apr 21, 2023
18c50be
fix example
jsdw Apr 21, 2023
7f9df99
Fix typos
jsdw Apr 21, 2023
52fd3c1
fix broken doc links, pub mods
jsdw Apr 21, 2023
88ddc52
Update Subxt macro docs
jsdw Apr 21, 2023
241033b
can't link to Subxt here
jsdw Apr 24, 2023
71e23a4
move macro docs to Subxt to make linking better and fix example code
jsdw Apr 24, 2023
6213091
note on macro about docs
jsdw Apr 24, 2023
baba008
Merge branch 'master' into jsdw-book
jsdw Apr 24, 2023
5ccba64
cargo fmt
jsdw Apr 24, 2023
c9dbc2c
Merge branch 'master' into jsdw-book
jsdw Apr 24, 2023
a10c1c1
document the no_default_derives macro feature
jsdw Apr 24, 2023
0b375fd
Merge branch 'master' into jsdw-book
jsdw Apr 24, 2023
64e591c
Merge branch 'master' into jsdw-book
jsdw Apr 26, 2023
67f676a
Merge branch 'master' into jsdw-book
jsdw May 2, 2023
2a2cdd5
Address feedback and remove redundant text
jsdw May 2, 2023
e3a6d9a
Merge branch 'master' into jsdw-book
jsdw May 2, 2023
3bbc87f
Merge branch 'master' into jsdw-book
jsdw May 2, 2023
8924c30
address review comments; minor tweaks
jsdw May 3, 2023
a8c570f
Merge branch 'master' into jsdw-book
jsdw May 3, 2023
4b35311
WIP add Runtime calls to book
jsdw May 4, 2023
e7e450f
Merge branch 'master' into jsdw-book
jsdw May 4, 2023
f0cbfc3
Improve Runtime API docs
jsdw May 4, 2023
e5990ea
expose thing we forgot to expose and doc link fixes
jsdw May 4, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 0 additions & 4 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -86,4 +86,4 @@ subxt-macro = { version = "0.28.0", path = "macro" }
subxt-metadata = { version = "0.28.0", path = "metadata" }
subxt-codegen = { version = "0.28.0", path = "codegen" }
test-runtime = { path = "testing/test-runtime" }
substrate-runner = { path = "testing/substrate-runner" }
substrate-runner = { path = "testing/substrate-runner" }
Binary file modified artifacts/polkadot_metadata.scale
Binary file not shown.
9 changes: 7 additions & 2 deletions codegen/src/api/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -219,8 +219,13 @@ impl RuntimeGenerator {
// Preserve any Rust items that were previously defined in the adorned module
#( #rust_items ) *

// Make it easy to access the root via `root_mod` at different levels:
use super::#mod_ident as root_mod;
// Make it easy to access the root items via `root_mod` at different levels
// without reaching out of this module.
#[allow(unused_imports)]
mod root_mod {
pub use super::*;
}

#types_mod
}
})
Expand Down
4 changes: 0 additions & 4 deletions examples/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,5 @@ description = "Subxt example usage"
subxt = { workspace = true }
tokio = { workspace = true }
futures = { workspace = true }
codec = { package = "parity-scale-codec", workspace = true, features = ["derive", "bit-vec"] }
hex = { workspace = true }
sp-keyring = { workspace = true }
sp-core = { workspace = true }
sp-runtime = { workspace = true }
tracing-subscriber = { workspace = true }
4 changes: 3 additions & 1 deletion examples/README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
# Subxt Examples

Take a look in the [examples](./examples) subfolder for various `subxt` usage examples.
Take a look in the [examples](./examples) subfolder for various `subxt` usage examples.

All examples form part of the `subxt` documentation; there should be no examples without corresponding links from the docs.
40 changes: 0 additions & 40 deletions examples/examples/balance_transfer.rs

This file was deleted.

34 changes: 34 additions & 0 deletions examples/examples/balance_transfer_basic.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
use sp_keyring::AccountKeyring;
use subxt::{tx::PairSigner, OnlineClient, PolkadotConfig};

// Generate an interface that we can use from the node's metadata.
#[subxt::subxt(runtime_metadata_path = "../artifacts/polkadot_metadata.scale")]
pub mod polkadot {}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Create a new API client, configured to talk to Polkadot nodes.
let api = OnlineClient::<PolkadotConfig>::new().await?;

// Build a balance transfer extrinsic.
let dest = AccountKeyring::Bob.to_account_id().into();
let balance_transfer_tx = polkadot::tx().balances().transfer(dest, 10_000);

// Submit the balance transfer extrinsic from Alice, and wait for it to be successful
// and in a finalized block. We get back the extrinsic events if all is well.
let from = PairSigner::new(AccountKeyring::Alice.pair());
let events = api
.tx()
.sign_and_submit_then_watch_default(&balance_transfer_tx, &from)
.await?
.wait_for_finalized_success()
.await?;

// Find a Transfer event and print it.
let transfer_event = events.find_first::<polkadot::balances::events::Transfer>()?;
if let Some(event) = transfer_event {
println!("Balance transfer success: {event:?}");
}

Ok(())
}
54 changes: 54 additions & 0 deletions examples/examples/balance_transfer_status_stream.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
use futures::StreamExt;
use sp_keyring::AccountKeyring;
use subxt::{
tx::{PairSigner, TxStatus},
OnlineClient, PolkadotConfig,
};

// Generate an interface that we can use from the node's metadata.
#[subxt::subxt(runtime_metadata_path = "../artifacts/polkadot_metadata.scale")]
pub mod polkadot {}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let api = OnlineClient::<PolkadotConfig>::new().await?;

let dest = AccountKeyring::Bob.to_account_id().into();
let balance_transfer_tx = polkadot::tx().balances().transfer(dest, 10_000);

let signer = PairSigner::new(AccountKeyring::Alice.pair());
let mut balance_transfer_progress = api
.tx()
.sign_and_submit_then_watch_default(&balance_transfer_tx, &signer)
.await?;

while let Some(status) = balance_transfer_progress.next().await {
match status? {
// It's finalized in a block!
TxStatus::Finalized(in_block) => {
println!(
"Transaction {:?} is finalized in block {:?}",
in_block.extrinsic_hash(),
in_block.block_hash()
);

// grab the events and fail if no ExtrinsicSuccess event seen:
let events = in_block.wait_for_success().await?;
// We can look for events (this uses the static interface; we can also iterate
// over them and dynamically decode them):
let transfer_event = events.find_first::<polkadot::balances::events::Transfer>()?;

if let Some(event) = transfer_event {
println!("Balance transfer success: {event:?}");
} else {
println!("Failed to find Balances::Transfer Event");
}
}
// Just log any other status we encounter:
other => {
println!("Status: {other:?}");
}
}
}
Ok(())
}
46 changes: 11 additions & 35 deletions examples/examples/balance_transfer_with_params.rs
Original file line number Diff line number Diff line change
@@ -1,52 +1,28 @@
// Copyright 2019-2023 Parity Technologies (UK) Ltd.
// This file is dual-licensed as Apache-2.0 or GPL-3.0.
// see LICENSE for license details.

//! To run this example, a local polkadot node should be running. Example verified against polkadot v0.9.28-9ffe6e9e3da.
//!
//! E.g.
//! ```bash
//! curl "https://github.com/paritytech/polkadot/releases/download/v0.9.28/polkadot" --output /usr/local/bin/polkadot --location
//! polkadot --dev --tmp
//! ```

use sp_keyring::AccountKeyring;
use subxt::{
config::{
polkadot::{Era, PlainTip, PolkadotExtrinsicParamsBuilder as Params},
PolkadotConfig,
},
tx::PairSigner,
OnlineClient,
};
use subxt::config::polkadot::{Era, PlainTip, PolkadotExtrinsicParamsBuilder as Params};
use subxt::{tx::PairSigner, OnlineClient, PolkadotConfig};

#[subxt::subxt(runtime_metadata_path = "../artifacts/polkadot_metadata.scale")]
pub mod polkadot {}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
tracing_subscriber::fmt::init();

let signer = PairSigner::new(AccountKeyring::Alice.pair());
let dest = AccountKeyring::Bob.to_account_id().into();

// Create a client to use:
// Create a new API client, configured to talk to Polkadot nodes.
let api = OnlineClient::<PolkadotConfig>::new().await?;

// Create a transaction to submit:
let tx = polkadot::tx()
.balances()
.transfer(dest, 123_456_789_012_345);
// Build a balance transfer extrinsic.
let dest = AccountKeyring::Bob.to_account_id().into();
let tx = polkadot::tx().balances().transfer(dest, 10_000);

// Configure the transaction tip and era:
// Configure the transaction parameters; for Polkadot the tip and era:
let tx_params = Params::new()
.tip(PlainTip::new(20_000_000_000))
.tip(PlainTip::new(1_000))
.era(Era::Immortal, api.genesis_hash());

// submit the transaction:
let hash = api.tx().sign_and_submit(&tx, &signer, tx_params).await?;

println!("Balance transfer extrinsic submitted: {hash}");
let from = PairSigner::new(AccountKeyring::Alice.pair());
let hash = api.tx().sign_and_submit(&tx, &from, tx_params).await?;
println!("Balance transfer extrinsic submitted with hash : {hash}");

Ok(())
}
Original file line number Diff line number Diff line change
@@ -1,15 +1,3 @@
// Copyright 2019-2023 Parity Technologies (UK) Ltd.
// This file is dual-licensed as Apache-2.0 or GPL-3.0.
// see LICENSE for license details.

//! To run this example, a local polkadot node should be running. Example verified against polkadot 0.9.29-41a9d84b152.
//!
//! E.g.
//! ```bash
//! curl "https://github.com/paritytech/polkadot/releases/download/v0.9.29/polkadot" --output /usr/local/bin/polkadot --location
//! polkadot --dev --tmp
//! ```

use futures::StreamExt;
use subxt::{OnlineClient, PolkadotConfig};

Expand All @@ -18,14 +6,13 @@ pub mod polkadot {}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
tracing_subscriber::fmt::init();

// Create a client to use:
let api = OnlineClient::<PolkadotConfig>::new().await?;

// Subscribe to all finalized blocks:
let mut blocks_sub = api.blocks().subscribe_finalized().await?;

// For each block, print a bunch of information about it:
while let Some(block) = blocks_sub.next().await {
let block = block?;

Expand All @@ -36,6 +23,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
println!(" Hash: {block_hash}");
println!(" Extrinsics:");

// Log each of the extrinsic with it's associated events:
let body = block.body().await?;
for ext in body.extrinsics() {
let idx = ext.index();
Expand All @@ -51,8 +39,10 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {

let pallet_name = evt.pallet_name();
let event_name = evt.variant_name();
let event_values = evt.field_values()?;

println!(" {pallet_name}_{event_name}");
println!(" {}", event_values);
}
}
}
Expand Down
39 changes: 0 additions & 39 deletions examples/examples/concurrent_storage_requests.rs

This file was deleted.

17 changes: 17 additions & 0 deletions examples/examples/constants_dynamic.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
use subxt::{OnlineClient, PolkadotConfig};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Create a client to use:
let api = OnlineClient::<PolkadotConfig>::new().await?;

// A dynamic query to obtain some contant:
let constant_query = subxt::dynamic::constant("System", "BlockLength");

// Obtain the value:
let value = api.constants().at(&constant_query)?;

println!("Constant bytes: {:?}", value.encoded());
println!("Constant value: {}", value.to_value()?);
Ok(())
}
19 changes: 19 additions & 0 deletions examples/examples/constants_static.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
use subxt::{OnlineClient, PolkadotConfig};

#[subxt::subxt(runtime_metadata_path = "../artifacts/polkadot_metadata.scale")]
pub mod polkadot {}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Create a client to use:
let api = OnlineClient::<PolkadotConfig>::new().await?;

// A query to obtain some contant:
let constant_query = polkadot::constants().system().block_length();

// Obtain the value:
let value = api.constants().at(&constant_query)?;

println!("Block length: {value:?}");
Ok(())
}
Loading