Skip to content

Commit

Permalink
style: use cargo fmt to adjust files
Browse files Browse the repository at this point in the history
  • Loading branch information
hsxyl committed Sep 30, 2022
1 parent 28a2f94 commit 3abaf84
Show file tree
Hide file tree
Showing 39 changed files with 597 additions and 434 deletions.
2 changes: 1 addition & 1 deletion src/commands/check_unprofitable_validator/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,4 @@ impl CheckUnprofitableValidator {
pub async fn process(self) -> crate::CliResult {
self.selected_env.process().await
}
}
}
8 changes: 4 additions & 4 deletions src/commands/check_unprofitable_validator/select_env/mod.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
mod select_rpc;

use strum::{EnumDiscriminants, EnumIter, EnumMessage};
use crate::near::types::NearEnv;
use strum::{EnumDiscriminants, EnumIter, EnumMessage};

#[derive(Debug, Clone, EnumDiscriminants, interactive_clap_derive::InteractiveClap)]
#[strum_discriminants(derive(EnumMessage, EnumIter))]
Expand All @@ -17,8 +17,8 @@ pub enum SelectEnv {
impl SelectEnv {
pub async fn process(self) -> crate::CliResult {
Ok(match self {
SelectEnv::Testnet(env) => {env.process(NearEnv::Testnet).await?}
SelectEnv::Mainnet(env) => {env.process(NearEnv::Mainnet).await?}
SelectEnv::Testnet(env) => env.process(NearEnv::Testnet).await?,
SelectEnv::Mainnet(env) => env.process(NearEnv::Mainnet).await?,
})
}
}
Expand All @@ -30,7 +30,7 @@ mod env {
#[interactive_clap(context = ())]
pub struct Env {
#[interactive_clap(named_arg)]
pub select_rpc: super::select_rpc::SelectRpc
pub select_rpc: super::select_rpc::SelectRpc,
}

impl Env {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
use std::collections::{HashMap, HashSet};
use color_eyre::owo_colors::OwoColorize;
use dialoguer::Input;
use itertools::Itertools;
use near_primitives::types::AccountId;
use prettytable::{Cell, ptable, row, Row, Table, table};
use crate::CliResult;
use crate::near::rpc::client::Client;
use crate::near::types::NearEnv;
use crate::oct::contracts::anchor::AnchorContract;
use crate::oct::contracts::anchor::types::{AnchorStatus, AppchainState};
use crate::oct::contracts::anchor::AnchorContract;
use crate::oct::contracts::registry::RegistryContract;
use crate::CliResult;
use color_eyre::owo_colors::OwoColorize;
use dialoguer::Input;
use itertools::Itertools;
use near_primitives::types::AccountId;
use prettytable::{ptable, row, table, Cell, Row, Table};
use std::collections::{HashMap, HashSet};

#[derive(Debug, Clone, interactive_clap_derive::InteractiveClap)]
#[interactive_clap(context = ())]
Expand All @@ -18,70 +18,102 @@ pub struct InputRegistryAccount {
}

impl InputRegistryAccount {

pub fn input_registry_account(
_context: &()
) -> color_eyre::eyre::Result<String> {
pub fn input_registry_account(_context: &()) -> color_eyre::eyre::Result<String> {
Ok(Input::new()
.with_prompt("What is the registry account?")
.interact_text()?)
}

pub async fn process(
self,
connection_config: NearEnv,
client: Client
) -> CliResult {

let registry_contract = RegistryContract::new(self.registry_account.parse()?, &client );
let appchain_ids = registry_contract.get_appchain_ids().await.map_err(|err| {
color_eyre::Report::msg(format!("Failed to get appchain ids,contract_id:{}, error: {}", self.registry_account.clone(), err))
}).unwrap();
pub async fn process(self, connection_config: NearEnv, client: Client) -> CliResult {
let registry_contract = RegistryContract::new(self.registry_account.parse()?, &client);
let appchain_ids = registry_contract
.get_appchain_ids()
.await
.map_err(|err| {
color_eyre::Report::msg(format!(
"Failed to get appchain ids,contract_id:{}, error: {}",
self.registry_account.clone(),
err
))
})
.unwrap();

for appchain_id in appchain_ids {

let anchor_contract_id: AccountId = format!("{}.{}", appchain_id, self.registry_account).parse()?;
let anchor_contract_id: AccountId =
format!("{}.{}", appchain_id, self.registry_account).parse()?;

let anchor = AnchorContract {
account_id: anchor_contract_id.clone(),
client: &client
client: &client,
};

let appchain_state = registry_contract.get_appchain_status_of(appchain_id.clone()).await.map_err(|err| {
color_eyre::Report::msg(format!("Failed to get anchor({}) state, error: {}",anchor_contract_id, err))
} )?.appchain_state;
let appchain_state = registry_contract
.get_appchain_status_of(appchain_id.clone())
.await
.map_err(|err| {
color_eyre::Report::msg(format!(
"Failed to get anchor({}) state, error: {}",
anchor_contract_id, err
))
})?
.appchain_state;

if !(matches!(appchain_state, AppchainState::Active)) {
println!("The state of {} is {:?}, skip check!\n", anchor_contract_id.blue(), appchain_state.yellow());
println!(
"The state of {} is {:?}, skip check!\n",
anchor_contract_id.blue(),
appchain_state.yellow()
);
continue;
}

let anchor_status = anchor.get_anchor_status().await.map_err(|err| {
color_eyre::Report::msg(format!("Failed to get anchor({}) status, error: {}",anchor_contract_id, err))
color_eyre::Report::msg(format!(
"Failed to get anchor({}) status, error: {}",
anchor_contract_id, err
))
})?;
let era_now = anchor_status.index_range_of_validator_set_history.end_index;

let setting = anchor.get_protocol_settings().await.map_err(|err| {
color_eyre::Report::msg(format!("Failed to get protocol settings, error: {}", err))
})?;

let start_check_era = if (setting.maximum_allowed_unprofitable_era_count as u64)>era_now {0} else {era_now-(setting.maximum_allowed_unprofitable_era_count as u64)};
let start_check_era =
if (setting.maximum_allowed_unprofitable_era_count as u64) > era_now {
0
} else {
era_now - (setting.maximum_allowed_unprofitable_era_count as u64)
};

let mut era_with_unprofitable_validator_ids = HashMap::new();
let mut unprofitable_account_ids = HashSet::new();

for era in start_check_era..(era_now+1) {

let info = anchor.get_validator_set_info_of(era).await.map_err(|err| {
color_eyre::Report::msg(format!("Failed to get validator set info, error: {}", err))
})?.expect(format!("Error: Get empty validator set info of era({})", era).as_str());

info.unprofitable_validator_ids.iter().for_each(|e| {unprofitable_account_ids.insert(e.clone());} );
for era in start_check_era..(era_now + 1) {
let info = anchor
.get_validator_set_info_of(era)
.await
.map_err(|err| {
color_eyre::Report::msg(format!(
"Failed to get validator set info, error: {}",
err
))
})?
.expect(
format!("Error: Get empty validator set info of era({})", era).as_str(),
);

info.unprofitable_validator_ids.iter().for_each(|e| {
unprofitable_account_ids.insert(e.clone());
});

era_with_unprofitable_validator_ids.insert(era, info.unprofitable_validator_ids);

}
print_auto_unbound_info_table(anchor_contract_id, unprofitable_account_ids, era_with_unprofitable_validator_ids);
print_auto_unbound_info_table(
anchor_contract_id,
unprofitable_account_ids,
era_with_unprofitable_validator_ids,
);
}

Ok(())
Expand All @@ -91,21 +123,33 @@ impl InputRegistryAccount {
fn print_auto_unbound_info_table(
anchor_contract_id: AccountId,
unprofitable_account_ids: HashSet<AccountId>,
era_with_unprofitable_validator_ids: HashMap<u64, Vec<AccountId>>
era_with_unprofitable_validator_ids: HashMap<u64, Vec<AccountId>>,
) {
let mut table = Table::new();
let eras = era_with_unprofitable_validator_ids.iter().map(|(era,_ )| *era ).sorted().collect_vec();
let eras = era_with_unprofitable_validator_ids
.iter()
.map(|(era, _)| *era)
.sorted()
.collect_vec();

assert!(eras.len()>0, "Failed to print_auto_unbound_info_table, the era len should > 0.");
assert!(
eras.len() > 0,
"Failed to print_auto_unbound_info_table, the era len should > 0."
);

if unprofitable_account_ids.is_empty() {
// head.add_cell(Cell::new(format!("No unprofitable validator in allowed time range.").green().to_string().as_str()));
table.add_row(row![format!("No unprofitable validator from era_{} to era_{}.", eras[0], eras[eras.len()-1]).green()]);
table.add_row(row![format!(
"No unprofitable validator from era_{} to era_{}.",
eras[0],
eras[eras.len() - 1]
)
.green()]);
} else {

let mut head = row!["validators\\eras"];

eras.iter().for_each(|era| {head.add_cell(Cell::new(era.to_string().as_str()))});
eras.iter()
.for_each(|era| head.add_cell(Cell::new(era.to_string().as_str())));
table.add_row(head);
for account_id in unprofitable_account_ids {
let mut row = row![account_id];
Expand All @@ -114,15 +158,25 @@ fn print_auto_unbound_info_table(
.get(era)
.expect("Failed to get user's information unprofitable")
.contains(&account_id);
let cell_content = if is_unprofitable {format!("×").red().to_string()}
else {format!("√").green().to_string()};
let cell_content = if is_unprofitable {
format!("×").red().to_string()
} else {
format!("√").green().to_string()
};
row.add_cell(Cell::new(cell_content.as_str()));
}
table.add_row(row);
}
}

let title = Row::new(vec![Cell::new(format!("{} unprofitable_validator_ids table", anchor_contract_id.blue()).as_str()).style_spec("H1")]);
let title = Row::new(vec![Cell::new(
format!(
"{} unprofitable_validator_ids table",
anchor_contract_id.blue()
)
.as_str(),
)
.style_spec("H1")]);
table.set_titles(title);

table.printstd();
Expand All @@ -136,11 +190,16 @@ struct AutoBondInfo {
#[test]
fn test() {
let s = row![];
let mut table = table!(["1","2","3"]);
table.add_row(Row::new(vec![Cell::new(format!("No unprofitable validator in allowed time range.").green().to_string().as_str())]));
let mut table = table!(["1", "2", "3"]);
table.add_row(Row::new(vec![Cell::new(
format!("No unprofitable validator in allowed time range.")
.green()
.to_string()
.as_str(),
)]));
table.printstd();

let state = AppchainState::Active;
println!("{}", matches!(state, AppchainState::Active));
println!("{}", matches!(state, AppchainState::Frozen));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,22 +22,21 @@ impl SelectRpc {
SelectRpc::Official(rpc) => {
rpc.process(
connection_config.clone(),
Client::new(RpcProvider::NearOfficial.get_rpc_by_env(&connection_config))
).await
Client::new(RpcProvider::NearOfficial.get_rpc_by_env(&connection_config)),
)
.await
}
SelectRpc::BlockPi(rpc) => {
rpc.process(
connection_config.clone(),
Client::new(RpcProvider::BlockPi.get_rpc_by_env(&connection_config))
).await
Client::new(RpcProvider::BlockPi.get_rpc_by_env(&connection_config)),
)
.await
}
}

}

}


pub mod rpc {
use crate::near::rpc::client::Client;
use crate::near::types::NearEnv;
Expand All @@ -46,13 +45,14 @@ pub mod rpc {
#[interactive_clap(context = ())]
pub struct Rpc {
#[interactive_clap(named_arg)]
pub input_registry_account: super::input_registry_account::InputRegistryAccount
pub input_registry_account: super::input_registry_account::InputRegistryAccount,
}

impl Rpc {
pub async fn process(self, connection_config: NearEnv, client: Client) -> crate::CliResult {
self.input_registry_account.process(connection_config, client).await
self.input_registry_account
.process(connection_config, client)
.await
}
}

}
2 changes: 1 addition & 1 deletion src/commands/clean_state_command/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,4 @@ impl CleanStateCommand {
pub async fn process(self) -> crate::CliResult {
self.select_env.process().await
}
}
}
11 changes: 5 additions & 6 deletions src/commands/clean_state_command/select_env/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ use strum::{EnumDiscriminants, EnumIter, EnumMessage};

pub mod select_rpc;


#[derive(Debug, Clone, EnumDiscriminants, interactive_clap_derive::InteractiveClap)]
#[strum_discriminants(derive(EnumMessage, EnumIter))]
#[interactive_clap(context = ())]
Expand All @@ -18,8 +17,8 @@ pub enum SelectEnv {
impl SelectEnv {
pub async fn process(self) -> crate::CliResult {
Ok(match self {
SelectEnv::Testnet(env) => {env.process(NearEnv::Testnet).await?}
SelectEnv::Mainnet(env) => {env.process(NearEnv::Mainnet).await?}
SelectEnv::Testnet(env) => env.process(NearEnv::Testnet).await?,
SelectEnv::Mainnet(env) => env.process(NearEnv::Mainnet).await?,
})
}
}
Expand All @@ -31,12 +30,12 @@ mod env {
#[interactive_clap(context = ())]
pub struct Env {
#[interactive_clap(named_arg)]
pub select_rpc: super::select_rpc::SelectRpc
pub select_rpc: super::select_rpc::SelectRpc,
}

impl Env {
pub async fn process(self, connection_config: NearEnv ) -> crate::CliResult {
pub async fn process(self, connection_config: NearEnv) -> crate::CliResult {
self.select_rpc.process(connection_config).await
}
}
}
}
Loading

0 comments on commit 3abaf84

Please sign in to comment.