فهرست منبع

fix: Resolve Clippy Warnings and Format (#3751)

* refactor: Simplify error handling and improve readability in various modules

- Updated error handling in `cli/src/config.rs` to use `io::Error::other`.
- Enhanced error mapping in `client/src/lib.rs` for asynchronous calls.
- Refactored conditional expressions in `idl/src/convert.rs` and `lang/attribute/program/src/declare_program/mods/internal.rs` for clarity.
- Improved logic in `lang/syn/src/codegen/accounts/constraints.rs` for rent constraints handling.

* refactor: Enhance code readability and error handling in config and client modules

- Improved error handling formatting in `cli/src/config.rs` for directory reading and path canonicalization.
- Refactored asynchronous call handling in `client/src/lib.rs` to improve clarity and maintainability.
- Adjusted method chaining for better readability in multiple locations within the client module.

* fix: format TypeScript test files

* refactor: Update TypeScript test files for improved type inference

- Adjusted type definitions in various test files to enhance type inference by removing unnecessary parentheses around `typeof` expressions.
Hasip Timurtas 3 ماه پیش
والد
کامیت
b5aced54f3

+ 8 - 8
cli/src/config.rs

@@ -317,10 +317,10 @@ impl WithPath<Config> {
                             .filter_map(|entry| entry.ok())
                             .map(|entry| self.process_single_path(&entry.path()))
                             .collect(),
-                        Err(e) => vec![Err(Error::new(io::Error::new(
-                            io::ErrorKind::Other,
-                            format!("Error reading directory {:?}: {}", dir, e),
-                        )))],
+                        Err(e) => vec![Err(Error::new(io::Error::other(format!(
+                            "Error reading directory {:?}: {}",
+                            dir, e
+                        ))))],
                     }
                 } else {
                     vec![self.process_single_path(&path)]
@@ -331,10 +331,10 @@ impl WithPath<Config> {
 
     fn process_single_path(&self, path: &PathBuf) -> Result<PathBuf, Error> {
         path.canonicalize().map_err(|e| {
-            Error::new(io::Error::new(
-                io::ErrorKind::Other,
-                format!("Error canonicalizing path {:?}: {}", path, e),
-            ))
+            Error::new(io::Error::other(format!(
+                "Error canonicalizing path {:?}: {}",
+                path, e
+            )))
         })
     }
 }

+ 36 - 16
client/src/lib.rs

@@ -262,7 +262,8 @@ impl<C: Deref<Target = impl Signer> + Clone> Program<C> {
         let account = self
             .internal_rpc_client
             .get_account_with_commitment(&address, CommitmentConfig::processed())
-            .await?
+            .await
+            .map_err(Box::new)?
             .value
             .ok_or(ClientError::AccountNotFound)?;
         let mut data: &[u8] = &account.data;
@@ -288,7 +289,8 @@ impl<C: Deref<Target = impl Signer> + Clone> Program<C> {
             inner: self
                 .internal_rpc_client
                 .get_program_accounts_with_config(&self.id(), config)
-                .await?
+                .await
+                .map_err(Box::new)?
                 .into_iter()
                 .map(|(key, account)| {
                     Ok((key, T::try_deserialize(&mut (&account.data as &[u8]))?))
@@ -301,7 +303,9 @@ impl<C: Deref<Target = impl Signer> + Clone> Program<C> {
         let mut client = lock.write().await;
 
         if client.is_none() {
-            let sub_client = PubsubClient::new(self.cfg.cluster.ws_url()).await?;
+            let sub_client = PubsubClient::new(self.cfg.cluster.ws_url())
+                .await
+                .map_err(Box::new)?;
             *client = Some(sub_client);
         }
 
@@ -330,14 +334,18 @@ impl<C: Deref<Target = impl Signer> + Clone> Program<C> {
 
         let handle = tokio::spawn(async move {
             if let Some(ref client) = *lock.read().await {
-                let (mut notifications, unsubscribe) =
-                    client.logs_subscribe(filter, config).await?;
+                let (mut notifications, unsubscribe) = client
+                    .logs_subscribe(filter, config)
+                    .await
+                    .map_err(Box::new)?;
 
                 tx.send(unsubscribe).map_err(|e| {
-                    ClientError::SolanaClientPubsubError(PubsubClientError::RequestFailed {
-                        message: "Unsubscribe failed".to_string(),
-                        reason: e.to_string(),
-                    })
+                    ClientError::SolanaClientPubsubError(Box::new(
+                        PubsubClientError::RequestFailed {
+                            message: "Unsubscribe failed".to_string(),
+                            reason: e.to_string(),
+                        },
+                    ))
                 })?;
 
                 while let Some(logs) = notifications.next().await {
@@ -485,9 +493,9 @@ pub enum ClientError {
     #[error("{0}")]
     ProgramError(#[from] ProgramError),
     #[error("{0}")]
-    SolanaClientError(#[from] SolanaClientError),
+    SolanaClientError(#[from] Box<SolanaClientError>),
     #[error("{0}")]
-    SolanaClientPubsubError(#[from] PubsubClientError),
+    SolanaClientPubsubError(#[from] Box<PubsubClientError>),
     #[error("Unable to parse log: {0}")]
     LogParseError(String),
     #[error(transparent)]
@@ -635,27 +643,39 @@ impl<C: Deref<Target = impl Signer> + Clone, S: AsSigner> RequestBuilder<'_, C,
     }
 
     async fn signed_transaction_internal(&self) -> Result<Transaction, ClientError> {
-        let latest_hash = self.internal_rpc_client.get_latest_blockhash().await?;
+        let latest_hash = self
+            .internal_rpc_client
+            .get_latest_blockhash()
+            .await
+            .map_err(Box::new)?;
 
         let tx = self.signed_transaction_with_blockhash(latest_hash)?;
         Ok(tx)
     }
 
     async fn send_internal(&self) -> Result<Signature, ClientError> {
-        let latest_hash = self.internal_rpc_client.get_latest_blockhash().await?;
+        let latest_hash = self
+            .internal_rpc_client
+            .get_latest_blockhash()
+            .await
+            .map_err(Box::new)?;
         let tx = self.signed_transaction_with_blockhash(latest_hash)?;
 
         self.internal_rpc_client
             .send_and_confirm_transaction(&tx)
             .await
-            .map_err(Into::into)
+            .map_err(|e| Box::new(e).into())
     }
 
     async fn send_with_spinner_and_config_internal(
         &self,
         config: RpcSendTransactionConfig,
     ) -> Result<Signature, ClientError> {
-        let latest_hash = self.internal_rpc_client.get_latest_blockhash().await?;
+        let latest_hash = self
+            .internal_rpc_client
+            .get_latest_blockhash()
+            .await
+            .map_err(Box::new)?;
         let tx = self.signed_transaction_with_blockhash(latest_hash)?;
 
         self.internal_rpc_client
@@ -665,7 +685,7 @@ impl<C: Deref<Target = impl Signer> + Clone, S: AsSigner> RequestBuilder<'_, C,
                 config,
             )
             .await
-            .map_err(Into::into)
+            .map_err(|e| Box::new(e).into())
     }
 }
 

+ 4 - 2
idl/src/convert.rs

@@ -431,11 +431,13 @@ mod legacy {
         fn from(value: IdlTypeDefinitionTy) -> Self {
             match value {
                 IdlTypeDefinitionTy::Struct { fields } => Self::Struct {
-                    fields: fields.is_empty().then_some(None).unwrap_or_else(|| {
+                    fields: if fields.is_empty() {
+                        None
+                    } else {
                         Some(t::IdlDefinedFields::Named(
                             fields.into_iter().map(Into::into).collect(),
                         ))
-                    }),
+                    },
                 },
                 IdlTypeDefinitionTy::Enum { variants } => Self::Enum {
                     variants: variants

+ 5 - 4
lang/attribute/program/src/declare_program/mods/internal.rs

@@ -178,10 +178,11 @@ fn gen_internal_accounts_common(
                         }
                     };
 
-                    let acc_expr = acc
-                        .optional
-                        .then(|| quote! { Option<AccountInfo #generics> })
-                        .unwrap_or_else(|| quote! { AccountInfo #generics });
+                    let acc_expr = if acc.optional {
+                        quote! { Option<AccountInfo #generics> }
+                    } else {
+                        quote! { AccountInfo #generics }
+                    };
 
                     quote! {
                         #[account(#attrs)]

+ 6 - 3
lang/syn/src/codegen/accounts/constraints.rs

@@ -6,11 +6,14 @@ use crate::*;
 pub fn generate(f: &Field, accs: &AccountsStruct) -> proc_macro2::TokenStream {
     let constraints = linearize(&f.constraints);
 
-    let rent = constraints
+    let rent = if constraints
         .iter()
         .any(|c| matches!(c, Constraint::RentExempt(ConstraintRentExempt::Enforce)))
-        .then(|| quote! { let __anchor_rent = Rent::get()?; })
-        .unwrap_or_else(|| quote! {});
+    {
+        quote! { let __anchor_rent = Rent::get()?; }
+    } else {
+        quote! {}
+    };
 
     let checks: Vec<proc_macro2::TokenStream> = constraints
         .iter()