Skip to content

Commit

Permalink
refactor: remove unnecessary async
Browse files Browse the repository at this point in the history
  • Loading branch information
evilrobot-01 committed Dec 9, 2024
1 parent 8e95bd6 commit 9f731b4
Show file tree
Hide file tree
Showing 4 changed files with 65 additions and 80 deletions.
67 changes: 30 additions & 37 deletions crates/pop-cli/src/commands/call/parachain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ impl CallParachainCommand {
}
loop {
// Configure the call based on command line arguments/call UI.
let mut call = match self.configure_call(&chain, &mut cli).await {
let mut call = match self.configure_call(&chain, &mut cli) {
Ok(call) => call,
Err(e) => {
display_message(&e.to_string(), false, &mut cli)?;
Expand All @@ -77,7 +77,7 @@ impl CallParachainCommand {
// Display the configured call.
cli.info(call.display(&chain))?;
// Prepare the extrinsic.
let tx = match call.prepare_extrinsic(&chain.client, &mut cli).await {
let tx = match call.prepare_extrinsic(&chain.client, &mut cli) {
Ok(payload) => payload,
Err(e) => {
display_message(&e.to_string(), false, &mut cli)?;
Expand Down Expand Up @@ -122,7 +122,7 @@ impl CallParachainCommand {

// Parse metadata from chain url.
let client = set_up_client(url.as_str()).await?;
let mut pallets = parse_chain_metadata(&client).await.map_err(|e| {
let mut pallets = parse_chain_metadata(&client).map_err(|e| {
anyhow!(format!("Unable to fetch the chain metadata: {}", e.to_string()))
})?;
// Sort by name for display.
Expand All @@ -134,16 +134,16 @@ impl CallParachainCommand {
}

// Configure the call based on command line arguments/call UI.
async fn configure_call(&mut self, chain: &Chain, cli: &mut impl Cli) -> Result<CallParachain> {
fn configure_call(&mut self, chain: &Chain, cli: &mut impl Cli) -> Result<CallParachain> {
loop {
// Resolve pallet.
let pallet = match self.pallet {
Some(ref pallet_name) => find_pallet_by_name(&chain.pallets, pallet_name).await?,
Some(ref pallet_name) => find_pallet_by_name(&chain.pallets, pallet_name)?,
None => {
// Specific predefined actions first.
if let Some(action) = prompt_predefined_actions(&chain.pallets, cli).await? {
if let Some(action) = prompt_predefined_actions(&chain.pallets, cli)? {
self.extrinsic = Some(action.extrinsic_name().to_string());
find_pallet_by_name(&chain.pallets, action.pallet_name()).await?
find_pallet_by_name(&chain.pallets, action.pallet_name())?
} else {
let mut prompt = cli.select("Select the pallet to call:");
for pallet_item in &chain.pallets {
Expand All @@ -157,7 +157,7 @@ impl CallParachainCommand {
// Resolve extrinsic.
let extrinsic = match self.extrinsic {
Some(ref extrinsic_name) =>
find_extrinsic_by_name(&chain.pallets, &pallet.name, extrinsic_name).await?,
find_extrinsic_by_name(&chain.pallets, &pallet.name, extrinsic_name)?,
None => {
let mut prompt_extrinsic = cli.select("Select the extrinsic to call:");
for extrinsic in &pallet.extrinsics {
Expand Down Expand Up @@ -308,7 +308,7 @@ struct CallParachain {

impl CallParachain {
// Prepares the extrinsic or query.
async fn prepare_extrinsic(
fn prepare_extrinsic(
&self,
client: &OnlineClient<SubstrateConfig>,
cli: &mut impl Cli,
Expand All @@ -317,9 +317,7 @@ impl CallParachain {
self.pallet.name.as_str(),
&self.extrinsic,
self.args.clone(),
)
.await
{
) {
Ok(tx) => tx,
Err(e) => {
return Err(anyhow!("Error: {}", e));
Expand Down Expand Up @@ -396,12 +394,9 @@ fn display_message(message: &str, success: bool, cli: &mut impl Cli) -> Result<(
}

// Prompts the user for some predefined actions.
async fn prompt_predefined_actions(
pallets: &[Pallet],
cli: &mut impl Cli,
) -> Result<Option<Action>> {
fn prompt_predefined_actions(pallets: &[Pallet], cli: &mut impl Cli) -> Result<Option<Action>> {
let mut predefined_action = cli.select("What would you like to do?");
for action in supported_actions(pallets).await {
for action in supported_actions(pallets) {
predefined_action = predefined_action.item(
Some(action.clone()),
action.description(),
Expand Down Expand Up @@ -625,7 +620,7 @@ mod tests {
let chain = call_config.configure_chain(&mut cli).await?;
assert_eq!(chain.url, Url::parse("wss://rpc1.paseo.popnetwork.xyz")?);

let call_parachain = call_config.configure_call(&chain, &mut cli).await?;
let call_parachain = call_config.configure_call(&chain, &mut cli)?;
assert_eq!(call_parachain.pallet.name, "System");
assert_eq!(call_parachain.extrinsic.name, "remark");
assert_eq!(call_parachain.args, ["0x11".to_string()].to_vec());
Expand Down Expand Up @@ -661,7 +656,6 @@ mod tests {
true,
Some(
supported_actions(&chain.pallets)
.await
.into_iter()
.map(|action| {
(action.description().to_string(), action.pallet_name().to_string())
Expand All @@ -678,7 +672,7 @@ mod tests {
.expect_input("Enter the value for the parameter: para_id", "2000".into())
.expect_input("Signer of the extrinsic:", "//Bob".into());

let call_parachain = call_config.configure_call(&chain, &mut cli).await?;
let call_parachain = call_config.configure_call(&chain, &mut cli)?;

assert_eq!(call_parachain.pallet.name, "OnDemand");
assert_eq!(call_parachain.extrinsic.name, "place_order_allow_death");
Expand Down Expand Up @@ -712,18 +706,18 @@ mod tests {
let mut cli = MockCli::new();
// Error, wrong name of the pallet.
assert!(
matches!(call_config.prepare_extrinsic(&client, &mut cli).await, Err(message) if message.to_string().contains("Failed to encode call data. Metadata Error: Pallet with name WrongName not found"))
matches!(call_config.prepare_extrinsic(&client, &mut cli), Err(message) if message.to_string().contains("Failed to encode call data. Metadata Error: Pallet with name WrongName not found"))
);
let pallets = parse_chain_metadata(&client).await?;
call_config.pallet = find_pallet_by_name(&pallets, "System").await?.clone();
let pallets = parse_chain_metadata(&client)?;
call_config.pallet = find_pallet_by_name(&pallets, "System")?.clone();
// Error, wrong name of the extrinsic.
assert!(
matches!(call_config.prepare_extrinsic(&client, &mut cli).await, Err(message) if message.to_string().contains("Failed to encode call data. Metadata Error: Call with name WrongName not found"))
matches!(call_config.prepare_extrinsic(&client, &mut cli), Err(message) if message.to_string().contains("Failed to encode call data. Metadata Error: Call with name WrongName not found"))
);
// Success, extrinsic and pallet specified.
cli = MockCli::new().expect_info("Encoded call data: 0x00000411");
call_config.extrinsic = find_extrinsic_by_name(&pallets, "System", "remark").await?.clone();
let tx = call_config.prepare_extrinsic(&client, &mut cli).await?;
call_config.extrinsic = find_extrinsic_by_name(&pallets, "System", "remark")?.clone();
let tx = call_config.prepare_extrinsic(&client, &mut cli)?;
assert_eq!(tx.call_name(), "remark");
assert_eq!(tx.pallet_name(), "System");

Expand All @@ -733,18 +727,18 @@ mod tests {
#[tokio::test]
async fn user_cancel_submit_extrinsic_works() -> Result<()> {
let client = set_up_client("wss://rpc1.paseo.popnetwork.xyz").await?;
let pallets = parse_chain_metadata(&client).await?;
let pallets = parse_chain_metadata(&client)?;
let mut call_config = CallParachain {
pallet: find_pallet_by_name(&pallets, "System").await?.clone(),
extrinsic: find_extrinsic_by_name(&pallets, "System", "remark").await?.clone(),
pallet: find_pallet_by_name(&pallets, "System")?.clone(),
extrinsic: find_extrinsic_by_name(&pallets, "System", "remark")?.clone(),
args: vec!["0x11".to_string()].to_vec(),
suri: DEFAULT_URI.to_string(),
skip_confirm: false,
};
let mut cli = MockCli::new()
.expect_confirm("Do you want to submit the extrinsic?", false)
.expect_outro_cancel("Extrinsic remark was not submitted.");
let tx = call_config.prepare_extrinsic(&client, &mut cli).await?;
let tx = call_config.prepare_extrinsic(&client, &mut cli)?;
call_config.submit_extrinsic(&client, tx, &mut cli).await?;

cli.verify()
Expand Down Expand Up @@ -859,14 +853,13 @@ mod tests {
#[tokio::test]
async fn prompt_predefined_actions_works() -> Result<()> {
let client = set_up_client("wss://rpc1.paseo.popnetwork.xyz").await?;
let pallets = parse_chain_metadata(&client).await?;
let pallets = parse_chain_metadata(&client)?;
let mut cli = MockCli::new().expect_select(
"What would you like to do?",
Some(true),
true,
Some(
supported_actions(&pallets)
.await
.into_iter()
.map(|action| {
(action.description().to_string(), action.pallet_name().to_string())
Expand All @@ -879,17 +872,17 @@ mod tests {
),
2, // "Mint an Asset" action
);
let action = prompt_predefined_actions(&pallets, &mut cli).await?;
let action = prompt_predefined_actions(&pallets, &mut cli)?;
assert_eq!(action, Some(Action::MintAsset));
cli.verify()
}

#[tokio::test]
async fn prompt_for_param_works() -> Result<()> {
let client = set_up_client("wss://rpc1.paseo.popnetwork.xyz").await?;
let pallets = parse_chain_metadata(&client).await?;
let pallets = parse_chain_metadata(&client)?;
// Using NFT mint extrinsic to test the majority of subfunctions
let extrinsic = find_extrinsic_by_name(&pallets, "Nfts", "mint").await?;
let extrinsic = find_extrinsic_by_name(&pallets, "Nfts", "mint")?;
let mut cli = MockCli::new()
.expect_input("Enter the value for the parameter: collection", "0".into())
.expect_input("Enter the value for the parameter: item", "0".into())
Expand Down Expand Up @@ -940,7 +933,7 @@ mod tests {
cli.verify()?;

// Using Scheduler set_retry extrinsic to test the tuple params
let extrinsic = find_extrinsic_by_name(&pallets, "Scheduler", "set_retry").await?;
let extrinsic = find_extrinsic_by_name(&pallets, "Scheduler", "set_retry")?;
let mut cli = MockCli::new()
.expect_input(
"Enter the value for the parameter: Index 0 of the tuple task",
Expand All @@ -965,7 +958,7 @@ mod tests {
cli.verify()?;

// Using System remark extrinsic to test the sequence params
let extrinsic = find_extrinsic_by_name(&pallets, "System", "remark").await?;
let extrinsic = find_extrinsic_by_name(&pallets, "System", "remark")?;
// Temporal file for testing the input.
let temp_dir = tempdir()?;
let file = temp_dir.path().join("file.json");
Expand Down
11 changes: 4 additions & 7 deletions crates/pop-parachains/src/call/metadata/action.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,13 +106,10 @@ impl Action {
///
/// # Arguments
/// * `pallets`: Supported pallets.
pub async fn supported_actions(pallets: &[Pallet]) -> Vec<Action> {
pub fn supported_actions(pallets: &[Pallet]) -> Vec<Action> {
let mut actions = Vec::new();
for action in Action::VARIANTS.iter() {
if find_extrinsic_by_name(pallets, action.pallet_name(), action.extrinsic_name())
.await
.is_ok()
{
if find_extrinsic_by_name(pallets, action.pallet_name(), action.extrinsic_name()).is_ok() {
actions.push(action.clone());
}
}
Expand Down Expand Up @@ -185,7 +182,7 @@ mod tests {
// Test Pop Parachain.
let mut client: subxt::OnlineClient<subxt::SubstrateConfig> =
set_up_client("wss://rpc1.paseo.popnetwork.xyz").await?;
let mut actions = supported_actions(&parse_chain_metadata(&client).await?).await;
let mut actions = supported_actions(&parse_chain_metadata(&client)?);
assert_eq!(actions.len(), 5);
assert_eq!(actions[0], Action::Transfer);
assert_eq!(actions[1], Action::CreateAsset);
Expand All @@ -195,7 +192,7 @@ mod tests {

// Test Polkadot Relay Chain.
client = set_up_client("wss://polkadot-rpc.publicnode.com").await?;
actions = supported_actions(&parse_chain_metadata(&client).await?).await;
actions = supported_actions(&parse_chain_metadata(&client)?);
assert_eq!(actions.len(), 4);
assert_eq!(actions[0], Action::Transfer);
assert_eq!(actions[1], Action::PurchaseOnDemandCoretime);
Expand Down
34 changes: 16 additions & 18 deletions crates/pop-parachains/src/call/metadata/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,7 @@ impl Display for Extrinsic {
/// * `client`: The client to interact with the chain.
///
/// NOTE: pallets are ordered by their index within the runtime by default.
pub async fn parse_chain_metadata(
client: &OnlineClient<SubstrateConfig>,
) -> Result<Vec<Pallet>, Error> {
pub fn parse_chain_metadata(client: &OnlineClient<SubstrateConfig>) -> Result<Vec<Pallet>, Error> {
let metadata: Metadata = client.metadata();

let pallets = metadata
Expand Down Expand Up @@ -131,7 +129,7 @@ pub async fn parse_chain_metadata(
/// # Arguments
/// * `pallets`: List of pallets available in the chain.
/// * `pallet_name`: The name of the pallet to find.
pub async fn find_pallet_by_name<'a>(
pub fn find_pallet_by_name<'a>(
pallets: &'a [Pallet],
pallet_name: &str,
) -> Result<&'a Pallet, Error> {
Expand All @@ -148,12 +146,12 @@ pub async fn find_pallet_by_name<'a>(
/// * `pallets`: List of pallets available in the chain.
/// * `pallet_name`: The name of the pallet to find.
/// * `extrinsic_name`: Name of the extrinsic to locate.
pub async fn find_extrinsic_by_name<'a>(
pub fn find_extrinsic_by_name<'a>(
pallets: &'a [Pallet],
pallet_name: &str,
extrinsic_name: &str,
) -> Result<&'a Extrinsic, Error> {
let pallet = find_pallet_by_name(pallets, pallet_name).await?;
let pallet = find_pallet_by_name(pallets, pallet_name)?;
if let Some(extrinsic) = pallet.extrinsics.iter().find(|&e| e.name == extrinsic_name) {
Ok(extrinsic)
} else {
Expand All @@ -166,7 +164,7 @@ pub async fn find_extrinsic_by_name<'a>(
/// # Arguments
/// * `params`: The metadata definition for each parameter of the extrinsic.
/// * `raw_params`: A vector of raw string arguments for the extrinsic.
pub async fn parse_extrinsic_arguments(
pub fn parse_extrinsic_arguments(
params: &[Param],
raw_params: Vec<String>,
) -> Result<Vec<Value>, Error> {
Expand Down Expand Up @@ -201,7 +199,7 @@ mod tests {
#[tokio::test]
async fn parse_chain_metadata_works() -> Result<()> {
let client = set_up_client("wss://rpc1.paseo.popnetwork.xyz").await?;
let pallets = parse_chain_metadata(&client).await?;
let pallets = parse_chain_metadata(&client)?;
// Test the first pallet is parsed correctly
let first_pallet = pallets.first().unwrap();
assert_eq!(first_pallet.name, "System");
Expand Down Expand Up @@ -229,11 +227,11 @@ mod tests {
#[tokio::test]
async fn find_pallet_by_name_works() -> Result<()> {
let client = set_up_client("wss://rpc1.paseo.popnetwork.xyz").await?;
let pallets = parse_chain_metadata(&client).await?;
let pallets = parse_chain_metadata(&client)?;
assert!(matches!(
find_pallet_by_name(&pallets, "WrongName").await,
find_pallet_by_name(&pallets, "WrongName"),
Err(Error::PalletNotFound(pallet)) if pallet == "WrongName".to_string()));
let pallet = find_pallet_by_name(&pallets, "Balances").await?;
let pallet = find_pallet_by_name(&pallets, "Balances")?;
assert_eq!(pallet.name, "Balances");
assert_eq!(pallet.extrinsics.len(), 9);
Ok(())
Expand All @@ -242,24 +240,24 @@ mod tests {
#[tokio::test]
async fn find_extrinsic_by_name_works() -> Result<()> {
let client = set_up_client("wss://rpc1.paseo.popnetwork.xyz").await?;
let pallets = parse_chain_metadata(&client).await?;
let pallets = parse_chain_metadata(&client)?;
assert!(matches!(
find_extrinsic_by_name(&pallets, "WrongName", "wrong_extrinsic").await,
find_extrinsic_by_name(&pallets, "WrongName", "wrong_extrinsic"),
Err(Error::PalletNotFound(pallet)) if pallet == "WrongName".to_string()));
assert!(matches!(
find_extrinsic_by_name(&pallets, "Balances", "wrong_extrinsic").await,
find_extrinsic_by_name(&pallets, "Balances", "wrong_extrinsic"),
Err(Error::ExtrinsicNotSupported)
));
let extrinsic = find_extrinsic_by_name(&pallets, "Balances", "force_transfer").await?;
let extrinsic = find_extrinsic_by_name(&pallets, "Balances", "force_transfer")?;
assert_eq!(extrinsic.name, "force_transfer");
assert_eq!(extrinsic.docs, "Exactly as `transfer_allow_death`, except the origin must be root and the source account may be specified.");
assert_eq!(extrinsic.is_supported, true);
assert_eq!(extrinsic.params.len(), 3);
Ok(())
}

#[tokio::test]
async fn parse_extrinsic_arguments_works() -> Result<()> {
#[test]
fn parse_extrinsic_arguments_works() -> Result<()> {
// Values for testing from: https://docs.rs/scale-value/0.18.0/scale_value/stringify/fn.from_str.html
// and https://docs.rs/scale-value/0.18.0/scale_value/stringify/fn.from_str_custom.html
let args = [
Expand Down Expand Up @@ -299,7 +297,7 @@ mod tests {
Param { type_name: "composite".to_string(), ..Default::default() },
];
assert_eq!(
parse_extrinsic_arguments(&params, args).await?,
parse_extrinsic_arguments(&params, args)?,
[
Value::u128(1),
Value::i128(-1),
Expand Down
Loading

0 comments on commit 9f731b4

Please sign in to comment.