From d59a33156fce79d5e0ef6ab936cbc79ad08bc2e5 Mon Sep 17 00:00:00 2001 From: Alexandru Vasile Date: Thu, 18 May 2023 20:14:14 +0300 Subject: [PATCH] examples: Add light client example Signed-off-by: Alexandru Vasile --- Cargo.lock | 2 -- examples/Cargo.toml | 2 +- examples/examples/tx_basic_light_client.rs | 38 ++++++++++++++++++++++ 3 files changed, 39 insertions(+), 3 deletions(-) create mode 100644 examples/examples/tx_basic_light_client.rs diff --git a/Cargo.lock b/Cargo.lock index 6dca5bffd3..885bd27d8a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4336,8 +4336,6 @@ dependencies = [ "sp-keyring", "subxt", "tokio", - "tracing", - "tracing-subscriber 0.3.17", ] [[package]] diff --git a/examples/Cargo.toml b/examples/Cargo.toml index d6972e640c..79b1615d88 100644 --- a/examples/Cargo.toml +++ b/examples/Cargo.toml @@ -13,7 +13,7 @@ homepage.workspace = true description = "Subxt example usage" [dev-dependencies] -subxt = { workspace = true } +subxt = { workspace = true, default-features = false, features = ["default", "experimental-light-client"]} tokio = { workspace = true } futures = { workspace = true } hex = { workspace = true } diff --git a/examples/examples/tx_basic_light_client.rs b/examples/examples/tx_basic_light_client.rs new file mode 100644 index 0000000000..e89c0da5ce --- /dev/null +++ b/examples/examples/tx_basic_light_client.rs @@ -0,0 +1,38 @@ +use sp_keyring::AccountKeyring; +use subxt::rpc::LightClient; +use subxt::{tx::PairSigner, OnlineClient, PolkadotConfig}; + +use std::sync::Arc; + +// Generate an interface that we can use from the node's metadata. +#[subxt::subxt(runtime_metadata_path = "../artifacts/polkadot_metadata_small.scale")] +pub mod polkadot {} + +#[tokio::main] +async fn main() -> Result<(), Box> { + // Create a light client from the provided chain spec. + let light_client = LightClient::new(include_str!("../../artifacts/dev_spec.json"))?; + let api = OnlineClient::::from_rpc_client(Arc::new(light_client)).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::()?; + if let Some(event) = transfer_event { + println!("Balance transfer success: {event:?}"); + } + + Ok(()) +}