From d507d6b00201c09147351c7b430e4e2d3141bcd0 Mon Sep 17 00:00:00 2001 From: gianfra-t <96739519+gianfra-t@users.noreply.github.com> Date: Tue, 3 Sep 2024 08:34:53 +0300 Subject: [PATCH] Solve mandatory flow control (#550) * first iteration to solve mandatory flow control * cleanup * fix auth flag * remove extra check_to_send_more * auth response could work with flow control w/o bytes also * remove unused import for test * re-introduce interfaces, remove test * run cargo fmt * cargo fmt with nightly * Revert "cargo fmt with nightly" This reverts commit 08ab6fc06ab14aad712bdc5878dc755f5e3ce41b. * run cargo fmt with nightly 2024-02-09 * refactor auth flag, fix incorrect data len calculation * run cargo fmt * rename send_more method of flow controller * readability changes --- clients/runtime/src/cli.rs | 5 +- clients/runtime/src/error.rs | 10 +- clients/runtime/src/rpc.rs | 19 ++-- clients/runtime/src/types.rs | 20 ++-- .../src/connection/connector/connector.rs | 42 +++----- .../connection/connector/message_handler.rs | 38 ++++---- .../connection/connector/message_reader.rs | 5 +- .../connection/connector/message_sender.rs | 26 ++--- .../src/connection/flow_controller.rs | 95 +++++++++++++++---- .../src/connection/handshake.rs | 11 ++- clients/vault/src/issue.rs | 5 +- clients/vault/src/metrics.rs | 18 ++-- clients/vault/src/oracle/agent.rs | 5 +- .../src/oracle/collector/proof_builder.rs | 12 +-- clients/vault/src/requests/structs.rs | 20 ++-- clients/vault/src/system.rs | 5 +- clients/vault/tests/helper/helper.rs | 5 +- clients/wallet/src/error.rs | 10 +- clients/wallet/src/operations.rs | 8 +- clients/wallet/src/resubmissions.rs | 20 ++-- pallets/currency/src/lib.rs | 6 +- pallets/issue/src/lib.rs | 4 +- pallets/issue/src/tests.rs | 82 ++++++++-------- pallets/oracle/src/dia.rs | 8 +- pallets/oracle/src/lib.rs | 6 +- pallets/oracle/src/oracle_mock.rs | 15 ++- .../src/testing_utils/mock_convertors.rs | 15 ++- pallets/oracle/src/tests.rs | 10 +- pallets/redeem/src/lib.rs | 5 +- pallets/replace/src/lib.rs | 4 +- pallets/reward-distribution/src/lib.rs | 4 +- pallets/reward-distribution/src/tests.rs | 28 +++--- pallets/security/src/lib.rs | 4 +- pallets/stellar-relay/src/lib.rs | 4 +- pallets/stellar-relay/src/validation.rs | 10 +- pallets/vault-registry/src/lib.rs | 14 ++- pallets/vault-registry/src/tests.rs | 52 +++++----- pallets/vault-registry/src/types.rs | 21 ++-- primitives/src/lib.rs | 46 ++++----- testchain/node/src/command.rs | 10 +- 40 files changed, 365 insertions(+), 362 deletions(-) diff --git a/clients/runtime/src/cli.rs b/clients/runtime/src/cli.rs index 68000481e..18f92135a 100644 --- a/clients/runtime/src/cli.rs +++ b/clients/runtime/src/cli.rs @@ -33,9 +33,8 @@ impl ProviderUserOpts { // load parachain credentials let (pair, user_name) = match (self.keyfile.as_ref(), self.keyname.as_ref(), &self.keyring) { - (Some(file_path), Some(keyname), None) => { - (get_credentials_from_file(file_path, keyname)?, keyname.to_string()) - }, + (Some(file_path), Some(keyname), None) => + (get_credentials_from_file(file_path, keyname)?, keyname.to_string()), (None, None, Some(keyring)) => { let pair = Pair::from_string(keyring.to_seed().as_str(), None) .map_err(|_| Error::KeyringAccountParsingError)?; diff --git a/clients/runtime/src/error.rs b/clients/runtime/src/error.rs index bd9747f87..e4e6851d8 100644 --- a/clients/runtime/src/error.rs +++ b/clients/runtime/src/error.rs @@ -160,7 +160,7 @@ impl Error { pub fn is_rpc_disconnect_error(&self) -> bool { match self { - Error::SubxtRuntimeError(SubxtError::Rpc(RpcError::ClientError(e))) => { + Error::SubxtRuntimeError(SubxtError::Rpc(RpcError::ClientError(e))) => match e.downcast_ref::() { Some(e) => matches!(e, JsonRpseeError::RestartNeeded(_)), None => { @@ -169,8 +169,7 @@ impl Error { ); false }, - } - }, + }, Error::SubxtRuntimeError(SubxtError::Rpc(RpcError::SubscriptionDropped)) => true, _ => false, } @@ -204,7 +203,7 @@ impl Error { pub fn is_timeout_error(&self) -> bool { match self { - Error::SubxtRuntimeError(SubxtError::Rpc(RpcError::ClientError(e))) => { + Error::SubxtRuntimeError(SubxtError::Rpc(RpcError::ClientError(e))) => match e.downcast_ref::() { Some(e) => matches!(e, JsonRpseeError::RequestTimeout), None => { @@ -213,8 +212,7 @@ impl Error { ); false }, - } - }, + }, _ => false, } } diff --git a/clients/runtime/src/rpc.rs b/clients/runtime/src/rpc.rs index 9cd7d3c28..30885154f 100644 --- a/clients/runtime/src/rpc.rs +++ b/clients/runtime/src/rpc.rs @@ -242,12 +242,10 @@ impl SpacewalkParachain { match result.map_err(Into::::into) { Ok(ok) => Ok(ok), Err(err) => match err.is_invalid_transaction() { - Some(Recoverability::Recoverable(data)) => { - Err(RetryPolicy::Skip(Error::InvalidTransaction(data))) - }, - Some(Recoverability::Unrecoverable(data)) => { - Err(RetryPolicy::Throw(Error::InvalidTransaction(data))) - }, + Some(Recoverability::Recoverable(data)) => + Err(RetryPolicy::Skip(Error::InvalidTransaction(data))), + Some(Recoverability::Unrecoverable(data)) => + Err(RetryPolicy::Throw(Error::InvalidTransaction(data))), None => { // Handle other errors if err.is_pool_too_low_priority() { @@ -572,9 +570,8 @@ impl VaultRegistryPallet for SpacewalkParachain { let query = metadata::storage().vault_registry().vaults(&vault_id.clone()); match self.query_finalized(query).await? { - Some(SpacewalkVault { status: VaultStatus::Liquidated, .. }) => { - Err(Error::VaultLiquidated) - }, + Some(SpacewalkVault { status: VaultStatus::Liquidated, .. }) => + Err(Error::VaultLiquidated), Some(vault) if &vault.id == vault_id => Ok(vault), _ => Err(Error::VaultNotFound), } @@ -1082,8 +1079,8 @@ impl IssuePallet for SpacewalkParachain { while let Ok((issue_id, request)) = iter.next().await.ok_or(Error::RequestIssueIDNotFound)? { - if request.status == IssueRequestStatus::Pending - && request.opentime + issue_period > current_height + if request.status == IssueRequestStatus::Pending && + request.opentime + issue_period > current_height { let key_hash = issue_id.as_slice(); // last bytes are the raw key diff --git a/clients/runtime/src/types.rs b/clients/runtime/src/types.rs index 4e5cfd6fe..966609cb9 100644 --- a/clients/runtime/src/types.rs +++ b/clients/runtime/src/types.rs @@ -155,12 +155,11 @@ pub mod currency_id { ) .replace('\"', "")), }, - CurrencyId::ZenlinkLPToken(token1_id, token1_type, token2_id, token2_type) => { + CurrencyId::ZenlinkLPToken(token1_id, token1_type, token2_id, token2_type) => Ok(format!( "ZenlinkLPToken({},{},{},{})", token1_id, token1_type, token2_id, token2_type - )) - }, + )), CurrencyId::Token(token_id) => Ok(format!("Token({})", token_id)), } } @@ -340,19 +339,16 @@ mod dispatch_error { RichDispatchError::Other(_) => DispatchError::Other, RichDispatchError::CannotLookup => DispatchError::CannotLookup, RichDispatchError::BadOrigin => DispatchError::BadOrigin, - RichDispatchError::Module(RichModuleError { index, error, .. }) => { - DispatchError::Module(ModuleError { index, error }) - }, + RichDispatchError::Module(RichModuleError { index, error, .. }) => + DispatchError::Module(ModuleError { index, error }), RichDispatchError::ConsumerRemaining => DispatchError::ConsumerRemaining, RichDispatchError::NoProviders => DispatchError::NoProviders, RichDispatchError::TooManyConsumers => DispatchError::TooManyConsumers, RichDispatchError::Token(token_error) => DispatchError::Token(token_error.into()), - RichDispatchError::Arithmetic(arithmetic_error) => { - DispatchError::Arithmetic(arithmetic_error.into()) - }, - RichDispatchError::Transactional(transactional_error) => { - DispatchError::Transactional(transactional_error.into()) - }, + RichDispatchError::Arithmetic(arithmetic_error) => + DispatchError::Arithmetic(arithmetic_error.into()), + RichDispatchError::Transactional(transactional_error) => + DispatchError::Transactional(transactional_error.into()), RichDispatchError::Exhausted => DispatchError::Exhausted, sp_runtime::DispatchError::Corruption => DispatchError::Corruption, sp_runtime::DispatchError::Unavailable => DispatchError::Unavailable, diff --git a/clients/stellar-relay-lib/src/connection/connector/connector.rs b/clients/stellar-relay-lib/src/connection/connector/connector.rs index e84d67de1..b9392fc54 100644 --- a/clients/stellar-relay-lib/src/connection/connector/connector.rs +++ b/clients/stellar-relay-lib/src/connection/connector/connector.rs @@ -4,9 +4,11 @@ use std::{ net::Shutdown, }; use substrate_stellar_sdk::{ - types::{AuthenticatedMessageV0, Curve25519Public, HmacSha256Mac, MessageType}, + types::{AuthenticatedMessageV0, Curve25519Public, HmacSha256Mac}, XdrCodec, }; + +use substrate_stellar_sdk::types::StellarMessage; use tracing::{error, trace}; use crate::{ @@ -34,7 +36,7 @@ pub struct Connector { receive_scp_messages: bool, handshake_state: HandshakeState, - flow_controller: FlowController, + pub(crate) flow_controller: FlowController, /// for writing/reading xdr messages to/from Stellar Node. pub(crate) tcp_stream: TcpStream, @@ -227,20 +229,18 @@ impl Connector { pub fn got_hello(&mut self) { self.handshake_state = HandshakeState::GotHello; } - - pub fn handshake_completed(&mut self) { - self.handshake_state = HandshakeState::Completed; - } - - pub fn inner_check_to_send_more(&mut self, msg_type: MessageType) -> bool { - self.flow_controller.send_more(msg_type) - } - pub fn enable_flow_controller( + pub fn maybe_start_flow_control_bytes( &mut self, local_overlay_version: u32, remote_overlay_version: u32, - ) { - self.flow_controller.enable(local_overlay_version, remote_overlay_version) + ) -> StellarMessage { + return self + .flow_controller + .start(local_overlay_version, remote_overlay_version); + } + + pub fn handshake_completed(&mut self) { + self.handshake_state = HandshakeState::Completed; } } @@ -249,12 +249,6 @@ mod test { use crate::{connection::hmac::HMacKeys, node::RemoteInfo, StellarOverlayConfig}; use serial_test::serial; - use substrate_stellar_sdk::{ - compound_types::LimitedString, - types::{Hello, MessageType}, - PublicKey, - }; - use crate::{ connection::{ authentication::{create_auth_cert, ConnectionAuth}, @@ -264,6 +258,7 @@ mod test { node::NodeInfo, ConnectionInfo, }; + use substrate_stellar_sdk::{compound_types::LimitedString, types::Hello, PublicKey}; use wallet::keys::get_source_secret_key_from_env; @@ -424,13 +419,4 @@ mod test { connector.handshake_completed(); assert!(connector.is_handshake_created()); } - - #[tokio::test] - #[serial] - async fn enable_flow_controller_works() { - let (node_info, _, mut connector) = create_connector().await; - - assert!(!connector.inner_check_to_send_more(MessageType::ScpMessage)); - connector.enable_flow_controller(node_info.overlay_version, node_info.overlay_version); - } } diff --git a/clients/stellar-relay-lib/src/connection/connector/message_handler.rs b/clients/stellar-relay-lib/src/connection/connector/message_handler.rs index 69ac3a4bc..1722bf9e1 100644 --- a/clients/stellar-relay-lib/src/connection/connector/message_handler.rs +++ b/clients/stellar-relay-lib/src/connection/connector/message_handler.rs @@ -1,9 +1,12 @@ -use crate::connection::{ - authentication::verify_remote_auth_cert, - helper::{error_to_string, time_now}, - hmac::HMacKeys, - xdr_converter::parse_authenticated_message, - Connector, Error, Xdr, +use crate::{ + connection::{ + authentication::verify_remote_auth_cert, + helper::{error_to_string, time_now}, + hmac::HMacKeys, + xdr_converter::parse_authenticated_message, + Connector, Error, Xdr, + }, + node::RemoteInfo, }; use substrate_stellar_sdk::{ types::{ErrorCode, Hello, MessageType, StellarMessage}, @@ -11,8 +14,6 @@ use substrate_stellar_sdk::{ }; use tracing::{error, info, trace, warn}; -use crate::node::RemoteInfo; - impl Connector { /// Processes the raw bytes from the stream pub(super) async fn process_raw_message( @@ -24,7 +25,7 @@ impl Connector { match msg_type { MessageType::Transaction | MessageType::FloodAdvert if !self.receive_tx_messages() => { self.increment_remote_sequence()?; - self.check_to_send_more(MessageType::Transaction).await?; + self.maybe_reclaim_capacity(MessageType::Transaction, data.len()).await?; }, MessageType::ScpMessage if !self.receive_scp_messages() => { @@ -52,8 +53,7 @@ impl Connector { self.increment_remote_sequence()?; trace!("process_raw_message(): Processing {msg_type:?} message: auth verified"); } - - return self.process_stellar_message(auth_msg.message, msg_type).await; + return self.process_stellar_message(auth_msg.message, msg_type, data.len()).await; }, } Ok(None) @@ -65,6 +65,7 @@ impl Connector { &mut self, msg: StellarMessage, msg_type: MessageType, + data_len: usize, ) -> Result, Error> { match msg { StellarMessage::Hello(hello) => { @@ -76,7 +77,7 @@ impl Connector { if self.remote_called_us() { self.send_hello_message().await?; } else { - self.send_auth_message().await?; + self.send_auth_message(self.local().node().overlay_version).await?; } info!("process_stellar_message(): Hello message processed successfully"); }, @@ -92,10 +93,11 @@ impl Connector { } return Ok(Some(StellarMessage::ErrorMsg(e))); }, - + StellarMessage::SendMore(_) => {}, + StellarMessage::SendMoreExtended(_) => {}, // we do not handle other messages. Return to caller other => { - self.check_to_send_more(msg_type).await?; + self.maybe_reclaim_capacity(msg_type, data_len).await?; return Ok(Some(other)); }, } @@ -105,21 +107,21 @@ impl Connector { async fn process_auth_message(&mut self) -> Result<(), Error> { if self.remote_called_us() { - self.send_auth_message().await?; + self.send_auth_message(self.local().node().overlay_version).await?; } self.handshake_completed(); if let Some(remote) = self.remote() { - self.enable_flow_controller( + let msg = self.maybe_start_flow_control_bytes( self.local().node().overlay_version, remote.node().overlay_version, ); + self.send_to_node(msg).await?; } else { warn!("process_auth_message(): No remote overlay version after handshake."); } - - self.check_to_send_more(MessageType::Auth).await + Ok(()) } /// Updates the config based on the hello message that was received from the Stellar Node diff --git a/clients/stellar-relay-lib/src/connection/connector/message_reader.rs b/clients/stellar-relay-lib/src/connection/connector/message_reader.rs index 1509e61e1..98d901b52 100644 --- a/clients/stellar-relay-lib/src/connection/connector/message_reader.rs +++ b/clients/stellar-relay-lib/src/connection/connector/message_reader.rs @@ -34,11 +34,10 @@ pub(crate) async fn poll_messages_from_stellar( // check for messages from user. match send_to_node_receiver.try_recv() { - Ok(msg) => { + Ok(msg) => if let Err(e) = connector.send_to_node(msg).await { error!("poll_messages_from_stellar(): Error occurred during sending message to node: {e:?}"); - } - }, + }, Err(TryRecvError::Disconnected) => break, Err(TryRecvError::Empty) => {}, } diff --git a/clients/stellar-relay-lib/src/connection/connector/message_sender.rs b/clients/stellar-relay-lib/src/connection/connector/message_sender.rs index 4075d3ab2..70cc1f4cc 100644 --- a/clients/stellar-relay-lib/src/connection/connector/message_sender.rs +++ b/clients/stellar-relay-lib/src/connection/connector/message_sender.rs @@ -1,11 +1,10 @@ use async_std::io::WriteExt; use std::time::Duration; -use substrate_stellar_sdk::types::{MessageType, SendMore, StellarMessage}; +use substrate_stellar_sdk::types::{MessageType, StellarMessage}; use tokio::time::timeout; use tracing::debug; use crate::connection::{ - flow_controller::MAX_FLOOD_MSG_CAP, handshake::create_auth_message, helper::{time_now, to_base64_xdr_string}, Connector, Error, @@ -34,22 +33,25 @@ impl Connector { self.send_to_node(msg).await } - pub(super) async fn send_auth_message(&mut self) -> Result<(), Error> { - let msg = create_auth_message(); + pub(super) async fn send_auth_message( + &mut self, + local_overlay_version: u32, + ) -> Result<(), Error> { + let msg = create_auth_message(local_overlay_version); debug!("send_auth_message(): Sending Auth Message: {}", to_base64_xdr_string(&msg)); - self.send_to_node(create_auth_message()).await + return self.send_to_node(create_auth_message(local_overlay_version)).await; } - pub(super) async fn check_to_send_more( + pub(super) async fn maybe_reclaim_capacity( &mut self, message_type: MessageType, + data_len: usize, ) -> Result<(), Error> { - if !self.inner_check_to_send_more(message_type) { - return Ok(()); - } - - let msg = StellarMessage::SendMore(SendMore { num_messages: MAX_FLOOD_MSG_CAP }); - self.send_to_node(msg).await + let msg = self.flow_controller.create_reclaim_capacity_message(message_type, data_len); + if let Some(inner_msg) = msg { + return self.send_to_node(inner_msg).await; + }; + Ok(()) } } diff --git a/clients/stellar-relay-lib/src/connection/flow_controller.rs b/clients/stellar-relay-lib/src/connection/flow_controller.rs index 3d70e31a3..70532967f 100644 --- a/clients/stellar-relay-lib/src/connection/flow_controller.rs +++ b/clients/stellar-relay-lib/src/connection/flow_controller.rs @@ -1,42 +1,101 @@ -use substrate_stellar_sdk::types::MessageType; +use substrate_stellar_sdk::types::{MessageType, SendMore, SendMoreExtended, StellarMessage}; -pub const MAX_FLOOD_MSG_CAP: u32 = 2000; +pub const PER_FLOOD_READING_CAPACITY: u32 = 200; +pub const FLOW_CONTROL_SEND_MORE_BATCH_SIZE: u32 = 40; +pub const PER_FLOOD_READING_CAPACITY_BYTES: u32 = 300000; +pub const FLOW_CONTROL_SEND_MORE_BATCH_SIZE_BYTES: u32 = 100000; #[derive(Debug, Default)] pub struct FlowController { - enabled: bool, - flood_msg_cap: u32, + flow_control_bytes_enabled: bool, + messages_received_in_current_batch: u32, + bytes_received_in_current_batch: u32, } impl FlowController { - pub fn enable(&mut self, local_overlay_version: u32, remote_overlay_version: u32) { - self.enabled = remote_overlay_version >= 20 && local_overlay_version >= 20; + pub fn enable_bytes(&mut self, local_overlay_version: u32, remote_overlay_version: u32) { + self.flow_control_bytes_enabled = + remote_overlay_version >= 28 && local_overlay_version >= 28; } - pub fn send_more(&mut self, message_type: MessageType) -> bool { - if !self.enabled { - return false; + pub fn start( + &mut self, + local_overlay_version: u32, + remote_overlay_version: u32, + ) -> StellarMessage { + self.enable_bytes(local_overlay_version, remote_overlay_version); + + if self.flow_control_bytes_enabled { + let msg = StellarMessage::SendMoreExtended(SendMoreExtended { + num_messages: PER_FLOOD_READING_CAPACITY, + num_bytes: PER_FLOOD_READING_CAPACITY_BYTES, + }); + return msg; } + let msg = StellarMessage::SendMore(SendMore { num_messages: PER_FLOOD_READING_CAPACITY }); + return msg; + } + + fn reset_batch_counters(&mut self) { + self.messages_received_in_current_batch = 0; + self.bytes_received_in_current_batch = 0; + } + + pub fn create_reclaim_capacity_message( + &mut self, + message_type: MessageType, + data_len: usize, + ) -> Option { + let data_len_u32 = + u32::try_from(data_len).expect("data_len will always fit within u32; qed"); + let actual_message_size = data_len_u32 - 32 - 12; if is_flood_message(message_type) { - self.flood_msg_cap -= 1; + self.messages_received_in_current_batch += 1; + self.bytes_received_in_current_batch += actual_message_size; } - if self.flood_msg_cap == 0 { - self.flood_msg_cap = MAX_FLOOD_MSG_CAP; - return true; + let mut should_send_more = + self.messages_received_in_current_batch == FLOW_CONTROL_SEND_MORE_BATCH_SIZE; + + if self.flow_control_bytes_enabled { + should_send_more = should_send_more || + self.bytes_received_in_current_batch >= FLOW_CONTROL_SEND_MORE_BATCH_SIZE_BYTES; } - false + //reclaim the capacity + if should_send_more { + if self.flow_control_bytes_enabled { + let send_more_message = StellarMessage::SendMoreExtended(SendMoreExtended { + num_messages: self.messages_received_in_current_batch, /* request back the + * number of messages + * we received, not + * the total capacity + * like when starting! */ + num_bytes: self.bytes_received_in_current_batch, + }); + self.reset_batch_counters(); + + return Some(send_more_message); + } else { + let send_more_message = StellarMessage::SendMore(SendMore { + num_messages: self.messages_received_in_current_batch, + }); + self.reset_batch_counters(); + + return Some(send_more_message); + } + } + return None; } } pub fn is_flood_message(message_type: MessageType) -> bool { match message_type { - MessageType::Transaction - | MessageType::ScpMessage - | MessageType::FloodAdvert - | MessageType::FloodDemand => true, + MessageType::Transaction | + MessageType::ScpMessage | + MessageType::FloodAdvert | + MessageType::FloodDemand => true, _ => false, } } diff --git a/clients/stellar-relay-lib/src/connection/handshake.rs b/clients/stellar-relay-lib/src/connection/handshake.rs index f37db7ca7..187e3d9c1 100644 --- a/clients/stellar-relay-lib/src/connection/handshake.rs +++ b/clients/stellar-relay-lib/src/connection/handshake.rs @@ -6,6 +6,11 @@ use substrate_stellar_sdk::{ PublicKey, }; +// We enable flowControlWithBytes conditionally. This should be enabled if the node version is +// higher than 28. https://github.com/stellarbeat/js-stellar-node-connector/blob/9120f24b75867700ba0ece76369166959205c6b9/src/connection/connection.ts#L634 +// Will not be needed anymore after the minimum version is set to 28. +const AUTH_FLAG_BYTES_CONTROL: i32 = 200; +const AUTH_FLAG_CONTROL: i32 = 100; #[derive(Debug, PartialEq, Eq, PartialOrd, Ord)] pub enum HandshakeState { Connecting, @@ -13,8 +18,10 @@ pub enum HandshakeState { Completed, } -pub fn create_auth_message() -> StellarMessage { - let auth = Auth { flags: 100 }; +pub fn create_auth_message(local_overlay_version: u32) -> StellarMessage { + let flags = + if local_overlay_version >= 28 { AUTH_FLAG_BYTES_CONTROL } else { AUTH_FLAG_CONTROL }; + let auth = Auth { flags }; StellarMessage::Auth(auth) } diff --git a/clients/vault/src/issue.rs b/clients/vault/src/issue.rs index 00dd324e3..6ceee56aa 100644 --- a/clients/vault/src/issue.rs +++ b/clients/vault/src/issue.rs @@ -409,13 +409,12 @@ impl FilterWith for IssueFilter { ) -> bool { let issue_id = match tx.memo_text() { None => return false, - Some(memo_text) => { + Some(memo_text) => if let Some(issue_id) = memos_to_issue_ids.get(memo_text) { issue_id } else { return false; - } - }, + }, }; // check if the issue id is in the list of issues. diff --git a/clients/vault/src/metrics.rs b/clients/vault/src/metrics.rs index bef201b34..05f484a02 100644 --- a/clients/vault/src/metrics.rs +++ b/clients/vault/src/metrics.rs @@ -155,12 +155,10 @@ impl PerCurrencyMetrics { fn format_currency_for_display(currency: CurrencyId) -> String { match currency { CurrencyId::Stellar(asset) => match asset { - Asset::AlphaNum4 { code, .. } => { - String::from_utf8(code.to_vec()).unwrap_or_default().replace('\"', "") - }, - Asset::AlphaNum12 { code, .. } => { - String::from_utf8(code.to_vec()).unwrap_or_default().replace('\"', "") - }, + Asset::AlphaNum4 { code, .. } => + String::from_utf8(code.to_vec()).unwrap_or_default().replace('\"', ""), + Asset::AlphaNum12 { code, .. } => + String::from_utf8(code.to_vec()).unwrap_or_default().replace('\"', ""), Asset::StellarNative => "XLM".to_owned(), }, CurrencyId::Native => "Native".to_owned(), @@ -374,15 +372,15 @@ fn get_balances_for_asset(asset: stellar::Asset, balances: Vec) stellar::Asset::AssetTypeCreditAlphanum4(a4) => balances .iter() .find(|i| { - i.asset_issuer.clone().unwrap_or_default() == a4.issuer.to_encoding() - && i.asset_code.clone().unwrap_or_default() == a4.asset_code.to_vec() + i.asset_issuer.clone().unwrap_or_default() == a4.issuer.to_encoding() && + i.asset_code.clone().unwrap_or_default() == a4.asset_code.to_vec() }) .map(|i| i.balance), stellar::Asset::AssetTypeCreditAlphanum12(a12) => balances .iter() .find(|i| { - i.asset_issuer.clone().unwrap_or_default() == a12.issuer.to_encoding() - && i.asset_code.clone().unwrap_or_default() == a12.asset_code.to_vec() + i.asset_issuer.clone().unwrap_or_default() == a12.issuer.to_encoding() && + i.asset_code.clone().unwrap_or_default() == a12.asset_code.to_vec() }) .map(|i| i.balance), _ => { diff --git a/clients/vault/src/oracle/agent.rs b/clients/vault/src/oracle/agent.rs index 575085b46..dc72c8982 100644 --- a/clients/vault/src/oracle/agent.rs +++ b/clients/vault/src/oracle/agent.rs @@ -42,11 +42,10 @@ async fn handle_message( StellarMessage::ScpMessage(env) => { collector.write().await.handle_envelope(env, message_sender).await?; }, - StellarMessage::TxSet(set) => { + StellarMessage::TxSet(set) => if let Err(e) = collector.read().await.add_txset(set) { tracing::error!(e); - } - }, + }, StellarMessage::GeneralizedTxSet(set) => { if let Err(e) = collector.read().await.add_txset(set) { tracing::error!(e); diff --git a/clients/vault/src/oracle/collector/proof_builder.rs b/clients/vault/src/oracle/collector/proof_builder.rs index 8ddc3ff54..89dbeb2e0 100644 --- a/clients/vault/src/oracle/collector/proof_builder.rs +++ b/clients/vault/src/oracle/collector/proof_builder.rs @@ -123,8 +123,8 @@ impl ScpMessageCollector { if let Some(envelopes) = self.envelopes_map().get(&slot) { // If the data was provided from the archive, no need to check for the minimum // Otherwise, we are still lacking envelopes. - if !self.is_envelopes_data_from_archive(&slot) - && envelopes.len() < get_min_externalized_messages(self.is_public()) + if !self.is_envelopes_data_from_archive(&slot) && + envelopes.len() < get_min_externalized_messages(self.is_public()) { tracing::warn!( "get_envelopes(): Proof Building for slot {slot}: {:?} envelopes is not enough to build proof", @@ -252,8 +252,8 @@ impl ScpMessageCollector { let relevant_envelopes = vec_scp .into_iter() .filter(|scp| match scp.statement.pledges { - ScpStatementPledges::ScpStExternalize(_) - | ScpStatementPledges::ScpStConfirm(_) => true, + ScpStatementPledges::ScpStExternalize(_) | + ScpStatementPledges::ScpStConfirm(_) => true, _ => false, }) .collect::>(); @@ -345,9 +345,7 @@ impl ScpMessageCollector { let tx_set_type = match target_history_entry.clone().ext { TransactionHistoryEntryExt::V1(generalized_tx_set) => // If the type of `ext` is `V1` we use the contained generalized tx set - { - TransactionSetType::new(generalized_tx_set) - }, + TransactionSetType::new(generalized_tx_set), // Otherwise we can use the regular `tx_set` contained in the entry _ => TransactionSetType::new(target_history_entry.tx_set.clone()), }; diff --git a/clients/vault/src/requests/structs.rs b/clients/vault/src/requests/structs.rs index 475a74db7..3b657ea1b 100644 --- a/clients/vault/src/requests/structs.rs +++ b/clients/vault/src/requests/structs.rs @@ -198,12 +198,10 @@ impl Request { match result.map_err(Into::::into) { Ok(ok) => Ok(ok), Err(err) => match err.is_invalid_transaction() { - Some(Recoverability::Recoverable(data)) => { - Err(RetryPolicy::Skip(EnrichedError::InvalidTransaction(data))) - }, - Some(Recoverability::Unrecoverable(data)) => { - Err(RetryPolicy::Throw(EnrichedError::InvalidTransaction(data))) - }, + Some(Recoverability::Recoverable(data)) => + Err(RetryPolicy::Skip(EnrichedError::InvalidTransaction(data))), + Some(Recoverability::Unrecoverable(data)) => + Err(RetryPolicy::Throw(EnrichedError::InvalidTransaction(data))), None => { // Handle other errors if err.is_pool_too_low_priority() { @@ -284,7 +282,7 @@ impl Request { ); let response = match self.request_type { - RequestType::Redeem => { + RequestType::Redeem => wallet .send_payment_to_address( destination_public_key.clone(), @@ -293,9 +291,8 @@ impl Request { request_id, true, ) - .await - }, - RequestType::Replace => { + .await, + RequestType::Replace => wallet .send_payment_to_address( destination_public_key.clone(), @@ -304,8 +301,7 @@ impl Request { request_id, false, ) - .await - }, + .await, } .map_err(|e| Error::StellarWalletError(e))?; diff --git a/clients/vault/src/system.rs b/clients/vault/src/system.rs index 615269c29..c654d54ad 100644 --- a/clients/vault/src/system.rs +++ b/clients/vault/src/system.rs @@ -315,9 +315,8 @@ async fn run_and_monitor_tasks( let monitor = tokio_metrics::TaskMonitor::new(); let metrics_iterator = monitor.intervals(); let task = match task { - ServiceTask::Optional(true, t) | ServiceTask::Essential(t) => { - Some(wait_or_shutdown(shutdown_tx.clone(), t)) - }, + ServiceTask::Optional(true, t) | ServiceTask::Essential(t) => + Some(wait_or_shutdown(shutdown_tx.clone(), t)), _ => None, }?; let task = monitor.instrument(task); diff --git a/clients/vault/tests/helper/helper.rs b/clients/vault/tests/helper/helper.rs index 60c8e3123..fb8d947c1 100644 --- a/clients/vault/tests/helper/helper.rs +++ b/clients/vault/tests/helper/helper.rs @@ -157,9 +157,8 @@ pub async fn send_payment_to_address( match &result { // if the error is `tx_bad_seq` perform the process again - Err(Error::HorizonSubmissionError { reason, .. }) if reason.contains("tx_bad_seq") => { - continue - }, + Err(Error::HorizonSubmissionError { reason, .. }) if reason.contains("tx_bad_seq") => + continue, _ => { response = result; break; diff --git a/clients/wallet/src/error.rs b/clients/wallet/src/error.rs index b73e4e3b3..7c7e71e50 100644 --- a/clients/wallet/src/error.rs +++ b/clients/wallet/src/error.rs @@ -61,11 +61,11 @@ impl Error { }, Error::HorizonSubmissionError { status, .. } if *status == 504 => true, Error::CacheError(e) => match e.kind { - CacheErrorKind::CreateDirectoryFailed - | CacheErrorKind::FileCreationFailed - | CacheErrorKind::WriteToFileFailed - | CacheErrorKind::DeleteFileFailed - | CacheErrorKind::FileDoesNotExist => true, + CacheErrorKind::CreateDirectoryFailed | + CacheErrorKind::FileCreationFailed | + CacheErrorKind::WriteToFileFailed | + CacheErrorKind::DeleteFileFailed | + CacheErrorKind::FileDoesNotExist => true, _ => false, }, _ => false, diff --git a/clients/wallet/src/operations.rs b/clients/wallet/src/operations.rs index d06763d0a..1550a60a7 100644 --- a/clients/wallet/src/operations.rs +++ b/clients/wallet/src/operations.rs @@ -84,14 +84,12 @@ pub trait RedeemOperationsExt: HorizonClient { // if account exists and trustline exists, use normal payment operation Ok(account) if account.is_trustline_exist(&to_be_redeemed_asset) => // normal operation - { create_payment_operation( destination_address, to_be_redeemed_asset.clone(), to_be_redeemed_amount, source_address, - ) - }, + ), // if account exists and NO trustline, use claimable balance operation Ok(_) => claimable_balance_operation(), // if INactive account... @@ -99,8 +97,8 @@ pub trait RedeemOperationsExt: HorizonClient { let to_be_redeemed_amount_u128 = stellar_stroops_to_u128(to_be_redeemed_amount); // ... and redeeming amount >= 1 XLM, use create account operation - if to_be_redeemed_asset == Asset::AssetTypeNative - && to_be_redeemed_amount_u128 >= + if to_be_redeemed_asset == Asset::AssetTypeNative && + to_be_redeemed_amount_u128 >= // It's okay to use the default here because the Stellar decimals are the same primitives::DefaultDecimalsLookup::one( primitives::CurrencyId::StellarNative, diff --git a/clients/wallet/src/resubmissions.rs b/clients/wallet/src/resubmissions.rs index 7b7760963..474736590 100644 --- a/clients/wallet/src/resubmissions.rs +++ b/clients/wallet/src/resubmissions.rs @@ -33,11 +33,10 @@ impl StellarWallet { None => { debug!("try_stop_periodic_resubmission_of_transactions(): no schedule to stop"); }, - Some(sender) => { + Some(sender) => if let Err(e) = sender.send(()).await { warn!("try_stop_periodic_resubmission_of_transactions(): failed to send a stop message to scheduler: {e:?}"); - } - }, + }, } } /// reads in storage the failed (but recoverable) transactions and submit again to Stellar. @@ -170,15 +169,12 @@ impl StellarWallet { async fn handle_error(&self, error: Error) -> Result, Error> { match &error { Error::HorizonSubmissionError { reason, envelope_xdr, .. } => match &reason[..] { - "tx_bad_seq" => { - return self.handle_tx_bad_seq_error_with_xdr(envelope_xdr).await.map(Some) - }, - "tx_internal_error" => { - return self.handle_tx_internal_error(envelope_xdr).await.map(Some) - }, - "tx_insufficient_fee" => { - return self.handle_tx_insufficient_fee_error(envelope_xdr).await.map(Some) - }, + "tx_bad_seq" => + return self.handle_tx_bad_seq_error_with_xdr(envelope_xdr).await.map(Some), + "tx_internal_error" => + return self.handle_tx_internal_error(envelope_xdr).await.map(Some), + "tx_insufficient_fee" => + return self.handle_tx_insufficient_fee_error(envelope_xdr).await.map(Some), _ => { if let Ok(env) = decode_to_envelope(envelope_xdr) { self.remove_tx_envelope_from_cache(&env); diff --git a/pallets/currency/src/lib.rs b/pallets/currency/src/lib.rs index 33d59f2db..cd236940c 100644 --- a/pallets/currency/src/lib.rs +++ b/pallets/currency/src/lib.rs @@ -154,9 +154,9 @@ impl Pallet { let Claimant::ClaimantTypeV0(claimant) = payment.claimants.get_vec()[0].clone(); - if claimant.destination.eq(&recipient_account_pk) - && payment.asset == asset && claimant.predicate - == ClaimPredicate::ClaimPredicateUnconditional + if claimant.destination.eq(&recipient_account_pk) && + payment.asset == asset && claimant.predicate == + ClaimPredicate::ClaimPredicateUnconditional { transferred_amount = transferred_amount.saturating_add(payment.amount); } diff --git a/pallets/issue/src/lib.rs b/pallets/issue/src/lib.rs index 0d08807e4..0d7b37e83 100644 --- a/pallets/issue/src/lib.rs +++ b/pallets/issue/src/lib.rs @@ -863,8 +863,8 @@ impl Pallet { expected_total_amount, )? } else { - if amount_transferred.gt(&expected_total_amount)? - && !ext::vault_registry::is_vault_liquidated::(&issue.vault)? + if amount_transferred.gt(&expected_total_amount)? && + !ext::vault_registry::is_vault_liquidated::(&issue.vault)? { Self::try_increase_issue_amount( issue_id, diff --git a/pallets/issue/src/tests.rs b/pallets/issue/src/tests.rs index 3d2ea2531..1d142bc1e 100644 --- a/pallets/issue/src/tests.rs +++ b/pallets/issue/src/tests.rs @@ -972,43 +972,43 @@ mod integration_tests { let vault_4_collateral_usd = to_usd(&collateral_4, &VAULT_4.collateral_currency()); let vault_5_collateral_usd = to_usd(&collateral_5, &VAULT_5.collateral_currency()); - let total_amount_usd = vault_1_collateral_usd - + vault_2_collateral_usd - + vault_3_collateral_usd - + vault_4_collateral_usd - + vault_5_collateral_usd; + let total_amount_usd = vault_1_collateral_usd + + vault_2_collateral_usd + + vault_3_collateral_usd + + vault_4_collateral_usd + + vault_5_collateral_usd; // In order to calculate the value corresponding to each vault on the pool, // we must take into account that vault 1 and 2, vault 3 and 4 share the same // collateral, so in the calculations for the pooled rewards, these must be grouped let get_expected_value_vault_1 = |fee: Balance| -> Balance { - ((((vault_1_collateral_usd + vault_2_collateral_usd) as f64 - / total_amount_usd as f64) - * fee as f64) + ((((vault_1_collateral_usd + vault_2_collateral_usd) as f64 / + total_amount_usd as f64) * + fee as f64) .floor() * (collateral_1 as f64 / (collateral_2 + collateral_1) as f64)) .floor() as u128 }; let get_expected_value_vault_2 = |fee: Balance| -> Balance { - ((((vault_1_collateral_usd + vault_2_collateral_usd) as f64 - / total_amount_usd as f64) - * fee as f64) + ((((vault_1_collateral_usd + vault_2_collateral_usd) as f64 / + total_amount_usd as f64) * + fee as f64) .floor() * (collateral_2 as f64 / (collateral_2 + collateral_1) as f64)) .floor() as u128 }; let get_expected_value_vault_3 = |fee: Balance| -> Balance { - ((((vault_3_collateral_usd + vault_4_collateral_usd) as f64 - / total_amount_usd as f64) - * fee as f64) + ((((vault_3_collateral_usd + vault_4_collateral_usd) as f64 / + total_amount_usd as f64) * + fee as f64) .floor() * (collateral_3 as f64 / (collateral_3 + collateral_4) as f64)) .floor() as u128 }; let get_expected_value_vault_4 = |fee: Balance| -> Balance { - ((((vault_3_collateral_usd + vault_4_collateral_usd) as f64 - / total_amount_usd as f64) - * fee as f64) + ((((vault_3_collateral_usd + vault_4_collateral_usd) as f64 / + total_amount_usd as f64) * + fee as f64) .floor() * (collateral_4 as f64 / (collateral_3 + collateral_4) as f64)) .floor() as u128 }; @@ -1149,47 +1149,47 @@ mod integration_tests { let vault_4_collateral_usd = to_usd(&collateral_4, &VAULT_4.collateral_currency()); let vault_5_collateral_usd = to_usd(&collateral_5, &VAULT_5.collateral_currency()); - let total_amount_usd = vault_1_collateral_usd - + nominator_amount_usd - + vault_2_collateral_usd - + vault_3_collateral_usd - + vault_4_collateral_usd - + vault_5_collateral_usd; + let total_amount_usd = vault_1_collateral_usd + + nominator_amount_usd + + vault_2_collateral_usd + + vault_3_collateral_usd + + vault_4_collateral_usd + + vault_5_collateral_usd; let reward_for_pool_1_asset_1 = ((((vault_1_collateral_usd + vault_2_collateral_usd + nominator_amount_usd) - as f64 / total_amount_usd as f64) - * issue_fee_1 as f64) - .floor() * ((collateral_1 + nominator_amount) as f64 - / (collateral_1 + collateral_2 + nominator_amount) as f64)) + as f64 / total_amount_usd as f64) * + issue_fee_1 as f64) + .floor() * ((collateral_1 + nominator_amount) as f64 / + (collateral_1 + collateral_2 + nominator_amount) as f64)) .floor(); - let reward_for_nominator_asset_1 = (reward_for_pool_1_asset_1 - * (nominator_amount as f64 / (nominator_amount + collateral_1) as f64)) + let reward_for_nominator_asset_1 = (reward_for_pool_1_asset_1 * + (nominator_amount as f64 / (nominator_amount + collateral_1) as f64)) as u128; let reward_for_pool_1_asset_2 = ((((vault_1_collateral_usd + vault_2_collateral_usd + nominator_amount_usd) - as f64 / total_amount_usd as f64) - * issue_fee_2 as f64) - .floor() * ((collateral_1 + nominator_amount) as f64 - / (collateral_1 + collateral_2 + nominator_amount) as f64)) + as f64 / total_amount_usd as f64) * + issue_fee_2 as f64) + .floor() * ((collateral_1 + nominator_amount) as f64 / + (collateral_1 + collateral_2 + nominator_amount) as f64)) .floor(); - let reward_for_nominator_asset_2 = (reward_for_pool_1_asset_2 - * (nominator_amount as f64 / (nominator_amount + collateral_1) as f64)) + let reward_for_nominator_asset_2 = (reward_for_pool_1_asset_2 * + (nominator_amount as f64 / (nominator_amount + collateral_1) as f64)) as u128; let reward_for_pool_1_asset_3 = ((((vault_1_collateral_usd + vault_2_collateral_usd + nominator_amount_usd) - as f64 / total_amount_usd as f64) - * issue_fee_3 as f64) - .floor() * ((collateral_1 + nominator_amount) as f64 - / (collateral_1 + collateral_2 + nominator_amount) as f64)) + as f64 / total_amount_usd as f64) * + issue_fee_3 as f64) + .floor() * ((collateral_1 + nominator_amount) as f64 / + (collateral_1 + collateral_2 + nominator_amount) as f64)) .floor(); - let reward_for_nominator_asset_3 = (reward_for_pool_1_asset_3 - * (nominator_amount as f64 / (nominator_amount + collateral_1) as f64)) + let reward_for_nominator_asset_3 = (reward_for_pool_1_asset_3 * + (nominator_amount as f64 / (nominator_amount + collateral_1) as f64)) as u128; assert_ok!(>::collect_reward( diff --git a/pallets/oracle/src/dia.rs b/pallets/oracle/src/dia.rs index d97a86d6f..4e92c2c55 100644 --- a/pallets/oracle/src/dia.rs +++ b/pallets/oracle/src/dia.rs @@ -74,8 +74,8 @@ impl Convert None, + CurrencyId::Stellar(primitives::Asset::AlphaNum12 { .. }) | + CurrencyId::ZenlinkLPToken(_, _, _, _) => None, CurrencyId::Token(_) => None, }, } @@ -93,8 +93,8 @@ impl Convert<(Vec, Vec), O Some(OracleKey::ExchangeRate(CurrencyId::XCM(xcm_currency_id))) } else if blockchain == T::native_chain() && symbol == T::native_symbol() { Some(OracleKey::ExchangeRate(CurrencyId::Native)) - } else if blockchain == STELLAR_DIA_BLOCKCHAIN.as_bytes().to_vec() - && symbol == STELLAR_DIA_SYMBOL.as_bytes().to_vec() + } else if blockchain == STELLAR_DIA_BLOCKCHAIN.as_bytes().to_vec() && + symbol == STELLAR_DIA_SYMBOL.as_bytes().to_vec() { Some(OracleKey::ExchangeRate(CurrencyId::StellarNative)) } else if blockchain == FIAT_DIA_BLOCKCHAIN.as_bytes().to_vec() { diff --git a/pallets/oracle/src/lib.rs b/pallets/oracle/src/lib.rs index 85ebb5e9b..9128f2221 100644 --- a/pallets/oracle/src/lib.rs +++ b/pallets/oracle/src/lib.rs @@ -247,9 +247,9 @@ impl Pallet { } let current_status_is_online = Self::is_oracle_online(); - let new_status_is_online = oracle_keys.len() > 0 - && updated_items_len > 0 - && updated_items_len == oracle_keys.len(); + let new_status_is_online = oracle_keys.len() > 0 && + updated_items_len > 0 && + updated_items_len == oracle_keys.len(); if current_status_is_online != new_status_is_online { if new_status_is_online { diff --git a/pallets/oracle/src/oracle_mock.rs b/pallets/oracle/src/oracle_mock.rs index 22698c0d5..bec944a97 100644 --- a/pallets/oracle/src/oracle_mock.rs +++ b/pallets/oracle/src/oracle_mock.rs @@ -41,15 +41,12 @@ impl Convert, Vec)>> for MockOracleKeyConvertor { CurrencyId::XCM(token_symbol) => Some((vec![0u8], vec![token_symbol])), CurrencyId::Native => Some((vec![2u8], vec![])), CurrencyId::StellarNative => Some((vec![3u8], vec![])), - CurrencyId::Stellar(Asset::AlphaNum4 { code, .. }) => { - Some((vec![4u8], code.to_vec())) - }, - CurrencyId::Stellar(Asset::AlphaNum12 { code, .. }) => { - Some((vec![5u8], code.to_vec())) - }, - CurrencyId::ZenlinkLPToken(token1_id, token1_type, token2_id, token2_type) => { - Some((vec![6], vec![token1_id, token1_type, token2_id, token2_type])) - }, + CurrencyId::Stellar(Asset::AlphaNum4 { code, .. }) => + Some((vec![4u8], code.to_vec())), + CurrencyId::Stellar(Asset::AlphaNum12 { code, .. }) => + Some((vec![5u8], code.to_vec())), + CurrencyId::ZenlinkLPToken(token1_id, token1_type, token2_id, token2_type) => + Some((vec![6], vec![token1_id, token1_type, token2_id, token2_type])), CurrencyId::Token(token_symbol) => { let token_symbol = token_symbol.to_be_bytes().to_vec(); Some((vec![7], token_symbol)) diff --git a/pallets/oracle/src/testing_utils/mock_convertors.rs b/pallets/oracle/src/testing_utils/mock_convertors.rs index ec24bb3cf..5646dc1ed 100644 --- a/pallets/oracle/src/testing_utils/mock_convertors.rs +++ b/pallets/oracle/src/testing_utils/mock_convertors.rs @@ -13,15 +13,12 @@ impl Convert, Vec)>> for MockOracleKeyConvertor { CurrencyId::XCM(token_symbol) => Some((vec![0u8], vec![token_symbol])), CurrencyId::Native => Some((vec![2u8], vec![0])), CurrencyId::StellarNative => Some((vec![3u8], vec![0])), - CurrencyId::Stellar(Asset::AlphaNum4 { code, .. }) => { - Some((vec![4u8], code.to_vec())) - }, - CurrencyId::Stellar(Asset::AlphaNum12 { code, .. }) => { - Some((vec![5u8], code.to_vec())) - }, - CurrencyId::ZenlinkLPToken(token1_id, token1_type, token2_id, token2_type) => { - Some((vec![6u8], vec![token1_id, token1_type, token2_id, token2_type])) - }, + CurrencyId::Stellar(Asset::AlphaNum4 { code, .. }) => + Some((vec![4u8], code.to_vec())), + CurrencyId::Stellar(Asset::AlphaNum12 { code, .. }) => + Some((vec![5u8], code.to_vec())), + CurrencyId::ZenlinkLPToken(token1_id, token1_type, token2_id, token2_type) => + Some((vec![6u8], vec![token1_id, token1_type, token2_id, token2_type])), CurrencyId::Token(token_symbol) => { let token_symbol = token_symbol.to_be_bytes().to_vec(); Some((vec![7], token_symbol)) diff --git a/pallets/oracle/src/tests.rs b/pallets/oracle/src/tests.rs index d32437c02..7a12a8a5d 100644 --- a/pallets/oracle/src/tests.rs +++ b/pallets/oracle/src/tests.rs @@ -170,13 +170,11 @@ fn test_amount_conversion() { OracleKey::ExchangeRate(currency) => { match currency { // XCM(0) is worth 5 USD - CurrencyId::XCM(0) => { - MockResult::Return(Ok(FixedU128::from_rational(5, 1))) - }, + CurrencyId::XCM(0) => + MockResult::Return(Ok(FixedU128::from_rational(5, 1))), // XCM(1) is worth 1 USD - CurrencyId::XCM(1) => { - MockResult::Return(Ok(FixedU128::from_rational(1, 1))) - }, + CurrencyId::XCM(1) => + MockResult::Return(Ok(FixedU128::from_rational(1, 1))), _ => { panic!("Unexpected currency") }, diff --git a/pallets/redeem/src/lib.rs b/pallets/redeem/src/lib.rs index cea007a37..595b678df 100644 --- a/pallets/redeem/src/lib.rs +++ b/pallets/redeem/src/lib.rs @@ -1059,9 +1059,8 @@ impl Pallet { match request.status { RedeemRequestStatus::Pending => Ok(request), RedeemRequestStatus::Completed => Err(Error::::RedeemCompleted.into()), - RedeemRequestStatus::Reimbursed(_) | RedeemRequestStatus::Retried => { - Err(Error::::RedeemCancelled.into()) - }, + RedeemRequestStatus::Reimbursed(_) | RedeemRequestStatus::Retried => + Err(Error::::RedeemCancelled.into()), } } diff --git a/pallets/replace/src/lib.rs b/pallets/replace/src/lib.rs index 6746caac0..338b5b43d 100644 --- a/pallets/replace/src/lib.rs +++ b/pallets/replace/src/lib.rs @@ -686,8 +686,8 @@ impl Pallet { // if the new_vault locked additional collateral especially for this replace, // release it if it does not cause them to be undercollateralized - if !ext::vault_registry::is_vault_liquidated::(&new_vault_id)? - && ext::vault_registry::is_allowed_to_withdraw_collateral::( + if !ext::vault_registry::is_vault_liquidated::(&new_vault_id)? && + ext::vault_registry::is_allowed_to_withdraw_collateral::( &new_vault_id, &collateral, )? { diff --git a/pallets/reward-distribution/src/lib.rs b/pallets/reward-distribution/src/lib.rs index 65ff731a0..032803d36 100644 --- a/pallets/reward-distribution/src/lib.rs +++ b/pallets/reward-distribution/src/lib.rs @@ -300,8 +300,8 @@ impl Pallet { let mut reward_this_block = reward_per_block; - if Ok(true) - == ext::security::parachain_block_expired::( + if Ok(true) == + ext::security::parachain_block_expired::( rewards_adapted_at, T::DecayInterval::get().saturating_sub(BlockNumberFor::::one()), ) { diff --git a/pallets/reward-distribution/src/tests.rs b/pallets/reward-distribution/src/tests.rs index b343ad2c2..3eb810ea4 100644 --- a/pallets/reward-distribution/src/tests.rs +++ b/pallets/reward-distribution/src/tests.rs @@ -34,20 +34,20 @@ fn to_usd( fn expected_vault_rewards( reward: ::Balance, ) -> Vec<::Balance> { - let total_collateral_in_usd = to_usd(&COLLATERAL_POOL_1, &DEFAULT_COLLATERAL_CURRENCY) - + to_usd(&COLLATERAL_POOL_2, &XCM(1)) - + to_usd(&COLLATERAL_POOL_3, &XCM(2)) - + to_usd(&COLLATERAL_POOL_4, &XCM(3)); - - let reward_pool_1 = (reward as f64 - * (to_usd(&COLLATERAL_POOL_1, &DEFAULT_COLLATERAL_CURRENCY) as f64) - / (total_collateral_in_usd as f64)) as u128; - let reward_pool_2 = (reward as f64 * (to_usd(&COLLATERAL_POOL_2, &XCM(1)) as f64) - / (total_collateral_in_usd as f64)) as u128; - let reward_pool_3 = (reward as f64 * (to_usd(&COLLATERAL_POOL_3, &XCM(2)) as f64) - / (total_collateral_in_usd as f64)) as u128; - let reward_pool_4 = (reward as f64 * (to_usd(&COLLATERAL_POOL_4, &XCM(3)) as f64) - / (total_collateral_in_usd as f64)) as u128; + let total_collateral_in_usd = to_usd(&COLLATERAL_POOL_1, &DEFAULT_COLLATERAL_CURRENCY) + + to_usd(&COLLATERAL_POOL_2, &XCM(1)) + + to_usd(&COLLATERAL_POOL_3, &XCM(2)) + + to_usd(&COLLATERAL_POOL_4, &XCM(3)); + + let reward_pool_1 = (reward as f64 * + (to_usd(&COLLATERAL_POOL_1, &DEFAULT_COLLATERAL_CURRENCY) as f64) / + (total_collateral_in_usd as f64)) as u128; + let reward_pool_2 = (reward as f64 * (to_usd(&COLLATERAL_POOL_2, &XCM(1)) as f64) / + (total_collateral_in_usd as f64)) as u128; + let reward_pool_3 = (reward as f64 * (to_usd(&COLLATERAL_POOL_3, &XCM(2)) as f64) / + (total_collateral_in_usd as f64)) as u128; + let reward_pool_4 = (reward as f64 * (to_usd(&COLLATERAL_POOL_4, &XCM(3)) as f64) / + (total_collateral_in_usd as f64)) as u128; vec![reward_pool_1, reward_pool_2, reward_pool_3, reward_pool_4] } diff --git a/pallets/security/src/lib.rs b/pallets/security/src/lib.rs index bd2477963..28cc03d4f 100644 --- a/pallets/security/src/lib.rs +++ b/pallets/security/src/lib.rs @@ -211,8 +211,8 @@ impl Pallet { /// Checks if the Parachain has a OracleOffline Error state pub fn is_parachain_error_oracle_offline() -> bool { - Self::parachain_status() == StatusCode::Error - && >::get().contains(&ErrorCode::OracleOffline) + Self::parachain_status() == StatusCode::Error && + >::get().contains(&ErrorCode::OracleOffline) } /// Sets the given `StatusCode`. diff --git a/pallets/stellar-relay/src/lib.rs b/pallets/stellar-relay/src/lib.rs index 58e74dd1f..4abae0083 100644 --- a/pallets/stellar-relay/src/lib.rs +++ b/pallets/stellar-relay/src/lib.rs @@ -512,8 +512,8 @@ pub mod pallet { // update only when new organization or validators not equal to old organization or // validators - if new_organization_vec != current_organizations - || new_validator_vec != current_validators + if new_organization_vec != current_organizations || + new_validator_vec != current_validators { OldValidators::::put(current_validators); OldOrganizations::::put(current_organizations); diff --git a/pallets/stellar-relay/src/validation.rs b/pallets/stellar-relay/src/validation.rs index b4324493c..347f32d43 100644 --- a/pallets/stellar-relay/src/validation.rs +++ b/pallets/stellar-relay/src/validation.rs @@ -66,12 +66,10 @@ fn targeted_organization_map( /// Returns a tuple of Externalized Value and Externalized n_h pub fn get_externalized_info(envelope: &ScpEnvelope) -> Result<(&Value, u32), Error> { match &envelope.statement.pledges { - ScpStatementPledges::ScpStExternalize(externalized_statement) => { - Ok((&externalized_statement.commit.value, externalized_statement.n_h)) - }, - ScpStatementPledges::ScpStConfirm(confirmed_statement) => { - Ok((&confirmed_statement.ballot.value, confirmed_statement.n_h)) - }, + ScpStatementPledges::ScpStExternalize(externalized_statement) => + Ok((&externalized_statement.commit.value, externalized_statement.n_h)), + ScpStatementPledges::ScpStConfirm(confirmed_statement) => + Ok((&confirmed_statement.ballot.value, confirmed_statement.n_h)), _ => return Err(Error::::InvalidScpPledge), } } diff --git a/pallets/vault-registry/src/lib.rs b/pallets/vault-registry/src/lib.rs index fb9da5c4b..9a5e2399b 100644 --- a/pallets/vault-registry/src/lib.rs +++ b/pallets/vault-registry/src/lib.rs @@ -147,9 +147,8 @@ pub mod pallet { }; match call { - Call::report_undercollateralized_vault { .. } => { - valid_tx(b"report_undercollateralized_vault".to_vec()) - }, + Call::report_undercollateralized_vault { .. } => + valid_tx(b"report_undercollateralized_vault".to_vec()), _ => InvalidTransaction::Call.into(), } } @@ -1805,8 +1804,8 @@ impl Pallet { let redeemable_tokens = rich_vault.redeemable_tokens().ok()?; - if !redeemable_tokens.is_zero() - && Self::is_vault_below_premium_threshold(&vault_id).unwrap_or(false) + if !redeemable_tokens.is_zero() && + Self::is_vault_below_premium_threshold(&vault_id).unwrap_or(false) { Some((vault_id, redeemable_tokens)) } else { @@ -1834,13 +1833,12 @@ impl Pallet { // iterator returns tuple of (AccountId, Vault), match Self::get_issuable_tokens_from_vault(&vault_id).ok() { - Some(issuable_tokens) => { + Some(issuable_tokens) => if !issuable_tokens.is_zero() { Some((vault_id, issuable_tokens)) } else { None - } - }, + }, None => None, } }) diff --git a/pallets/vault-registry/src/tests.rs b/pallets/vault-registry/src/tests.rs index f886134a2..095a6731f 100644 --- a/pallets/vault-registry/src/tests.rs +++ b/pallets/vault-registry/src/tests.rs @@ -1857,15 +1857,15 @@ mod integration { let vault_1_collateral_usd = to_usd(&collateral_vault_1, &DEFAULT_COLLATERAL_CURRENCY); let vault_2_collateral_usd = to_usd(&collateral_vault_2, &DEFAULT_COLLATERAL_CURRENCY); - let expected_value_vault_1: u128 = ((vault_1_collateral_usd as f64 - / (vault_1_collateral_usd + vault_2_collateral_usd) as f64) - * reward_per_block as f64) + let expected_value_vault_1: u128 = ((vault_1_collateral_usd as f64 / + (vault_1_collateral_usd + vault_2_collateral_usd) as f64) * + reward_per_block as f64) .floor() as u128; //collect rewards for vault 2 - let expected_value_vault_2: u128 = ((vault_2_collateral_usd as f64 - / (vault_1_collateral_usd + vault_2_collateral_usd) as f64) - * reward_per_block as f64) + let expected_value_vault_2: u128 = ((vault_2_collateral_usd as f64 / + (vault_1_collateral_usd + vault_2_collateral_usd) as f64) * + reward_per_block as f64) .floor() as u128; assert_eq!( @@ -1948,37 +1948,37 @@ mod integration { let vault_4_collateral_usd = to_usd(&collateral_vault_4, &COLLATERAL_2_VAULT_2.collateral_currency()); - let total_usd_amount = vault_1_collateral_usd - + vault_2_collateral_usd - + vault_3_collateral_usd - + vault_4_collateral_usd; + let total_usd_amount = vault_1_collateral_usd + + vault_2_collateral_usd + + vault_3_collateral_usd + + vault_4_collateral_usd; let expected_value_vault_1: u128 = ((((vault_1_collateral_usd + vault_2_collateral_usd) - as f64 / total_usd_amount as f64) - * reward_per_block as f64) - .floor() * (collateral_vault_1 as f64 - / (collateral_vault_1 + collateral_vault_2) as f64)) + as f64 / total_usd_amount as f64) * + reward_per_block as f64) + .floor() * (collateral_vault_1 as f64 / + (collateral_vault_1 + collateral_vault_2) as f64)) .floor() as u128; let expected_value_vault_2: u128 = ((((vault_1_collateral_usd + vault_2_collateral_usd) - as f64 / total_usd_amount as f64) - * reward_per_block as f64) - .floor() * (collateral_vault_2 as f64 - / (collateral_vault_1 + collateral_vault_2) as f64)) + as f64 / total_usd_amount as f64) * + reward_per_block as f64) + .floor() * (collateral_vault_2 as f64 / + (collateral_vault_1 + collateral_vault_2) as f64)) .floor() as u128; let expected_value_vault_3: u128 = ((((vault_4_collateral_usd + vault_3_collateral_usd) - as f64 / total_usd_amount as f64) - * reward_per_block as f64) - .floor() * (collateral_vault_3 as f64 - / (collateral_vault_3 + collateral_vault_4) as f64)) + as f64 / total_usd_amount as f64) * + reward_per_block as f64) + .floor() * (collateral_vault_3 as f64 / + (collateral_vault_3 + collateral_vault_4) as f64)) .floor() as u128; let expected_value_vault_4: u128 = ((((vault_4_collateral_usd + vault_3_collateral_usd) - as f64 / total_usd_amount as f64) - * reward_per_block as f64) - .floor() * (collateral_vault_4 as f64 - / (collateral_vault_3 + collateral_vault_4) as f64)) + as f64 / total_usd_amount as f64) * + reward_per_block as f64) + .floor() * (collateral_vault_4 as f64 / + (collateral_vault_3 + collateral_vault_4) as f64)) .floor() as u128; //ACT diff --git a/pallets/vault-registry/src/types.rs b/pallets/vault-registry/src/types.rs index ed9f2a545..8d6d1d4a7 100644 --- a/pallets/vault-registry/src/types.rs +++ b/pallets/vault-registry/src/types.rs @@ -38,17 +38,17 @@ pub enum CurrencySource { impl CurrencySource { pub fn account_id(&self) -> ::AccountId { match self { - CurrencySource::Collateral(DefaultVaultId:: { account_id: x, .. }) - | CurrencySource::AvailableReplaceCollateral(DefaultVaultId:: { + CurrencySource::Collateral(DefaultVaultId:: { account_id: x, .. }) | + CurrencySource::AvailableReplaceCollateral(DefaultVaultId:: { account_id: x, .. - }) - | CurrencySource::ActiveReplaceCollateral(DefaultVaultId:: { + }) | + CurrencySource::ActiveReplaceCollateral(DefaultVaultId:: { account_id: x, .. - }) - | CurrencySource::UserGriefing(x) - | CurrencySource::FreeBalance(x) - | CurrencySource::LiquidatedCollateral(DefaultVaultId:: { account_id: x, .. }) => x.clone(), + }) | + CurrencySource::UserGriefing(x) | + CurrencySource::FreeBalance(x) | + CurrencySource::LiquidatedCollateral(DefaultVaultId:: { account_id: x, .. }) => x.clone(), CurrencySource::LiquidationVault(_) => Pallet::::liquidation_vault_account_id(), } } @@ -70,9 +70,8 @@ impl CurrencySource { T::GetGriefingCollateralCurrencyId::get(), ) }, - CurrencySource::UserGriefing(x) => { - ext::currency::get_reserved_balance::(currency_id, x) - }, + CurrencySource::UserGriefing(x) => + ext::currency::get_reserved_balance::(currency_id, x), CurrencySource::FreeBalance(x) => ext::currency::get_free_balance::(currency_id, x), CurrencySource::LiquidatedCollateral(vault_id) => { let vault = Pallet::::get_vault_from_id(vault_id)?; diff --git a/primitives/src/lib.rs b/primitives/src/lib.rs index 7b42cd61d..81db15e8f 100644 --- a/primitives/src/lib.rs +++ b/primitives/src/lib.rs @@ -478,12 +478,10 @@ impl CurrencyInfo for Asset { fn name(&self) -> &str { match self { Asset::StellarNative => "Stellar", - Asset::AlphaNum4 { code, issuer: _ } => { - from_utf8(&remove_trailing_non_alphanum_bytes(code)).unwrap_or("unspecified") - }, - Asset::AlphaNum12 { code, issuer: _ } => { - from_utf8(&remove_trailing_non_alphanum_bytes(code)).unwrap_or("unspecified") - }, + Asset::AlphaNum4 { code, issuer: _ } => + from_utf8(&remove_trailing_non_alphanum_bytes(code)).unwrap_or("unspecified"), + Asset::AlphaNum12 { code, issuer: _ } => + from_utf8(&remove_trailing_non_alphanum_bytes(code)).unwrap_or("unspecified"), } } @@ -583,9 +581,8 @@ impl DecimalsLookup for PendulumDecimalsLookup { _ => 12, }, // We assume that all other assets have 12 decimals - CurrencyId::Native | CurrencyId::ZenlinkLPToken(_, _, _, _) | CurrencyId::Token(_) => { - 12 - }, + CurrencyId::Native | CurrencyId::ZenlinkLPToken(_, _, _, _) | CurrencyId::Token(_) => + 12, }) as u32 } } @@ -605,9 +602,8 @@ impl DecimalsLookup for AmplitudeDecimalsLookup { _ => 12, }, // We assume that all other assets have 12 decimals - CurrencyId::Native | CurrencyId::ZenlinkLPToken(_, _, _, _) | CurrencyId::Token(_) => { - 12 - }, + CurrencyId::Native | CurrencyId::ZenlinkLPToken(_, _, _, _) | CurrencyId::Token(_) => + 12, }) as u32 } } @@ -693,21 +689,18 @@ impl TryInto for CurrencyId { Self::XCM(_currency_id) => Err("XCM Foreign Asset not defined in the Stellar world."), Self::Native => Err("PEN token not defined in the Stellar world."), Self::StellarNative => Ok(stellar::Asset::native()), - Self::Stellar(Asset::AlphaNum4 { code, issuer }) => { + Self::Stellar(Asset::AlphaNum4 { code, issuer }) => Ok(stellar::Asset::AssetTypeCreditAlphanum4(AlphaNum4 { asset_code: code, issuer: PublicKey::PublicKeyTypeEd25519(issuer), - })) - }, - Self::Stellar(Asset::AlphaNum12 { code, issuer }) => { + })), + Self::Stellar(Asset::AlphaNum12 { code, issuer }) => Ok(stellar::Asset::AssetTypeCreditAlphanum12(AlphaNum12 { asset_code: code, issuer: PublicKey::PublicKeyTypeEd25519(issuer), - })) - }, - Self::ZenlinkLPToken(_, _, _, _) => { - Err("Zenlink LP Token not defined in the Stellar world.") - }, + })), + Self::ZenlinkLPToken(_, _, _, _) => + Err("Zenlink LP Token not defined in the Stellar world."), Self::Token(_) => Err("Token not defined in the Stellar world."), } } @@ -943,9 +936,9 @@ impl TransactionEnvelopeExt for TransactionEnvelope { if payment.claimants.len() == 1 { let Claimant::ClaimantTypeV0(claimant) = &payment.claimants.get_vec()[0]; - if claimant.destination.eq(&recipient_account_pk) - && payment.asset == asset && claimant.predicate - == ClaimPredicate::ClaimPredicateUnconditional + if claimant.destination.eq(&recipient_account_pk) && + payment.asset == asset && claimant.predicate == + ClaimPredicate::ClaimPredicateUnconditional { acc.saturating_add(payment.amount) } else { @@ -973,9 +966,8 @@ impl TransactionEnvelopeExt for TransactionEnvelope { fn get_transaction(&self) -> Option { match self { - TransactionEnvelope::EnvelopeTypeTxV0(transaction) => { - Some(transaction.tx.clone().into()) - }, + TransactionEnvelope::EnvelopeTypeTxV0(transaction) => + Some(transaction.tx.clone().into()), TransactionEnvelope::EnvelopeTypeTx(transaction) => Some(transaction.tx.clone()), _ => None, } diff --git a/testchain/node/src/command.rs b/testchain/node/src/command.rs index 8e0d0af57..5e9146cac 100644 --- a/testchain/node/src/command.rs +++ b/testchain/node/src/command.rs @@ -140,7 +140,7 @@ pub fn run() -> Result<()> { // This switch needs to be in the client, since the client decides // which sub-commands it wants to support. match cmd { - BenchmarkCmd::Pallet(cmd) => { + BenchmarkCmd::Pallet(cmd) => if cfg!(feature = "runtime-benchmarks") { cmd.run:: Result<()> { Err("Benchmarking wasn't enabled when building the node. \ You can enable it with `--features runtime-benchmarks`." .into()) - } - }, + }, BenchmarkCmd::Block(cmd) => { let PartialComponents { client, .. } = spacewalk_service::new_partial_testnet(&config, false)?; @@ -199,9 +198,8 @@ pub fn run() -> Result<()> { cmd.run(client, inherent_benchmark_data()?, Vec::new(), &ext_factory) }, - BenchmarkCmd::Machine(cmd) => { - cmd.run(&config, SUBSTRATE_REFERENCE_HARDWARE.clone()) - }, + BenchmarkCmd::Machine(cmd) => + cmd.run(&config, SUBSTRATE_REFERENCE_HARDWARE.clone()), } }) },