From c1859dfe1341a96999bd5c76b91d1e33fdcd2530 Mon Sep 17 00:00:00 2001 From: Brayan Vargas <86427419+b-avb@users.noreply.github.com> Date: Mon, 18 Nov 2024 09:17:16 -0500 Subject: [PATCH] Clippy happy (#179) * chore: make clippy happy * style: fmt --- src/components/atoms/attach.rs | 10 ++-- src/components/atoms/avatar.rs | 2 +- src/components/atoms/dropdown.rs | 2 +- src/components/atoms/input.rs | 14 +++-- src/components/atoms/input_tags.rs | 30 +++++----- src/components/atoms/markdown.rs | 18 +++--- src/components/atoms/search_input.rs | 6 +- .../molecules/action_request_list.rs | 8 +-- src/components/molecules/actions/members.rs | 2 +- src/components/molecules/actions/voting.rs | 4 +- src/components/molecules/header.rs | 40 +++++++------ .../molecules/initiative/actions.rs | 8 +-- .../molecules/initiative/settings.rs | 2 +- src/components/molecules/sidebar.rs | 13 +++-- src/hooks/use_communities.rs | 14 ++--- src/hooks/use_connect_wallet.rs | 2 +- src/hooks/use_deposit.rs | 10 ++-- src/hooks/use_initiative.rs | 25 ++++---- src/hooks/use_location.rs | 2 +- src/hooks/use_notification.rs | 2 +- src/hooks/use_onboard.rs | 4 +- src/hooks/use_timestamp.rs | 2 +- src/hooks/use_tooltip.rs | 2 +- src/hooks/use_withdraw.rs | 6 +- src/locales/en-US.json | 3 +- src/locales/es-ES.json | 3 +- src/pages/account.rs | 6 +- src/pages/dashboard.rs | 40 ++++++------- src/pages/deposit.rs | 8 +-- src/pages/explore.rs | 14 ++--- src/pages/initiative.rs | 38 ++----------- src/pages/initiatives.rs | 26 +++------ src/pages/onboarding.rs | 28 ++++----- src/pages/vote.rs | 16 ++---- src/pages/withdraw.rs | 8 +-- src/services/kreivo/communities.rs | 9 ++- src/services/kreivo/community_memberships.rs | 57 +++++++++---------- src/services/kreivo/community_referenda.rs | 11 ++-- src/services/kreivo/community_track.rs | 3 +- src/services/kreivo/preimage.rs | 4 +- src/services/kreivo/system.rs | 3 +- src/services/kreivo/timestamp.rs | 3 +- src/services/kusama/system.rs | 3 +- src/services/market/types.rs | 2 +- 44 files changed, 230 insertions(+), 283 deletions(-) diff --git a/src/components/atoms/attach.rs b/src/components/atoms/attach.rs index 486a7f2..213acce 100644 --- a/src/components/atoms/attach.rs +++ b/src/components/atoms/attach.rs @@ -56,7 +56,7 @@ pub fn Attach(props: AttachProps) -> Element { async move { let files = &event.files().ok_or(AttachError::NotFound)?; let fs = files.files(); - let existing_file = fs.get(0).ok_or(AttachError::NotFound)?; + let existing_file = fs.first().ok_or(AttachError::NotFound)?; let content = files .read_file(existing_file) .await @@ -81,7 +81,7 @@ pub fn Attach(props: AttachProps) -> Element { } _ => gloo::file::Blob::new(content.deref()), }; - let size = blob.size().clone(); + let size = blob.size(); if size > MAX_FILE_SIZE { return Err(AttachError::Size); } @@ -184,11 +184,13 @@ pub fn Attach(props: AttachProps) -> Element { r#type: "file", class: "attach__input", onmounted: move |event| { - event + if let Some(html_element) = event .data .downcast::() .and_then(|element| element.clone().dyn_into::().ok()) - .map(|html_element| textarea_ref.set(Some(Box::new(html_element.clone())))); + { + textarea_ref.set(Some(Box::new(html_element.clone()))) + } }, oninput: on_handle_input } diff --git a/src/components/atoms/avatar.rs b/src/components/atoms/avatar.rs index 2e773a2..114fc55 100644 --- a/src/components/atoms/avatar.rs +++ b/src/components/atoms/avatar.rs @@ -15,7 +15,7 @@ pub struct AvatarProps { } pub fn Avatar(props: AvatarProps) -> Element { let size_avatar = format!("--avatar-size: {}px;", props.size); - let avatar_style = format!("{}", size_avatar); + let avatar_style = size_avatar.to_string(); let variant = match props.variant { Variant::Round => "avatar--round", Variant::SemiRound => "avatar--semi-round", diff --git a/src/components/atoms/dropdown.rs b/src/components/atoms/dropdown.rs index d33f92f..cd22634 100644 --- a/src/components/atoms/dropdown.rs +++ b/src/components/atoms/dropdown.rs @@ -30,7 +30,7 @@ pub struct DropdownProps { pub fn Dropdown(props: DropdownProps) -> Element { let mut is_active = use_signal::(|| false); let disabled = if props.disabled { "button--disabled" } else { "" }; - let placeholder = if let None = props.value { "dropdown__placeholder" } else { "" }; + let placeholder = if props.value.is_none() { "dropdown__placeholder" } else { "" }; let size = match props.size { ElementSize::Big => "dropdown__container--big", ElementSize::Medium => "dropdown__container--medium", diff --git a/src/components/atoms/input.rs b/src/components/atoms/input.rs index d0434a0..9832153 100644 --- a/src/components/atoms/input.rs +++ b/src/components/atoms/input.rs @@ -1,8 +1,8 @@ +use super::dropdown::ElementSize; +use crate::components::atoms::{Icon, IconButton, Search, WarningSign}; use dioxus::prelude::*; use wasm_bindgen::JsCast; use web_sys::HtmlInputElement; -use crate::components::atoms::{Icon, IconButton, Search, WarningSign}; -use super::dropdown::ElementSize; #[derive(PartialEq, Clone)] pub enum InputType { Text, @@ -35,7 +35,7 @@ pub struct InputProps { } pub fn Input(props: InputProps) -> Element { let mut input_ref = use_signal::>>(|| None); - let input_error_container = if let Some(_) = props.error { + let input_error_container = if props.error.is_some() { "input--error-container" } else { "" @@ -71,11 +71,13 @@ pub fn Input(props: InputProps) -> Element { r#type: "{input_type}", class: "input", onmounted: move |event| { - event + if let Some(html_element) = event .data .downcast::() .and_then(|element| element.clone().dyn_into::().ok()) - .map(|html_element| input_ref.set(Some(Box::new(html_element.clone())))); + { + input_ref.set(Some(Box::new(html_element.clone()))) + } if input_type == "date" { if let Some(input_element) = input_ref() { input_element.set_type("text") @@ -98,7 +100,7 @@ pub fn Input(props: InputProps) -> Element { placeholder: if props.required { format!("{}*", props.placeholder) } else { - format!("{}", props.placeholder) + props.placeholder.to_string() }, oninput: move |event| props.on_input.call(event), onkeypress: move |event| props.on_keypress.call(event) diff --git a/src/components/atoms/input_tags.rs b/src/components/atoms/input_tags.rs index 9b11a26..d76f1c8 100644 --- a/src/components/atoms/input_tags.rs +++ b/src/components/atoms/input_tags.rs @@ -24,7 +24,7 @@ pub struct InputTagsProps { on_click: EventHandler, } pub fn InputTags(props: InputTagsProps) -> Element { - let input_error_container = if let Some(_) = props.error { + let input_error_container = if props.error.is_some() { "input--error-container" } else { "" @@ -37,19 +37,19 @@ pub fn InputTags(props: InputTagsProps) -> Element { let is_active = use_signal::(|| false); let mut tags = use_signal::>(|| { - if props.message.len() > 0 { + if !props.message.is_empty() { props .message - .split(",") - .map(|e| String::from(e)) + .split(',') + .map(String::from) .collect::>() } else { vec![] } }); - let mut complete_value = use_signal(|| String::new()); - let mut new_value = use_signal(|| String::new()); - let mut temporal_value = use_signal(|| String::new()); + let mut complete_value = use_signal(String::new); + let mut new_value = use_signal(String::new); + let mut temporal_value = use_signal(String::new); let mut is_editing_tag = use_signal(|| None); rsx!( section { @@ -109,7 +109,7 @@ pub fn InputTags(props: InputTagsProps) -> Element { ) }) }, - if new_value().trim().len() > 0 { + if !new_value().trim().is_empty() { div { class: "tag", class: if is_editing_tag().is_some() { "tag--editing" }, @@ -119,7 +119,7 @@ pub fn InputTags(props: InputTagsProps) -> Element { new_value.set(temporal_value()); is_editing_tag.set(None); }, - if temporal_value().len() > 0 { + if !temporal_value().is_empty() { "{temporal_value()}" } else { "{new_value()}" @@ -141,11 +141,7 @@ pub fn InputTags(props: InputTagsProps) -> Element { class: "input", value: new_value, required: props.required, - placeholder: if props.required { - format!("{}*", props.placeholder) - } else { - format!("{}", props.placeholder) - }, + placeholder: if props.required { format!("{}*", props.placeholder) } else { props.placeholder }, oninput: move |event| { if let Some(index) = is_editing_tag() { tags.with_mut(|t| t[index] = event.value()); @@ -171,7 +167,7 @@ pub fn InputTags(props: InputTagsProps) -> Element { .map(|s| s.to_string()) .collect(); let last_tag = e[1].clone(); - if last_tag.len() > 0 { + if !last_tag.is_empty() { tags.with_mut(|t| t.push(e[0].clone())); complete_value.set(tags().join(",")); new_value.set(last_tag.clone()); @@ -181,11 +177,11 @@ pub fn InputTags(props: InputTagsProps) -> Element { } else { new_value.set(event.value().clone()); } - if event.value().len() == 0 && tags.last().is_some() { + if event.value().is_empty() && tags.last().is_some() { new_value.set(tags().last().unwrap().to_string()); tags.with_mut(|t| t.pop()); } - let val = if temporal_value().len() > 0 { + let val = if !temporal_value().is_empty() { temporal_value() } else { new_value() diff --git a/src/components/atoms/markdown.rs b/src/components/atoms/markdown.rs index a0a500a..494272e 100644 --- a/src/components/atoms/markdown.rs +++ b/src/components/atoms/markdown.rs @@ -55,7 +55,7 @@ pub fn Markdown(props: MarkdownProps) -> Element { let i18 = use_i18(); let mut is_editor_loaded = use_signal(|| false); let content = use_signal(|| { - if props.content.len() > 0 { + if !props.content.is_empty() { props.content.clone() } else { translate!(i18, "utils.markdown.value") @@ -97,21 +97,25 @@ pub fn Markdown(props: MarkdownProps) -> Element { class: if !is_markdown_visible() { "hide" } else { "markdown__wrapper--editor" }, div { onmounted: move |event| { - event + if let Some(html_element) = event .data .downcast::() .and_then(|element| element.clone().dyn_into::().ok()) - .map(|html_element| toolbar_ref.set(Some(Box::new(html_element.clone())))); - }, + { + toolbar_ref.set(Some(Box::new(html_element.clone()))) + } + } } div { onmounted: move |event| { - event + if let Some(html_element) = event .data .downcast::() .and_then(|element| element.clone().dyn_into::().ok()) - .map(|html_element| editor_ref.set(Some(Box::new(html_element.clone())))); - }, + { + editor_ref.set(Some(Box::new(html_element.clone()))) + } + } } } div { diff --git a/src/components/atoms/search_input.rs b/src/components/atoms/search_input.rs index 40c617a..c20de36 100644 --- a/src/components/atoms/search_input.rs +++ b/src/components/atoms/search_input.rs @@ -1,6 +1,6 @@ -use dioxus::prelude::*; -use crate::components::atoms::{Icon, IconButton, Search}; use super::dropdown::ElementSize; +use crate::components::atoms::{Icon, IconButton, Search}; +use dioxus::prelude::*; #[derive(PartialEq, Props, Clone)] pub struct SearchInputProps { message: String, @@ -15,7 +15,7 @@ pub struct SearchInputProps { on_click: EventHandler, } pub fn SearchInput(props: SearchInputProps) -> Element { - let input_error_container = if let Some(_) = props.error { + let input_error_container = if props.error.is_some() { "input--error-container" } else { "" diff --git a/src/components/molecules/action_request_list.rs b/src/components/molecules/action_request_list.rs index 12d8e5b..4746598 100644 --- a/src/components/molecules/action_request_list.rs +++ b/src/components/molecules/action_request_list.rs @@ -95,10 +95,10 @@ pub fn ActionRequestList(props: ActionRequestListProps) -> Element { for request in props.actions.iter() { div { class: "requests", match request { - ActionItem::AddMembers(action) => render_add_members(& action), - ActionItem::KusamaTreasury(action) => render_kusama_treasury(& action), - ActionItem::VotingOpenGov(action) => render_voting_open_gov(& action) , - ActionItem::CommunityTransfer(action) => render_community_transfer(& action) } + ActionItem::AddMembers(action) => render_add_members(action), + ActionItem::KusamaTreasury(action) => render_kusama_treasury(action), + ActionItem::VotingOpenGov(action) => render_voting_open_gov(action) , + ActionItem::CommunityTransfer(action) => render_community_transfer(action) } } } ) diff --git a/src/components/molecules/actions/members.rs b/src/components/molecules/actions/members.rs index e79a1fb..d108064 100644 --- a/src/components/molecules/actions/members.rs +++ b/src/components/molecules/actions/members.rs @@ -30,7 +30,7 @@ pub fn MembersAction(props: VotingProps) -> Element { }, value: match member.medium.clone() { MediumOptions::Wallet => translate!(i18, "onboard.invite.form.wallet.label"), } }; - + rsx!( li { ComboInput { diff --git a/src/components/molecules/actions/voting.rs b/src/components/molecules/actions/voting.rs index 00b3cf5..c4005b6 100644 --- a/src/components/molecules/actions/voting.rs +++ b/src/components/molecules/actions/voting.rs @@ -146,7 +146,7 @@ pub fn VotingAction(props: VotingProps) -> Element { RadioButton { title: translate!(i18, "initiative.steps.actions.voting_open_gov.standard.aye"), name: "Aye", - checked: vote.aye.clone(), + checked: vote.aye, on_change: move |_| { if let ActionItem::VotingOpenGov(ref mut meta) = initiative.get_action(props.index) { vote_b.aye = true; @@ -158,7 +158,7 @@ pub fn VotingAction(props: VotingProps) -> Element { RadioButton { title: translate!(i18, "initiative.steps.actions.voting_open_gov.standard.nay"), name: "Nay", - checked: !vote.aye.clone(), + checked: !vote.aye, on_change: move |_| { if let ActionItem::VotingOpenGov(ref mut meta) = initiative.get_action(props.index) { vote_c.aye = false; diff --git a/src/components/molecules/header.rs b/src/components/molecules/header.rs index e7fa954..dce2472 100644 --- a/src/components/molecules/header.rs +++ b/src/components/molecules/header.rs @@ -41,9 +41,7 @@ pub fn Header() -> Element { let mut connect_handled = use_signal(|| false); let get_account = move || { - let Some(user_session) = session.get() else { - return None; - }; + let user_session = session.get()?; accounts.get_one(user_session.account_id) }; let get_balance = move || { @@ -79,8 +77,8 @@ pub fn Header() -> Element { let usdt_value = unscaled_value * KSM_PRICE; let usdt_value = usdt_value.to_string(); let unscaled_value = unscaled_value.to_string(); - let usdt_value = usdt_value.split(".").collect::>(); - let unscaled_value = unscaled_value.split(".").collect::>(); + let usdt_value = usdt_value.split('.').collect::>(); + let unscaled_value = unscaled_value.split('.').collect::>(); ksm_balance.set(( unscaled_value[0].to_string(), @@ -93,17 +91,16 @@ pub fn Header() -> Element { Ok::<(), String>(()) } - .unwrap_or_else(move |e: String| notification.handle_warning(&translate!(i18, "warnings.title"), &e)) + .unwrap_or_else(move |e: String| { + notification.handle_warning(&translate!(i18, "warnings.title"), &e) + }) }); }; let mut dropdown_value = use_signal::>(|| { - let account = get_account().and_then(|account| { - Some(DropdownItem { - key: account.address().clone(), - value: account.name(), - }) - }); - account + get_account().map(|account| DropdownItem { + key: account.address().clone(), + value: account.name(), + }) }); let mut items = vec![]; for account in accounts.get().into_iter() { @@ -117,10 +114,13 @@ pub fn Header() -> Element { let on_handle_account = use_coroutine(move |mut rx: UnboundedReceiver| async move { while let Some(event) = rx.next().await { let account_list = accounts.get(); - + let Some(account) = account_list.get(event as usize) else { - // return; - return notification.handle_warning(&translate!(i18, "warnings.title"), &translate!(i18, "warnings.middleware.not_account")); + // return; + return notification.handle_warning( + &translate!(i18, "warnings.title"), + &translate!(i18, "warnings.middleware.not_account"), + ); }; let Ok(serialized_session) = serde_json::to_string(&UserSession { @@ -142,11 +142,9 @@ pub fn Header() -> Element { accounts.set_account(Some(account.clone())); set_signer(account.address().clone()); - let account = get_account().and_then(|account| { - Some(DropdownItem { - key: account.address().clone(), - value: account.name(), - }) + let account = get_account().map(|account| DropdownItem { + key: account.address().clone(), + value: account.name(), }); dropdown_value.set(account); diff --git a/src/components/molecules/initiative/actions.rs b/src/components/molecules/initiative/actions.rs index dda7860..75883f3 100644 --- a/src/components/molecules/initiative/actions.rs +++ b/src/components/molecules/initiative/actions.rs @@ -54,9 +54,9 @@ pub fn InitiativeActions() -> Element { default: None, on_change: move |event: usize| { let options = initiative.get_actions_options(); - + let to_assign = &options[event]; - + initiative.update_action(index, initiative.to_action_option(to_assign.key.clone())); }, body: items.clone() @@ -110,10 +110,8 @@ pub fn InitiativeActions() -> Element { default: None, on_change: move |event: usize| { let options = initiative.get_actions_options(); - let to_assign = &options[event]; let action = initiative.to_action_option(to_assign.key.clone()); - initiative.push_action(action); }, body: items @@ -122,7 +120,7 @@ pub fn InitiativeActions() -> Element { variant: Variant::Round, size: ElementSize::Small, class: "button--action", - disabled: actions_lock.len() == 0, + disabled: actions_lock.is_empty(), body: rsx! { Icon { icon: AddPlus, height: 24, width: 24, fill: "var(--fill-00)" } }, diff --git a/src/components/molecules/initiative/settings.rs b/src/components/molecules/initiative/settings.rs index b52bdd5..69394f6 100644 --- a/src/components/molecules/initiative/settings.rs +++ b/src/components/molecules/initiative/settings.rs @@ -39,7 +39,7 @@ pub fn InitiativeSettings() -> Element { size: ElementSize::Small, default: None, on_change: move |event: usize| { - let dropdown_options = vec![ + let dropdown_options = [ DropdownItem { key: "Admin".to_string(), value: "Admin".to_string(), diff --git a/src/components/molecules/sidebar.rs b/src/components/molecules/sidebar.rs index 3914e94..f66a61b 100644 --- a/src/components/molecules/sidebar.rs +++ b/src/components/molecules/sidebar.rs @@ -103,7 +103,9 @@ pub fn Sidebar() -> Element { nav.push(vec![], "/"); } } - span { class: "sidebar__action-label__not-displayed", {translate!(i18, "sidebar.dashboard")} } + span { class: "sidebar__action-label__not-displayed", + {translate!(i18, "sidebar.dashboard")} + } } li { class: "sidebar__item", onclick: move |_| {}, IconButton { @@ -124,21 +126,22 @@ pub fn Sidebar() -> Element { nav.push(vec![], "/explore"); } } - span { class: "sidebar__action-label__not-displayed", {translate!(i18, "sidebar.explore")} } + span { class: "sidebar__action-label__not-displayed", + {translate!(i18, "sidebar.explore")} + } } hr { class: "sidebar__divider" } for community in communities.get_communities_by_filters(Some(()), None, None) { { let active_community = communities.get_community(); - let community_id = community.id.clone(); rsx!( li { class: "sidebar__item", class: if active_community.id == community.id { "sidebar__item--active" }, onclick: move |_| { - if let Ok(_) = communities.set_community(community_id) { - let path = format!("/dao/{}/initiatives", community_id); + if communities.set_community(community.id).is_ok() { + let path = format!("/dao/{}/initiatives", community.id); nav.push(vec![], &path); }; }, diff --git a/src/hooks/use_communities.rs b/src/hooks/use_communities.rs index 3b34cc3..5dc6789 100644 --- a/src/hooks/use_communities.rs +++ b/src/hooks/use_communities.rs @@ -36,7 +36,7 @@ pub fn use_communities() -> UseCommunitiesState { let cached_communities = get_cached_communities(); communities.set(cached_communities.clone()); - if cached_communities.len() == 0 { + if cached_communities.is_empty() { is_loading.set(true); } else { tooltip.hide(); @@ -44,7 +44,7 @@ pub fn use_communities() -> UseCommunitiesState { let public_address = session .get() - .map( + .and_then( |session| match sp_core::sr25519::Public::from_str(&session.address) { Ok(public_address) => Some(public_address.0), Err(_) => { @@ -54,8 +54,7 @@ pub fn use_communities() -> UseCommunitiesState { None } }, - ) - .flatten(); + ); let Ok(mut community_tracks) = get_communities().await else { log::warn!("error here by member"); @@ -142,7 +141,7 @@ impl UseCommunitiesState { filter_by_name: Option<&str>, filter_by_pagination: Option<(usize, usize)>, ) -> Vec { - if self.is_loading.read().clone() { + if *self.is_loading.read() { return vec![]; } @@ -162,7 +161,7 @@ impl UseCommunitiesState { match filter_by_name { Some(name) => communities .into_iter() - .filter(|community| community.name.to_lowercase().contains(&name)) + .filter(|community| community.name.to_lowercase().contains(name)) .collect::>(), None => { if let Some((from, to)) = filter_by_pagination { @@ -237,8 +236,7 @@ impl UseCommunitiesState { return Err(CommunitiesError::FailedUpdatingFavorites); }; - if let Err(_) = - ::set("communities", cached_communities) + if ::set("communities", cached_communities).is_err() { log::warn!("Failed to persist communities"); }; diff --git a/src/hooks/use_connect_wallet.rs b/src/hooks/use_connect_wallet.rs index 9b4f81a..80ceeea 100644 --- a/src/hooks/use_connect_wallet.rs +++ b/src/hooks/use_connect_wallet.rs @@ -22,7 +22,7 @@ pub async fn use_connect_wallet() -> Result<(), PjsError> { let mut pjs = use_context::>>(); let mut vault = pjs::PjsExtension::connect(APP_NAME).await.map_err(|_| { - if let Err(_) = session.persist_session_file("") { + if session.persist_session_file("").is_err() { log::warn!("Failed to persist session") }; diff --git a/src/hooks/use_deposit.rs b/src/hooks/use_deposit.rs index 23b0490..e5f829b 100644 --- a/src/hooks/use_deposit.rs +++ b/src/hooks/use_deposit.rs @@ -23,11 +23,11 @@ impl DepositForm { pub fn is_valid(&self) -> bool { let has_info = match &self.dest { // Check if is a valid address - DepositTo::Address(addrs) => addrs.len() > 0, + DepositTo::Address(addrs) => !addrs.is_empty(), DepositTo::Community(_) => true, }; - has_info && self.amount.len() > 0 + has_info && !self.amount.is_empty() } pub fn address(&self) -> String { @@ -45,7 +45,7 @@ impl DepositForm { let amount = (amount * 1_000_000_000_000.0) as u64; match &self.dest { DepositTo::Address(addrs) => { - let address = sp_core::sr25519::Public::from_str(&addrs) + let address = sp_core::sr25519::Public::from_str(addrs) .map_err(|_| DepositError::MalformedAddress)?; let hex_address = format!("0x{}", hex::encode(address.0)); Ok((hex_address, amount, false)) @@ -81,7 +81,7 @@ pub struct UseDepositInner { impl UseDepositState { pub fn get(&self) -> UseDepositInner { - self.inner.clone() + self.inner } pub fn get_deposit(&self) -> DepositForm { @@ -94,7 +94,7 @@ impl UseDepositState { } pub fn deposit_mut(&mut self) -> Signal { - self.inner.deposit.clone() + self.inner.deposit } pub fn is_form_complete(&self) -> bool { diff --git a/src/hooks/use_initiative.rs b/src/hooks/use_initiative.rs index 86e3f1f..b9cf0ef 100644 --- a/src/hooks/use_initiative.rs +++ b/src/hooks/use_initiative.rs @@ -321,13 +321,13 @@ pub struct UseInitiativeInner { } impl UseInitiativeState { pub fn is_loading(&self) -> bool { - self.inner.is_loading.read().clone() + *self.inner.is_loading.read() } pub fn set_loading(&mut self, loading: bool) { self.inner.is_loading.set(loading); } pub fn get(&self) -> UseInitiativeInner { - self.inner.clone() + self.inner } pub fn get_info(&self) -> InfoForm { self.inner.info.read().clone() @@ -337,7 +337,7 @@ impl UseInitiativeState { *inner = info; } pub fn info_mut(&mut self) -> Signal { - self.inner.info.clone() + self.inner.info } pub fn get_actions(&self) -> Vec { self.inner.actions.read().value.clone() @@ -610,10 +610,10 @@ impl UseInitiativeState { && self.check_treasury() && self.check_voting_open_gov() && self.check_community_transfer()) - && (self.filter_valid_address_add_members().len() > 0 - || self.filter_valid_treasury().len() > 0 - || self.filter_valid_voting_open_gov().len() > 0 - || self.filter_valid_community_transfer().len() > 0) + && (!self.filter_valid_address_add_members().is_empty() + || !self.filter_valid_treasury().is_empty() + || !self.filter_valid_voting_open_gov().is_empty() + || !self.filter_valid_community_transfer().is_empty()) } } @@ -622,7 +622,7 @@ fn convert_treasury_to_period( current_block: u32, current_date_millis: u64, ) -> KusamaTreasuryPeriod { - if treasury.date != "" { + if !treasury.date.is_empty() { let future_block = calculate_future_block(current_block, current_date_millis, &treasury.date); KusamaTreasuryPeriod { @@ -648,16 +648,17 @@ fn calculate_future_block( .expect("Invalid future date"); let future_date = DateTime::::from_naive_utc_and_offset(future, Utc); - let x = DateTime::from_timestamp( + let date = DateTime::from_timestamp( (current_date_millis / 1000).try_into().unwrap(), ((current_date_millis % 1000) * 1_000_000) as u32, ) .expect(""); - let x = NaiveDateTime::from_str(&x.date_naive().to_string()).expect("Invalid calculated date"); - let current_date = DateTime::from_naive_utc_and_offset(x, Utc); + let calculated_date = + NaiveDateTime::from_str(&date.date_naive().to_string()).expect("Invalid calculated date"); + let current_date = DateTime::from_naive_utc_and_offset(calculated_date, Utc); let elapsed_time_in_seconds = (future_date - current_date).num_seconds(); let blocks_to_add = elapsed_time_in_seconds / BLOCK_TIME_IN_SECONDS; - (current_block + blocks_to_add as u32).into() + current_block + blocks_to_add as u32 } diff --git a/src/hooks/use_location.rs b/src/hooks/use_location.rs index 73e36c9..74eae2b 100644 --- a/src/hooks/use_location.rs +++ b/src/hooks/use_location.rs @@ -19,7 +19,7 @@ pub fn use_location() -> UseLocationState { let mut error = use_signal(|| None); use_coroutine(move |_:UnboundedReceiver<()>| async move { - if let Some(stored_location) = LocalStorage::get("user_location").ok() { + if let Ok(stored_location) = LocalStorage::get("user_location") { location.set(Some(stored_location)); log::info!("{}", "Location loaded from storage"); } else { diff --git a/src/hooks/use_notification.rs b/src/hooks/use_notification.rs index 2fe0881..a068e01 100644 --- a/src/hooks/use_notification.rs +++ b/src/hooks/use_notification.rs @@ -41,7 +41,7 @@ impl UseNotificationState { self.inner.read().clone() } pub fn handle_notification(&mut self, item: NotificationItem) { - let mut inner = self.inner.clone(); + let mut inner = self.inner; *inner.write() = item; spawn_forever(async move { TimeoutFuture::new(3000).await; diff --git a/src/hooks/use_onboard.rs b/src/hooks/use_onboard.rs index ae21f7e..baa4768 100644 --- a/src/hooks/use_onboard.rs +++ b/src/hooks/use_onboard.rs @@ -55,7 +55,7 @@ pub struct UseOnboardInner { } impl UseOnboardState { pub fn get(&self) -> UseOnboardInner { - self.inner.clone() + self.inner } pub fn get_basics(&self) -> BasicsForm { self.inner.basics.read().clone() @@ -65,7 +65,7 @@ impl UseOnboardState { *inner = basics; } pub fn basics_mut(&mut self) -> Signal { - self.inner.basics.clone() + self.inner.basics } pub fn get_management(&self) -> ManagementForm { self.inner.management.read().clone() diff --git a/src/hooks/use_timestamp.rs b/src/hooks/use_timestamp.rs index 69fd4a0..c36aae4 100644 --- a/src/hooks/use_timestamp.rs +++ b/src/hooks/use_timestamp.rs @@ -13,7 +13,7 @@ pub struct UseTimestampState { } impl UseTimestampState { pub fn get(&self) -> TimestampValue { - self.timestamp.read().clone() + *self.timestamp.read() } pub fn set(&mut self, timestamp: TimestampValue) { let mut inner = self.timestamp.write(); diff --git a/src/hooks/use_tooltip.rs b/src/hooks/use_tooltip.rs index 99ce14b..9f36502 100644 --- a/src/hooks/use_tooltip.rs +++ b/src/hooks/use_tooltip.rs @@ -18,7 +18,7 @@ impl UseTooltipState { self.inner.read().clone() } pub fn handle_tooltip(&mut self, item: TooltipItem) { - let mut inner = self.inner.clone(); + let mut inner = self.inner; *inner.write() = item; } pub fn hide(&mut self) { diff --git a/src/hooks/use_withdraw.rs b/src/hooks/use_withdraw.rs index eab276b..fb75d01 100644 --- a/src/hooks/use_withdraw.rs +++ b/src/hooks/use_withdraw.rs @@ -26,7 +26,7 @@ pub struct UseWithdrawInner { impl UseWithdrawState { pub fn get(&self) -> UseWithdrawInner { - self.inner.clone() + self.inner } pub fn get_withdraw(&self) -> WithdrawForm { @@ -39,13 +39,13 @@ impl UseWithdrawState { } pub fn withdraw_mut(&mut self) -> Signal { - self.inner.withdraw.clone() + self.inner.withdraw } pub fn is_form_complete(&self) -> bool { let withdraw = self.inner.withdraw.read(); - withdraw.address.len() > 0 && withdraw.amount.len() > 0 + !withdraw.address.is_empty() && !withdraw.amount.is_empty() } pub fn default(&mut self) { diff --git a/src/locales/en-US.json b/src/locales/en-US.json index 4a291a4..ec25e16 100644 --- a/src/locales/en-US.json +++ b/src/locales/en-US.json @@ -509,7 +509,8 @@ "connection_failed": "Oops! The connection has failed 🔴 Contact us if the problem persists" }, "communities": { - "query_failed": "We're sorry! 😞 We couldn't load the information correctly. Please try again! 🤲" + "query_failed": "We're sorry! 😞 We couldn't load the information correctly. Please try again! 🤲", + "favorite_pick_failed": "Failed to update favorite" }, "initiatives": { "query_failed": "We're sorry! 😞 We couldn't load the information correctly. Please try again! 🤲" diff --git a/src/locales/es-ES.json b/src/locales/es-ES.json index 61df335..1f3aa06 100644 --- a/src/locales/es-ES.json +++ b/src/locales/es-ES.json @@ -510,7 +510,8 @@ "query_failed": "¡Lo sentimos! 😞 No hemos logrado cargar la información correctamente. ¡Inténtalo de nuevo! 🤲" }, "initiatives": { - "query_failed": "¡Lo sentimos! 😞 No hemos logrado cargar la información correctamente. ¡Inténtalo de nuevo! 🤲" + "query_failed": "¡Lo sentimos! 😞 No hemos logrado cargar la información correctamente. ¡Inténtalo de nuevo! 🤲", + "favorite_pick_failed": "No se pudo actualizar el favorito" }, "vote": { "persist_failed": "No se ha podido guardar el voto", diff --git a/src/pages/account.rs b/src/pages/account.rs index 19f62d9..1401b05 100644 --- a/src/pages/account.rs +++ b/src/pages/account.rs @@ -85,8 +85,8 @@ pub fn Account() -> Element { let usdt_value = usdt_value.to_string(); let unscaled_value = unscaled_value.to_string(); - let usdt_value = usdt_value.split(".").collect::>(); - let unscaled_value = unscaled_value.split(".").collect::>(); + let usdt_value = usdt_value.split('.').collect::>(); + let unscaled_value = unscaled_value.split('.').collect::>(); ksm_balance.set(( unscaled_value[0].to_string(), @@ -118,7 +118,7 @@ pub fn Account() -> Element { div { class: "account__options", Tab { text: translate!(i18, "account.tabs.wallet.tab"), - is_active: if *profile_value.read() == ProfileTabs::Wallet { true } else { false }, + is_active: matches!(*profile_value.read(), ProfileTabs::Wallet), on_click: move |_| { profile_value.set(ProfileTabs::Wallet); } diff --git a/src/pages/dashboard.rs b/src/pages/dashboard.rs index f7d9953..33b9a54 100644 --- a/src/pages/dashboard.rs +++ b/src/pages/dashboard.rs @@ -51,7 +51,7 @@ pub fn Dashboard() -> Element { let timestamp = use_timestamp(); let mut current_page = use_signal::(|| 1); - let mut search_word = use_signal::(|| String::new()); + let mut search_word = use_signal::(String::new); let tab_items = vec![TabItem { k: String::from("all"), value: translate!(i18, "dashboard.tabs.owned"), @@ -85,11 +85,7 @@ pub fn Dashboard() -> Element { div { class: "dashboard__head", section { class: "tabs", for item in tab_items.into_iter() { - Tab { - text: item.value, - is_active: if tab_value() == item.k { true } else { false }, - on_click: move |_| {} - } + Tab { text: item.value, is_active: tab_value() == item.k, on_click: move |_| {} } } } div { class: "head__actions", @@ -169,25 +165,25 @@ pub fn Dashboard() -> Element { Icon { icon: Star, height: 24, width: 24, fill: "var(--state-primary-active)" } } } else { - div { class: "card__favorite", - IconButton { - class: "button-favorite button--drop bg--transparent", - body: rsx!( - Icon { icon : Star, height : 24, width : 24, fill : if community.favorite { - "var(--state-primary-active)" } else { "var(--state-base-background)" } } - ), - on_click: move |_| { - if let Err(e) = communities.handle_favorite(community.id) { - let message = match e { - CommunitiesError::NotFound => "Failed to update favorite", - CommunitiesError::FailedUpdatingFavorites => "Failed to update favorite", - CommunitiesError::NotFoundFavorite => "Failed to update favorite", - }; - notification.handle_error(&message); - } + div { class: "card__favorite", + IconButton { + class: "button-favorite button--drop bg--transparent", + body: rsx!( + Icon { icon : Star, height : 24, width : 24, fill : if community.favorite { + "var(--state-primary-active)" } else { "var(--state-base-background)" } } + ), + on_click: move |_| { + if let Err(e) = communities.handle_favorite(community.id) { + let message = match e { + CommunitiesError::NotFound => translate!(i18, "errors.communities.favorite_pick_failed"), + CommunitiesError::FailedUpdatingFavorites => translate!(i18, "errors.communities.favorite_pick_failed"), + CommunitiesError::NotFoundFavorite => translate!(i18, "errors.communities.favorite_pick_failed"), + }; + notification.handle_error(&message); } } } + } } div { class: "card__metrics", span { class: "card__metric", diff --git a/src/pages/deposit.rs b/src/pages/deposit.rs index 8892149..a881606 100644 --- a/src/pages/deposit.rs +++ b/src/pages/deposit.rs @@ -61,7 +61,7 @@ pub fn Deposit() -> Element { let mut dropdown_value = use_signal::>(|| None); use_coroutine(move |_: UnboundedReceiver<()>| async move { - if let Err(_) = is_signer_ready(i18, accounts, notification)() { + if is_signer_ready(i18, accounts, notification)().is_err() { nav.push(vec![], "/login"); }; }); @@ -249,21 +249,21 @@ pub fn Deposit() -> Element { div { class: "account__options", Tab { text: translate!(i18, "deposit.tabs.accounts"), - is_active: if *tab_value.read() == DepositKreivoTabs::Accounts { true } else { false }, + is_active: matches!(*tab_value.read(), DepositKreivoTabs::Accounts), on_click: move |_| { tab_value.set(DepositKreivoTabs::Accounts); } } Tab { text: translate!(i18, "deposit.tabs.others"), - is_active: if *tab_value.read() == DepositKreivoTabs::Wallet { true } else { false }, + is_active: matches!(*tab_value.read(), DepositKreivoTabs::Wallet), on_click: move |_| { tab_value.set(DepositKreivoTabs::Wallet); } } Tab { text: translate!(i18, "deposit.tabs.communities"), - is_active: if *tab_value.read() == DepositKreivoTabs::Community { true } else { false }, + is_active: matches!(*tab_value.read(), DepositKreivoTabs::Community), on_click: move |_| { tab_value.set(DepositKreivoTabs::Community); } diff --git a/src/pages/explore.rs b/src/pages/explore.rs index fc758a5..b3d4646 100644 --- a/src/pages/explore.rs +++ b/src/pages/explore.rs @@ -35,7 +35,7 @@ pub fn Explore() -> Element { let timestamp = use_timestamp(); let mut current_page = use_signal::(|| 1); - let mut search_word = use_signal::(|| String::new()); + let mut search_word = use_signal::(String::new); let tab_items = vec![TabItem { k: String::from("all"), value: translate!(i18, "dashboard.tabs.all"), @@ -70,11 +70,7 @@ pub fn Explore() -> Element { div { class: "dashboard__head", section { class: "tabs", for item in tab_items.into_iter() { - Tab { - text: item.value, - is_active: if tab_value() == item.k { true } else { false }, - on_click: move |_| {} - } + Tab { text: item.value, is_active: tab_value() == item.k, on_click: move |_| {} } } } div { class: "head__actions", @@ -157,9 +153,9 @@ pub fn Explore() -> Element { on_click: move |_| { if let Err(e) = communities.handle_favorite(community.id) { let message = match e { - CommunitiesError::NotFound => "Failed to update favorite", - CommunitiesError::FailedUpdatingFavorites => "Failed to update favorite", - CommunitiesError::NotFoundFavorite => "Failed to update favorite", + CommunitiesError::NotFound => translate!(i18, "errors.communities.favorite_pick_failed"), + CommunitiesError::FailedUpdatingFavorites => translate!(i18, "errors.communities.favorite_pick_failed"), + CommunitiesError::NotFoundFavorite => translate!(i18, "errors.communities.favorite_pick_failed"), }; notification.handle_error(&message); } diff --git a/src/pages/initiative.rs b/src/pages/initiative.rs index 98a249a..757a4fa 100644 --- a/src/pages/initiative.rs +++ b/src/pages/initiative.rs @@ -9,16 +9,13 @@ use crate::{ hooks::{ use_accounts::use_accounts, use_initiative::{ - use_initiative, ActionItem, InitiativeData, InitiativeInfoContent, - InitiativeInitContent, KusamaTreasury, KusamaTreasuryPeriod, TransferItem, - VotingOpenGov, + use_initiative, InitiativeData, InitiativeInfoContent, InitiativeInitContent, }, use_notification::use_notification, use_our_navigator::use_our_navigator, use_session::use_session, use_spaces_client::use_spaces_client, use_tooltip::{use_tooltip, TooltipItem}, - }, middlewares::is_signer_ready::is_signer_ready, pages::onboarding::convert_to_jsvalue, @@ -71,7 +68,7 @@ pub fn Initiative(id: u16) -> Element { initiative.default(); }); use_coroutine(move |_: UnboundedReceiver<()>| async move { - if let Err(_) = is_signer_ready(i18, accounts, notification)() { + if is_signer_ready(i18, accounts, notification)().is_err() { nav.push(vec![], &format!("/dao/{}/initiatives", id)); }; }); @@ -216,7 +213,7 @@ pub fn Initiative(id: u16) -> Element { class: "", text: translate!(i18, "initiative.cta.continue"), size: ElementSize::Small, - disabled: !initiative.check() || initiative.get_info().name.len() == 0, + disabled: !initiative.check() || initiative.get_info().name.is_empty(), on_click: move |_| { spawn( async move { @@ -270,7 +267,8 @@ pub fn Initiative(id: u16) -> Element { log::info!("{} {}", current_block, now_kusama); let add_members_action = initiative.filter_valid_address_add_members(); log::info!("add_members_action: {:?}", add_members_action); - let treasury_action = initiative.convert_treasury_to_period(current_block, now_kusama); + let treasury_action = initiative + .convert_treasury_to_period(current_block, now_kusama); log::info!("treasury {:?}", treasury_action); let votiong_open_gov_action = initiative.filter_valid_voting_open_gov(); let votiong_open_gov_action = votiong_open_gov_action @@ -279,31 +277,7 @@ pub fn Initiative(id: u16) -> Element { .collect::>(); log::info!("votiong_open_gov_action {:?}", votiong_open_gov_action); let community_transfer_action = initiative - .get_actions() - .into_iter() - .filter_map(|action| { - match action { - ActionItem::CommunityTransfer(community_transfer_action) => { - Some( - community_transfer_action - .transfers - .clone() - .into_iter() - .filter_map(|transfer| { - if transfer.value > 0 { Some(transfer) } else { None } - }) - .collect::>(), - ) - } - _ => None, - } - }) - .collect::>>(); - let community_transfer_action = community_transfer_action - .into_iter() - .flat_map(|v| v.into_iter()) - .collect::>(); - let community_transfer_action = initiative.filter_valid_community_transfer(); + .filter_valid_community_transfer(); log::info!("community_transfer_action {:?}", community_transfer_action); let votiong_open_gov_action = convert_to_jsvalue( &votiong_open_gov_action, diff --git a/src/pages/initiatives.rs b/src/pages/initiatives.rs index 9babd24..83349c8 100644 --- a/src/pages/initiatives.rs +++ b/src/pages/initiatives.rs @@ -1,8 +1,8 @@ use crate::{ components::{ atoms::{ - dropdown::ElementSize, AddPlus, ArrowRight, Badge, CircleCheck, - Icon, IconButton, SearchInput, StopSign, Tab, CardSkeleton, + dropdown::ElementSize, AddPlus, ArrowRight, Badge, CardSkeleton, CircleCheck, Icon, + IconButton, SearchInput, StopSign, Tab, }, molecules::{paginator::PaginatorValue, tabs::TabItem, Paginator}, }, @@ -40,24 +40,21 @@ pub fn Initiatives(id: u16) -> Element { let mut initiative_wrapper = consume_context::>>(); let mut current_page = use_signal::(|| 1); - let mut search_word = use_signal::(|| String::new()); + let mut search_word = use_signal::(String::new); let tab_items = vec![TabItem { k: String::from("all"), value: translate!(i18, "dao.tabs.all"), }]; let tab_value = use_signal::(|| String::from("all")); - let initiatives_ids = use_signal::>(|| vec![]); - let mut initiatives = use_signal::>(|| vec![]); - let mut filtered_initiatives = use_signal::>(|| vec![]); + let initiatives_ids = use_signal::>(Vec::new); + let mut initiatives = use_signal::>(Vec::new); + let mut filtered_initiatives = use_signal::>(Vec::new); use_effect(use_reactive( (&communities.get_communities().len(),), move |(len,)| { - if len > 0 { - if let Err(_) = communities.set_community(id) { - let path = format!("/"); - nav.push(vec![], &path); - }; + if len > 0 && communities.set_community(id).is_err() { + nav.push(vec![], "/"); } }, )); @@ -149,11 +146,7 @@ pub fn Initiatives(id: u16) -> Element { div { class: "dashboard__head", section { class: "tabs", for item in tab_items.into_iter() { - Tab { - text: item.value, - is_active: if tab_value() == item.k { true } else { false }, - on_click: move |_| {} - } + Tab { text: item.value, is_active: tab_value() == item.k, on_click: move |_| {} } } } div { class: "head__actions", @@ -256,7 +249,6 @@ pub fn Initiatives(id: u16) -> Element { } } } - } }, section { class: "card card--reverse", diff --git a/src/pages/onboarding.rs b/src/pages/onboarding.rs index 1a4da6f..4d12956 100644 --- a/src/pages/onboarding.rs +++ b/src/pages/onboarding.rs @@ -78,7 +78,7 @@ pub fn Onboarding() -> Element { let to_pay = consume_context::>(); - let mut id_number = use_signal::(|| String::new()); + let mut id_number = use_signal::(String::new); let mut onboarding_step = use_signal::(|| OnboardingStep::Basics); let mut handle_required_inputs = use_signal::(|| false); @@ -91,7 +91,7 @@ pub fn Onboarding() -> Element { nav.push(vec![], "/"); }; - if let Err(_) = is_chain_available(i18, timestamp, notification)() { + if is_chain_available(i18, timestamp, notification)().is_err() { nav.push(vec![], "/"); }; }); @@ -100,20 +100,20 @@ pub fn Onboarding() -> Element { div { class: "row", div { class: "onboarding__form", div { class: "form__wrapper", - IconButton { - on_click: move |_| { - nav.push(vec![], "/"); - }, - body: rsx! { - Icon { - icon: VirtoLogo, - height: 64, - width: 64, - stroke_width: 1, - fill: "var(--color-lavanda-400)" + IconButton { + on_click: move |_| { + nav.push(vec![], "/"); + }, + body: rsx! { + Icon { + icon: VirtoLogo, + height: 64, + width: 64, + stroke_width: 1, + fill: "var(--color-lavanda-400)" + } } } - } div { class: "progress progress--steps", button { class: "step", diff --git a/src/pages/vote.rs b/src/pages/vote.rs index 4feba66..eb70cc8 100644 --- a/src/pages/vote.rs +++ b/src/pages/vote.rs @@ -47,8 +47,8 @@ pub fn Vote(id: u16, initiativeid: u16) -> Element { let nav = use_our_navigator(); let mut notification = use_notification(); let mut tooltip = use_tooltip(); - let mut votes_statistics = use_signal(|| VoteDigest::default()); - let mut content = use_signal(|| String::new()); + let mut votes_statistics = use_signal(VoteDigest::default); + let mut content = use_signal(String::new); let mut can_vote = use_signal(|| false); let mut show_requests = use_signal(|| false); let mut show_vote = use_signal(|| true); @@ -64,7 +64,7 @@ pub fn Vote(id: u16, initiativeid: u16) -> Element { let mut html_buf = String::new(); pulldown_cmark::html::push_html(&mut html_buf, parser); let on_handle_vote = use_coroutine(move |mut rx: UnboundedReceiver<()>| async move { - while let Some(_) = rx.next().await { + while (rx.next().await).is_some() { let Some(account) = session.get() else { log::info!("error here by account"); notification @@ -87,11 +87,7 @@ pub fn Vote(id: u16, initiativeid: u16) -> Element { // get community members let response_item = item(id).await; - let item_details = match response_item { - Ok(items) => items, - Err(_) => 0u16, - }; - members.set(item_details); + members.set(response_item.unwrap_or(0)); let Ok(block) = number().await else { log::warn!("Failed to get last block kusama"); continue; @@ -122,13 +118,13 @@ pub fn Vote(id: u16, initiativeid: u16) -> Element { ); } let threshold = get_approval_threshold( - &*track_info.read(), + &track_info.read(), &initiative_wrapper.unwrap().ongoing.deciding, current_block(), ); approval_threshold.set(threshold); let threshold = get_participation_threshold( - &*track_info.read(), + &track_info.read(), &initiative_wrapper.unwrap().ongoing.deciding, current_block(), ); diff --git a/src/pages/withdraw.rs b/src/pages/withdraw.rs index 11d0b6d..4844e57 100644 --- a/src/pages/withdraw.rs +++ b/src/pages/withdraw.rs @@ -60,9 +60,9 @@ pub fn Withdraw() -> Element { let mut dropdown_value = use_signal::>(|| None); use_coroutine(move |_: UnboundedReceiver<()>| async move { - if let Err(_) = is_signer_ready(i18, accounts, notification)() { + if is_signer_ready(i18, accounts, notification)().is_err() { nav.push(vec![], "/login"); - }; + } }); let mut items = vec![]; @@ -212,14 +212,14 @@ pub fn Withdraw() -> Element { div { class: "account__options", Tab { text: "My accounts", - is_active: if *tab_value.read() == WithdrawKreivoTabs::Accounts { true } else { false }, + is_active: matches!(*tab_value.read(), WithdrawKreivoTabs::Accounts), on_click: move |_| { tab_value.set(WithdrawKreivoTabs::Accounts); } } Tab { text: "Others", - is_active: if *tab_value.read() == WithdrawKreivoTabs::Wallet { true } else { false }, + is_active: matches!(*tab_value.read(), WithdrawKreivoTabs::Wallet), on_click: move |_| { tab_value.set(WithdrawKreivoTabs::Wallet); } diff --git a/src/services/kreivo/communities.rs b/src/services/kreivo/communities.rs index e37020e..1a8582c 100644 --- a/src/services/kreivo/communities.rs +++ b/src/services/kreivo/communities.rs @@ -12,16 +12,15 @@ pub enum ChainStateError { FailedDecode, } pub async fn is_admin(address: &[u8]) -> Result { - let query = format!("wss://kreivo.io/communities/communityIdFor"); - let response = sube!(& query).await.map_err(|_| ChainStateError::FailedQuery)?; + let response = sube!("wss://kreivo.io/communities/communityIdFor").await.map_err(|_| ChainStateError::FailedQuery)?; let Response::ValueSet(value) = response else { return Err(ChainStateError::InternalError); }; for d in value.iter() { - let Some(value) = d.0.get(0) else { + let Some(value) = d.0.first() else { continue; }; - let Ok(value) = serde_json::to_value(&value) else { + let Ok(value) = serde_json::to_value(value) else { continue; }; let Some(system) = value.get("system") else { @@ -30,7 +29,7 @@ pub async fn is_admin(address: &[u8]) -> Result { let Some(signed) = system.get("Signed") else { continue; }; - let Ok(value) = serde_json::to_value(&signed) else { + let Ok(value) = serde_json::to_value(signed) else { continue; }; let Ok(account_info) = serde_json::from_value::>(value) else { diff --git a/src/services/kreivo/community_memberships.rs b/src/services/kreivo/community_memberships.rs index dc95841..fe23bd4 100644 --- a/src/services/kreivo/community_memberships.rs +++ b/src/services/kreivo/community_memberships.rs @@ -1,10 +1,8 @@ +use super::community_track::{tracks, tracksIds}; +use crate::{pages::dashboard::Community, services::kreivo::community_track::ChainStateError}; use codec::Decode; use serde::Deserialize; use sube::{sube, Response}; -use crate::{ - pages::dashboard::Community, services::kreivo::community_track::ChainStateError, -}; -use super::community_track::{tracks, tracksIds}; #[derive(Decode, Debug, Deserialize)] pub struct CollectionDetails { pub items: u16, @@ -17,7 +15,9 @@ pub async fn collection(collection: u16) -> Result Result Result { let query = format!("wss://kreivo.io/communityMemberships/item/{}", item); - let response = sube!(& query).await.map_err(|_| ChainStateError::FailedQuery)?; + let response = sube!(&query) + .await + .map_err(|_| ChainStateError::FailedQuery)?; let Response::ValueSet(value) = response else { return Err(ChainStateError::InternalError); }; Ok(value.len() as u16) } -pub async fn get_membership_id( - address: &str, - community_id: u16, -) -> Result { +pub async fn get_membership_id(address: &str, community_id: u16) -> Result { let query = format!( "wss://kreivo.io/communityMemberships/account/{}/{}", - address, - community_id, + address, community_id, ); - let response = sube!(& query).await.map_err(|_| ChainStateError::FailedQuery)?; + let response = sube!(&query) + .await + .map_err(|_| ChainStateError::FailedQuery)?; let Response::ValueSet(ref value) = response else { return Err(ChainStateError::InternalError); }; - let Some(value) = value.get(0) else { + let Some(value) = value.first() else { return Err(ChainStateError::InternalError); }; let value = &value.0; let Some(value) = value.get(2) else { return Err(ChainStateError::InternalError); }; - let Ok(value) = serde_json::to_value(&value) else { + let Ok(value) = serde_json::to_value(value) else { return Err(ChainStateError::InternalError); }; - let membership_id = serde_json::from_value::(value) - .map_err(|_| ChainStateError::FailedDecode)?; + let membership_id = + serde_json::from_value::(value).map_err(|_| ChainStateError::FailedDecode)?; Ok(membership_id) } pub async fn get_owned_memberships(address: &str) -> Result { let query = format!("wss://kreivo.io/communityMemberships/account/{}", address); - let response = sube!(& query).await.map_err(|_| ChainStateError::FailedQuery)?; + let response = sube!(&query) + .await + .map_err(|_| ChainStateError::FailedQuery)?; let Response::ValueSet(ref value) = response else { return Err(ChainStateError::InternalError); }; @@ -74,12 +76,10 @@ pub async fn get_owned_memberships(address: &str) -> Result Result, ChainStateError> { let mut communities = vec![]; - let community_trackIds = tracksIds() - .await - .map_err(|e| { - log::warn!("error: {:?}", e); - ChainStateError::FailedQuery - })?; + let community_trackIds = tracksIds().await.map_err(|e| { + log::warn!("error: {:?}", e); + ChainStateError::FailedQuery + })?; for community in community_trackIds.communities.iter() { let response_track = tracks(*community).await; let response_collection = collection(*community).await; @@ -106,11 +106,6 @@ pub async fn get_communities() -> Result, ChainStateError> { let filtered_name: &[u8] = &filtered_name; - let item_details = match response_item { - Ok(items) => items, - Err(_) => 0u16, - }; - let community = Community { id: *community, icon: None, @@ -118,7 +113,7 @@ pub async fn get_communities() -> Result, ChainStateError> { description: String::from(""), tags: vec![], memberships: collection_items, - members: item_details, + members: response_item.unwrap_or(0), favorite: false, has_membership: false, }; @@ -148,7 +143,7 @@ pub async fn is_community_member_by_address( return Ok(false); }; - value.len() > 0 + !value.is_empty() }; Ok(is_member) diff --git a/src/services/kreivo/community_referenda.rs b/src/services/kreivo/community_referenda.rs index fd7ad5a..ffcc40c 100644 --- a/src/services/kreivo/community_referenda.rs +++ b/src/services/kreivo/community_referenda.rs @@ -13,7 +13,7 @@ pub async fn track_queue(item: u16) -> Result, ChainStateError> { let Response::Value(ref value) = response else { return Err(ChainStateError::InternalError); }; - let Ok(value) = serde_json::to_value(&value) else { + let Ok(value) = serde_json::to_value(value) else { return Err(ChainStateError::InternalError); }; let Value::Array(track_infos) = value else { @@ -26,12 +26,11 @@ pub async fn track_queue(item: u16) -> Result, ChainStateError> { Ok(track_infos) } pub async fn referendum_count() -> Result { - let query = format!("wss://kreivo.io/communityReferenda/referendumCount"); - let response = sube!(& query).await.map_err(|_| ChainStateError::FailedQuery)?; + let response = sube!("wss://kreivo.io/communityReferenda/referendumCount").await.map_err(|_| ChainStateError::FailedQuery)?; let Response::Value(ref value) = response else { return Err(ChainStateError::InternalError); }; - let Ok(value) = serde_json::to_value(&value) else { + let Ok(value) = serde_json::to_value(value) else { return Err(ChainStateError::InternalError); }; let count = serde_json::from_value::(value) @@ -93,7 +92,7 @@ pub async fn referendum_info_for(id: u16) -> Result(value) @@ -106,7 +105,7 @@ pub async fn metadata_of(id: u16) -> Result, ChainStateError> { let Response::Value(ref value) = response else { return Err(ChainStateError::InternalError); }; - let Ok(value) = serde_json::to_value(&value) else { + let Ok(value) = serde_json::to_value(value) else { return Err(ChainStateError::InternalError); }; let preimage_hash = serde_json::from_value::>(value) diff --git a/src/services/kreivo/community_track.rs b/src/services/kreivo/community_track.rs index 7421978..b9b03f7 100644 --- a/src/services/kreivo/community_track.rs +++ b/src/services/kreivo/community_track.rs @@ -12,8 +12,7 @@ pub enum ChainStateError { FailedDecode, } pub async fn tracksIds() -> Result { - let query = format!("wss://kreivo.io/communityTracks/tracksIds"); - let response = sube!(& query) + let response = sube!("wss://kreivo.io/communityTracks/tracksIds") .await .map_err(|e| { log::warn!("{:?}", e); diff --git a/src/services/kreivo/preimage.rs b/src/services/kreivo/preimage.rs index df1a742..e162016 100644 --- a/src/services/kreivo/preimage.rs +++ b/src/services/kreivo/preimage.rs @@ -6,7 +6,7 @@ pub async fn preimage_for(hash: &str, len: u32) -> Result>(value) @@ -21,7 +21,7 @@ pub async fn request_status_for(hash: &str) -> Result { let Response::Value(ref value) = response else { return Err(ChainStateError::InternalError); }; - let Ok(value) = serde_json::to_value(&value) else { + let Ok(value) = serde_json::to_value(value) else { return Err(ChainStateError::InternalError); }; let response = value.get("Unrequested").ok_or(ChainStateError::FailedDecode)?; diff --git a/src/services/kreivo/system.rs b/src/services/kreivo/system.rs index 7512662..aff365c 100644 --- a/src/services/kreivo/system.rs +++ b/src/services/kreivo/system.rs @@ -1,8 +1,7 @@ use sube::{sube, Response}; use crate::services::kreivo::communities::ChainStateError; pub async fn number() -> Result { - let query = format!("wss://kreivo.io/system/number"); - let response = sube!(& query).await.map_err(|_| ChainStateError::FailedQuery)?; + let response = sube!("wss://kreivo.io/system/number").await.map_err(|_| ChainStateError::FailedQuery)?; let Response::Value(value) = response else { return Err(ChainStateError::InternalError); }; diff --git a/src/services/kreivo/timestamp.rs b/src/services/kreivo/timestamp.rs index 6888fc1..ceb8144 100644 --- a/src/services/kreivo/timestamp.rs +++ b/src/services/kreivo/timestamp.rs @@ -1,8 +1,7 @@ use sube::{sube, Response}; use super::community_track::ChainStateError; pub async fn now() -> Result { - let query = format!("wss://kreivo.io/timestamp/now"); - let response = sube!(& query).await.map_err(|_| ChainStateError::FailedQuery)?; + let response = sube!("wss://kreivo.io/timestamp/now").await.map_err(|_| ChainStateError::FailedQuery)?; let Response::Value(value) = response else { return Err(ChainStateError::InternalError); }; diff --git a/src/services/kusama/system.rs b/src/services/kusama/system.rs index 17acc44..5322618 100644 --- a/src/services/kusama/system.rs +++ b/src/services/kusama/system.rs @@ -1,8 +1,7 @@ use sube::{sube, Response}; use crate::services::kreivo::communities::ChainStateError; pub async fn number() -> Result { - let query = format!("wss://kusama-rpc.dwellir.com/system/number"); - let response = sube!(& query).await.map_err(|_| ChainStateError::FailedQuery)?; + let response = sube!("wss://kusama-rpc.dwellir.com/system/number").await.map_err(|_| ChainStateError::FailedQuery)?; let Response::Value(value) = response else { return Err(ChainStateError::InternalError); }; diff --git a/src/services/market/types.rs b/src/services/market/types.rs index a42ad65..95f7a11 100644 --- a/src/services/market/types.rs +++ b/src/services/market/types.rs @@ -13,7 +13,7 @@ pub enum Error { impl Response { pub fn get_price(&self) -> f64 { - let data = self.data.get(self.data.len() - 1).expect("Should get data"); + let data = self.data.last().expect("Should get data"); let price = *data.get(1).expect("Should get price"); price }