Skip to content

Commit

Permalink
Add EventReport and failed xt check to examples (#615)
Browse files Browse the repository at this point in the history
* update author tests

* fix comment

* use submit_and_watch_extrinsic_until instead of without_events in examples

* add Txstatus

* add .clone

* update examples

* rename files

* fix file comments

* also update custom_nonce

* fix typos

* fix tests

* add some tests

* fix typo
  • Loading branch information
haerdib authored Jul 24, 2023
1 parent eb1bc03 commit f25124a
Show file tree
Hide file tree
Showing 18 changed files with 240 additions and 149 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -134,13 +134,13 @@ jobs:
benchmark_bulk_xt,
compose_extrinsic_offline,
custom_nonce,
event_callback,
event_error_details,
check_extrinsic_events,
get_account_identity,
get_blocks_async,
get_storage,
print_metadata,
staking_batch_payout,
subscribe_events,
sudo,
transfer_with_tungstenite_client,
transfer_with_ws_client,
Expand Down
9 changes: 4 additions & 5 deletions examples/examples/benchmark_bulk_xt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,6 @@

//! This example floods the node with a series of transactions.

// run this against test node with
// > substrate-test-node --dev --execution native --ws-port 9979 -ltxpool=debug

use kitchensink_runtime::{AccountId, BalancesCall, RuntimeCall};
use sp_keyring::AccountKeyring;
use substrate_api_client::{
Expand All @@ -26,8 +23,10 @@ use substrate_api_client::{
Api, SubmitExtrinsic,
};

// To test this example in CI, we run it against the Substrate kitchensink node. Therefore, we use the AssetRuntimeConfig
// ! Careful: Most runtimes uses plain as tips, they need a polkadot config.
// To test this example with CI we run it against the Substrate kitchensink node, which uses the asset pallet.
// Therefore, we need to use the `AssetRuntimeConfig` in this example.
// ! However, most Substrate runtimes do not use the asset pallet at all. So if you run an example against your own node
// you most likely should use `DefaultRuntimeConfig` instead.

// Define an extrinsic signer type which sets the generic types of the `GenericExtrinsicSigner`.
// This way, the types don't have to be reassigned with every usage of this type and makes
Expand Down
142 changes: 142 additions & 0 deletions examples/examples/check_extrinsic_events.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
/*
Copyright 2019 Supercomputing Systems AG
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

use sp_keyring::AccountKeyring;
use substrate_api_client::{
ac_node_api::EventDetails,
ac_primitives::{AssetRuntimeConfig, Config, ExtrinsicSigner},
extrinsic::BalancesExtrinsics,
rpc::JsonrpseeClient,
Api, GetAccountInformation, SubmitAndWatch, TransactionStatus, XtStatus,
};

// To test this example with CI we run it against the Substrate kitchensink node, which uses the asset pallet.
// Therefore, we need to use the `AssetRuntimeConfig` in this example.
// ! However, most Substrate runtimes do not use the asset pallet at all. So if you run an example against your own node
// you most likely should use `DefaultRuntimeConfig` instead.

type Hash = <AssetRuntimeConfig as Config>::Hash;

#[tokio::main]
async fn main() {
env_logger::init();

// Initialize api and set the signer (sender) that is used to sign the extrinsics.
let alice_signer = AccountKeyring::Alice.pair();
let client = JsonrpseeClient::with_default_url().unwrap();
let mut api = Api::<AssetRuntimeConfig, _>::new(client).unwrap();
api.set_signer(ExtrinsicSigner::<AssetRuntimeConfig>::new(alice_signer));

let alice = AccountKeyring::Alice.to_account_id();
let balance_of_alice = api.get_account_data(&alice).unwrap().unwrap().free;
println!("[+] Alice's Free Balance is {balance_of_alice}\n");

let bob = AccountKeyring::Bob.to_account_id();
let balance_of_bob = api.get_account_data(&bob).unwrap().unwrap_or_default().free;
println!("[+] Bob's Free Balance is {balance_of_bob}\n");

// First we want to see the events of a failed extrinsic.
// So lets create an extrinsic that will not succeed:
// Alice tries so transfer all her balance, but that will not work, because
// she will not have enough balance left to pay the fees.
let bad_transfer_extrinsic =
api.balance_transfer_allow_death(bob.clone().into(), balance_of_alice);
println!("[+] Composed extrinsic: {bad_transfer_extrinsic:?}\n",);

// Send and watch extrinsic until InBlock.
let result = api.submit_and_watch_extrinsic_until(bad_transfer_extrinsic, XtStatus::InBlock);
println!("[+] Sent the transfer extrinsic. Result {result:?}");

// Check if the transfer really has failed:
match result {
Ok(_report) => {
panic!("Exptected the call to fail.");
},
Err(e) => {
println!("[+] Couldn't execute the extrinsic due to {e:?}\n");
let string_error = format!("{e:?}");
assert!(string_error.contains("FundsUnavailable"));
},
};

// Verify that Bob's free Balance hasn't changed.
let new_balance_of_bob = api.get_account_data(&bob).unwrap().unwrap().free;
println!("[+] Bob's Free Balance is now {}\n", new_balance_of_bob);
assert_eq!(balance_of_bob, new_balance_of_bob);

// Verify that Alice's free Balance decreased: paid fees.
let new_balance_of_alice = api.get_account_data(&alice).unwrap().unwrap().free;
println!("[+] Alice's Free Balance is now {}\n", new_balance_of_alice);
assert!(balance_of_alice > new_balance_of_alice);

// Next, we send an extrinsic that should succeed:
let balance_to_transfer = 1000;
let good_transfer_extrinsic =
api.balance_transfer_allow_death(bob.clone().into(), balance_to_transfer);
// Send and watch extrinsic until InBlock.
let result = api.submit_and_watch_extrinsic_until(good_transfer_extrinsic, XtStatus::InBlock);
println!("[+] Sent the transfer extrinsic.");

// Check if the transfer really was successful:
match result {
Ok(report) => {
let extrinsic_hash = report.extrinsic_hash;
let block_hash = report.block_hash.unwrap();
let extrinsic_status = report.status;
let extrinsic_events = report.events.unwrap();

println!("[+] Extrinsic with hash {extrinsic_hash:?} was successfully executed.",);
println!("[+] Extrinsic got included in block with hash {block_hash:?}");
println!("[+] Watched extrinsic until it reached the status {extrinsic_status:?}");
println!("[+] The following events were thrown when the extrinsic was executed: {extrinsic_events:?}");

assert!(matches!(extrinsic_status, TransactionStatus::InBlock(_block_hash)));
assert_associated_events_match_expected(extrinsic_events);
},
Err(e) => {
panic!("Expected the transfer to succeed. Instead, it failed due to {e:?}");
},
};

// Verify that Bob release has received the transferred amount.
let new_balance_of_bob = api.get_account_data(&bob).unwrap().unwrap().free;
println!("[+] Bob's Free Balance is now {}\n", new_balance_of_bob);
let expected_balance_of_bob = balance_of_bob + balance_to_transfer;
assert_eq!(expected_balance_of_bob, new_balance_of_bob);
}

fn assert_associated_events_match_expected(events: Vec<EventDetails<Hash>>) {
// First event
assert_eq!(events[0].pallet_name(), "Balances");
assert_eq!(events[0].variant_name(), "Withdraw");

assert_eq!(events[1].pallet_name(), "Balances");
assert_eq!(events[1].variant_name(), "Transfer");

assert_eq!(events[2].pallet_name(), "Balances");
assert_eq!(events[2].variant_name(), "Deposit");

assert_eq!(events[3].pallet_name(), "Treasury");
assert_eq!(events[3].variant_name(), "Deposit");

assert_eq!(events[4].pallet_name(), "Balances");
assert_eq!(events[4].variant_name(), "Deposit");

assert_eq!(events[5].pallet_name(), "TransactionPayment");
assert_eq!(events[5].variant_name(), "TransactionFeePaid");

assert_eq!(events[6].pallet_name(), "System");
assert_eq!(events[6].variant_name(), "ExtrinsicSuccess");
}
10 changes: 6 additions & 4 deletions examples/examples/compose_extrinsic_offline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
*/

//! This example shows how to use the compose_extrinsic_offline macro which generates an extrinsic
//! without asking the node for nonce and does not need to know the metadata
//! without asking the node for nonce and does not need to know the metadata.

use kitchensink_runtime::{BalancesCall, RuntimeCall};
use sp_keyring::AccountKeyring;
Expand All @@ -25,8 +25,10 @@ use substrate_api_client::{
Api, GetChainInfo, SubmitAndWatch, XtStatus,
};

// To test this example in CI, we run it against the Substrate kitchensink node. Therefore, we use the AssetRuntimeConfig
// ! Careful: Most runtimes uses plain as tips, they need a polkadot config.
// To test this example with CI we run it against the Substrate kitchensink node, which uses the asset pallet.
// Therefore, we need to use the `AssetRuntimeConfig` in this example.
// ! However, most Substrate runtimes do not use the asset pallet at all. So if you run an example against your own node
// you most likely should use `DefaultRuntimeConfig` instead.

#[tokio::main]
async fn main() {
Expand Down Expand Up @@ -66,7 +68,7 @@ async fn main() {

// Send and watch extrinsic until in block (online).
let block_hash = api
.submit_and_watch_extrinsic_until_without_events(xt, XtStatus::InBlock)
.submit_and_watch_extrinsic_until(xt, XtStatus::InBlock)
.unwrap()
.block_hash
.unwrap();
Expand Down
10 changes: 5 additions & 5 deletions examples/examples/contract_instantiate_with_code.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,10 @@ use substrate_api_client::{
SubmitAndWatch, XtStatus,
};

// To test this example in CI, we run it against the Substrate kitchensink node. Therefore, we use the AssetRuntimeConfig
// ! Careful: Most runtimes uses plain as tips, they need a polkadot config.
// To test this example with CI we run it against the Substrate kitchensink node, which uses the asset pallet.
// Therefore, we need to use the `AssetRuntimeConfig` in this example.
// ! However, most Substrate runtimes do not use the asset pallet at all. So if you run an example against your own node
// you most likely should use `DefaultRuntimeConfig` instead.

#[allow(unused)]
#[derive(Decode)]
Expand Down Expand Up @@ -89,8 +91,6 @@ async fn main() {
let xt = api.contract_call(contract.into(), 500_000, 500_000, vec![0u8]);

println!("[+] Calling the contract with extrinsic Extrinsic:\n{:?}\n\n", xt);
let report = api
.submit_and_watch_extrinsic_until_without_events(xt, XtStatus::Finalized)
.unwrap();
let report = api.submit_and_watch_extrinsic_until(xt, XtStatus::Finalized).unwrap();
println!("[+] Extrinsic got finalized. Extrinsic Hash: {:?}", report.extrinsic_hash);
}
8 changes: 5 additions & 3 deletions examples/examples/custom_nonce.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,10 @@ use substrate_api_client::{
Api, Error, GetChainInfo, SubmitAndWatch, UnexpectedTxStatus, XtStatus,
};

// To test this example in CI, we run it against the Substrate kitchensink node. Therefore, we use the AssetRuntimeConfig.
// ! Careful: Most runtimes uses plain as tips, they need a polkadot config.
// To test this example with CI we run it against the Substrate kitchensink node, which uses the asset pallet.
// Therefore, we need to use the `AssetRuntimeConfig` in this example.
// ! However, most Substrate runtimes do not use the asset pallet at all. So if you run an example against your own node
// you most likely should use `DefaultRuntimeConfig` instead.

#[tokio::main]
async fn main() {
Expand Down Expand Up @@ -61,7 +63,7 @@ async fn main() {
println!("[+] Composed Extrinsic:\n {:?}\n", xt);

// Send and watch extrinsic until InBlock.
let result = api.submit_and_watch_extrinsic_until_without_events(xt, XtStatus::InBlock);
let result = api.submit_and_watch_extrinsic_until(xt, XtStatus::InBlock);
println!("Returned Result {:?}", result);
match result {
Err(Error::UnexpectedTxStatus(UnexpectedTxStatus::Future)) => {
Expand Down
77 changes: 0 additions & 77 deletions examples/examples/event_error_details.rs

This file was deleted.

8 changes: 5 additions & 3 deletions examples/examples/get_account_identity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,10 @@ type BalanceOf<T> = <<T as pallet_identity::Config>::Currency as Currency<
type MaxRegistrarsOf<T> = <T as pallet_identity::Config>::MaxRegistrars;
type MaxAdditionalFieldsOf<T> = <T as pallet_identity::Config>::MaxAdditionalFields;

// To test this example in CI, we run it against the Substrate kitchensink node. Therefore, we use the AssetRuntimeConfig
// ! Careful: Most runtimes uses plain as tips, they need a polkadot config.
// To test this example with CI we run it against the Substrate kitchensink node, which uses the asset pallet.
// Therefore, we need to use the `AssetRuntimeConfig` in this example.
// ! However, most Substrate runtimes do not use the asset pallet at all. So if you run an example against your own node
// you most likely should use `DefaultRuntimeConfig` instead.

#[tokio::main]
async fn main() {
Expand Down Expand Up @@ -65,7 +67,7 @@ async fn main() {

// Send and watch extrinsic until InBlock.
let _block_hash = api
.submit_and_watch_extrinsic_until_without_events(xt, XtStatus::InBlock)
.submit_and_watch_extrinsic_until(xt, XtStatus::InBlock)
.unwrap()
.block_hash
.unwrap();
Expand Down
6 changes: 4 additions & 2 deletions examples/examples/get_blocks_async.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,10 @@ async fn main() {
println!("Please compile this example with `--no-default-features` for it to run properly.")
}

// To test this example in CI, we run it against the Substrate kitchensink node. Therefore, we use the AssetRuntimeConfig
// ! Careful: Most runtimes uses plain as tips, they need a polkadot config.
// To test this example with CI we run it against the Substrate kitchensink node, which uses the asset pallet.
// Therefore, we need to use the `AssetRuntimeConfig` in this example.
// ! However, most Substrate runtimes do not use the asset pallet at all. So if you run an example against your own node
// you most likely should use `DefaultRuntimeConfig` instead.

#[cfg(not(feature = "sync-examples"))]
#[tokio::main]
Expand Down
6 changes: 4 additions & 2 deletions examples/examples/get_storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,10 @@ use substrate_api_client::{
Api, GetAccountInformation, GetStorage,
};

// To test this example in CI, we run it against the Substrate kitchensink node. Therefore, we use the AssetRuntimeConfig
// ! Careful: Most runtimes uses plain as tips, they need a polkadot config.
// To test this example with CI we run it against the Substrate kitchensink node, which uses the asset pallet.
// Therefore, we need to use the `AssetRuntimeConfig` in this example.
// ! However, most Substrate runtimes do not use the asset pallet at all. So if you run an example against your own node
// you most likely should use `DefaultRuntimeConfig` instead.

type AccountInfo = GenericAccountInfo<
<AssetRuntimeConfig as Config>::Index,
Expand Down
6 changes: 4 additions & 2 deletions examples/examples/print_metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,10 @@

use substrate_api_client::{ac_primitives::AssetRuntimeConfig, rpc::JsonrpseeClient, Api};

// To test this example in CI, we run it against the Substrate kitchensink node. Therefore, we use the AssetRuntimeConfig
// ! Careful: Most runtimes uses plain as tips, they need a polkadot config.
// To test this example with CI we run it against the Substrate kitchensink node, which uses the asset pallet.
// Therefore, we need to use the `AssetRuntimeConfig` in this example.
// ! However, most Substrate runtimes do not use the asset pallet at all. So if you run an example against your own node
// you most likely should use `DefaultRuntimeConfig` instead.

#[tokio::main]
async fn main() {
Expand Down
Loading

0 comments on commit f25124a

Please sign in to comment.