chore: fix clippy complains (#3776)

* chore: fix clippy complains

* fix lints

* simplify some parts

---------

Co-authored-by: Aursen <aursen@users.noreply.github.com>
This commit is contained in:
Jean (Exotic Markets) 2025-07-17 22:21:27 +07:00 committed by GitHub
parent f8602079af
commit bf495ac3df
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
15 changed files with 54 additions and 68 deletions

View File

@ -194,7 +194,7 @@ pub fn install_version(
AVM_HOME.to_str().unwrap().into(), AVM_HOME.to_str().unwrap().into(),
]; ];
let conditional_args = match install_target { let conditional_args = match install_target {
InstallTarget::Version(version) => ["--tag".into(), format!("v{}", version)], InstallTarget::Version(version) => ["--tag".into(), format!("v{version}")],
InstallTarget::Commit(commit) => ["--rev".into(), commit], InstallTarget::Commit(commit) => ["--rev".into(), commit],
}; };
args.extend_from_slice(&conditional_args); args.extend_from_slice(&conditional_args);

View File

@ -131,12 +131,15 @@ pub fn check_idl_build_feature() -> Result<()> {
.iter() .iter()
.any(|(feature, _)| feature == "idl-build"); .any(|(feature, _)| feature == "idl-build");
if !has_idl_build_feature { if !has_idl_build_feature {
let anchor_spl_idl_build = manifest let anchor_spl_idl_build = if manifest
.dependencies .dependencies
.iter() .iter()
.any(|dep| dep.0 == "anchor-spl") .any(|dep| dep.0 == "anchor-spl")
.then_some(r#", "anchor-spl/idl-build""#) {
.unwrap_or_default(); r#", "anchor-spl/idl-build""#
} else {
""
};
return Err(anyhow!( return Err(anyhow!(
r#"`idl-build` feature is missing. To solve, add r#"`idl-build` feature is missing. To solve, add

View File

@ -318,8 +318,7 @@ impl WithPath<Config> {
.map(|entry| self.process_single_path(&entry.path())) .map(|entry| self.process_single_path(&entry.path()))
.collect(), .collect(),
Err(e) => vec![Err(Error::new(io::Error::other(format!( Err(e) => vec![Err(Error::new(io::Error::other(format!(
"Error reading directory {:?}: {}", "Error reading directory {dir:?}: {e}"
dir, e
))))], ))))],
} }
} else { } else {
@ -332,8 +331,7 @@ impl WithPath<Config> {
fn process_single_path(&self, path: &PathBuf) -> Result<PathBuf, Error> { fn process_single_path(&self, path: &PathBuf) -> Result<PathBuf, Error> {
path.canonicalize().map_err(|e| { path.canonicalize().map_err(|e| {
Error::new(io::Error::other(format!( Error::new(io::Error::other(format!(
"Error canonicalizing path {:?}: {}", "Error canonicalizing path {path:?}: {e}"
path, e
))) )))
}) })
} }
@ -685,7 +683,7 @@ impl fmt::Display for Config {
}; };
let cfg = toml::to_string(&cfg).expect("Must be well formed"); let cfg = toml::to_string(&cfg).expect("Must be well formed");
write!(f, "{}", cfg) write!(f, "{cfg}")
} }
} }

View File

@ -1086,10 +1086,7 @@ fn init(
let package_manager_result = install_node_modules(&package_manager_cmd)?; let package_manager_result = install_node_modules(&package_manager_cmd)?;
if !package_manager_result.status.success() && package_manager_cmd != "npm" { if !package_manager_result.status.success() && package_manager_cmd != "npm" {
println!( println!("Failed {package_manager_cmd} install will attempt to npm install");
"Failed {} install will attempt to npm install",
package_manager_cmd
);
install_node_modules("npm")?; install_node_modules("npm")?;
} else { } else {
eprintln!("Failed to install node modules"); eprintln!("Failed to install node modules");
@ -2017,7 +2014,7 @@ fn _build_solidity_cwd(
// idl is written to idl_out or . // idl is written to idl_out or .
let idl_path = idl_out let idl_path = idl_out
.unwrap_or(PathBuf::from(".")) .unwrap_or(PathBuf::from("."))
.join(format!("{}.json", name)); .join(format!("{name}.json"));
let idl = fs::read(idl_path)?; let idl = fs::read(idl_path)?;
let idl = convert_idl(&idl)?; let idl = convert_idl(&idl)?;
@ -3852,14 +3849,14 @@ fn deploy(
let solana_args = add_recommended_deployment_solana_args(&client, solana_args)?; let solana_args = add_recommended_deployment_solana_args(&client, solana_args)?;
// Deploy the programs. // Deploy the programs.
println!("Deploying cluster: {}", url); println!("Deploying cluster: {url}");
println!("Upgrade authority: {}", keypair); println!("Upgrade authority: {keypair}");
for mut program in cfg.get_programs(program_name)? { for mut program in cfg.get_programs(program_name)? {
let binary_path = program.binary_path(verifiable).display().to_string(); let binary_path = program.binary_path(verifiable).display().to_string();
println!("Deploying program {:?}...", program.lib_name); println!("Deploying program {:?}...", program.lib_name);
println!("Program path: {}...", binary_path); println!("Program path: {binary_path}...");
let (program_keypair_filepath, program_id) = match &program_keypair { let (program_keypair_filepath, program_id) = match &program_keypair {
Some(path) => (path.clone(), get_keypair(path)?.pubkey()), Some(path) => (path.clone(), get_keypair(path)?.pubkey()),
@ -4036,7 +4033,7 @@ fn create_idl_account(
if retries == 19 { if retries == 19 {
return Err(anyhow!("Error creating IDL account: {}", err)); return Err(anyhow!("Error creating IDL account: {}", err));
} }
println!("Error creating IDL account: {}. Retrying...", err); println!("Error creating IDL account: {err}. Retrying...");
} }
} }
} }
@ -4118,7 +4115,7 @@ fn create_idl_buffer(
if retries == 19 { if retries == 19 {
return Err(anyhow!("Error creating buffer account: {}", err)); return Err(anyhow!("Error creating buffer account: {}", err));
} }
println!("Error creating buffer account: {}. Retrying...", err); println!("Error creating buffer account: {err}. Retrying...");
} }
} }
} }
@ -4825,7 +4822,7 @@ fn get_recommended_micro_lamport_fee(client: &RpcClient) -> Result<u64> {
fees.sort_unstable_by_key(|fee| fee.prioritization_fee); fees.sort_unstable_by_key(|fee| fee.prioritization_fee);
let median_index = fees.len() / 2; let median_index = fees.len() / 2;
let median_priority_fee = if fees.len() % 2 == 0 { let median_priority_fee = if fees.len().is_multiple_of(2) {
(fees[median_index - 1].prioritization_fee + fees[median_index].prioritization_fee) / 2 (fees[median_index - 1].prioritization_fee + fees[median_index].prioritization_fee) / 2
} else { } else {
fees[median_index].prioritization_fee fees[median_index].prioritization_fee

View File

@ -751,10 +751,9 @@ description = "Created with Anchor"
edition = "2021" edition = "2021"
[dependencies] [dependencies]
anchor-client = "{0}" anchor-client = "{VERSION}"
{1} = {{ version = "0.1.0", path = "../programs/{1}" }} {name} = {{ version = "0.1.0", path = "../programs/{name}" }}
"#, "#,
VERSION, name,
) )
} }

View File

@ -101,7 +101,7 @@ impl<C: Deref<Target = impl Signer> + Clone> Program<C> {
pub fn on<T: anchor_lang::Event + anchor_lang::AnchorDeserialize>( pub fn on<T: anchor_lang::Event + anchor_lang::AnchorDeserialize>(
&self, &self,
f: impl Fn(&EventContext, T) + Send + 'static, f: impl Fn(&EventContext, T) + Send + 'static,
) -> Result<EventUnsubscriber, ClientError> { ) -> Result<EventUnsubscriber<'_>, ClientError> {
let (handle, rx) = self.rt.block_on(self.on_internal(f))?; let (handle, rx) = self.rt.block_on(self.on_internal(f))?;
Ok(EventUnsubscriber { Ok(EventUnsubscriber {

View File

@ -140,7 +140,7 @@ fn build(
) -> Result<Idl> { ) -> Result<Idl> {
// `nightly` toolchain is currently required for building the IDL. // `nightly` toolchain is currently required for building the IDL.
let toolchain = std::env::var("RUSTUP_TOOLCHAIN") let toolchain = std::env::var("RUSTUP_TOOLCHAIN")
.map(|toolchain| format!("+{}", toolchain)) .map(|toolchain| format!("+{toolchain}"))
.unwrap_or_else(|_| "+nightly".to_string()); .unwrap_or_else(|_| "+nightly".to_string());
install_toolchain_if_needed(&toolchain)?; install_toolchain_if_needed(&toolchain)?;
@ -174,7 +174,7 @@ fn build(
let stdout = String::from_utf8_lossy(&output.stdout); let stdout = String::from_utf8_lossy(&output.stdout);
if env::var("ANCHOR_LOG").is_ok() { if env::var("ANCHOR_LOG").is_ok() {
eprintln!("{}", stdout); eprintln!("{stdout}");
} }
if !output.status.success() { if !output.status.success() {

View File

@ -126,9 +126,8 @@ pub fn convert_idl_type_def_to_ts(
let attrs = { let attrs = {
let debug_attr = quote!(#[derive(Debug)]); let debug_attr = quote!(#[derive(Debug)]);
let default_attr = can_derive_default(ty_def, ty_defs) let default_attr =
.then(|| quote!(#[derive(Default)])) can_derive_default(ty_def, ty_defs).then_some(quote!(#[derive(Default)]));
.unwrap_or_default();
let ser_attr = match &ty_def.serialization { let ser_attr = match &ty_def.serialization {
IdlSerialization::Borsh => quote!(#[derive(AnchorSerialize, AnchorDeserialize)]), IdlSerialization::Borsh => quote!(#[derive(AnchorSerialize, AnchorDeserialize)]),
@ -155,7 +154,7 @@ pub fn convert_idl_type_def_to_ts(
} }
}; };
let repr = if let Some(repr) = &ty_def.repr { let repr = ty_def.repr.as_ref().map(|repr| {
let kind = match repr { let kind = match repr {
IdlRepr::Rust(_) => "Rust", IdlRepr::Rust(_) => "Rust",
IdlRepr::C(_) => "C", IdlRepr::C(_) => "C",
@ -166,33 +165,24 @@ pub fn convert_idl_type_def_to_ts(
let modifier = match repr { let modifier = match repr {
IdlRepr::Rust(modifier) | IdlRepr::C(modifier) => { IdlRepr::Rust(modifier) | IdlRepr::C(modifier) => {
let packed = modifier.packed.then(|| quote!(packed)).unwrap_or_default(); let packed = modifier.packed.then_some(quote!(packed));
let align = modifier let align = modifier
.align .align
.map(Literal::usize_unsuffixed) .map(Literal::usize_unsuffixed)
.map(|align| quote!(align(#align))) .map(|align| quote!(align(#align)));
.unwrap_or_default();
if packed.is_empty() { match (packed, align) {
align (None, None) => None,
} else if align.is_empty() { (Some(p), None) => Some(quote!(#p)),
packed (None, Some(a)) => Some(quote!(#a)),
} else { (Some(p), Some(a)) => Some(quote!(#p, #a)),
quote! { #packed, #align }
} }
} }
_ => quote!(), _ => None,
}; }
let modifier = if modifier.is_empty() { .map(|m| quote!(, #m));
modifier
} else {
quote! { , #modifier }
};
quote! { #[repr(#kind #modifier)] } quote! { #[repr(#kind #modifier)] }
} else { });
quote!()
};
match &ty_def.ty { match &ty_def.ty {
IdlTypeDefTy::Struct { fields } => { IdlTypeDefTy::Struct { fields } => {

View File

@ -167,14 +167,14 @@ fn gen_internal_accounts_common(
let name = format_ident!("{}", acc.name); let name = format_ident!("{}", acc.name);
let attrs = { let attrs = {
let signer = acc.signer.then(|| quote!(signer)).unwrap_or_default(); let signer = acc.signer.then_some(quote!(signer));
let mt = acc.writable.then(|| quote!(mut)).unwrap_or_default(); let mt = acc.writable.then_some(quote!(mut));
if signer.is_empty() {
mt match (signer, mt) {
} else if mt.is_empty() { (None, None) => None,
signer (Some(s), None) => Some(quote!(#s)),
} else { (None, Some(m)) => Some(quote!(#m)),
quote! { #signer, #mt } (Some(s), Some(m)) => Some(quote!(#s, #m)),
} }
}; };

View File

@ -151,7 +151,7 @@ impl<'info, T: ZeroCopy + Owner> AccountLoader<'info, T> {
} }
/// Returns a Ref to the account data structure for reading. /// Returns a Ref to the account data structure for reading.
pub fn load(&self) -> Result<Ref<T>> { pub fn load(&self) -> Result<Ref<'_, T>> {
let data = self.acc_info.try_borrow_data()?; let data = self.acc_info.try_borrow_data()?;
let disc = T::DISCRIMINATOR; let disc = T::DISCRIMINATOR;
if data.len() < disc.len() { if data.len() < disc.len() {
@ -169,7 +169,7 @@ impl<'info, T: ZeroCopy + Owner> AccountLoader<'info, T> {
} }
/// Returns a `RefMut` to the account data structure for reading or writing. /// Returns a `RefMut` to the account data structure for reading or writing.
pub fn load_mut(&self) -> Result<RefMut<T>> { pub fn load_mut(&self) -> Result<RefMut<'_, T>> {
// AccountInfo api allows you to borrow mut even if the account isn't // AccountInfo api allows you to borrow mut even if the account isn't
// writable, so add this check for a better dev experience. // writable, so add this check for a better dev experience.
if !self.acc_info.is_writable { if !self.acc_info.is_writable {
@ -196,7 +196,7 @@ impl<'info, T: ZeroCopy + Owner> AccountLoader<'info, T> {
/// Returns a `RefMut` to the account data structure for reading or writing. /// Returns a `RefMut` to the account data structure for reading or writing.
/// Should only be called once, when the account is being initialized. /// Should only be called once, when the account is being initialized.
pub fn load_init(&self) -> Result<RefMut<T>> { pub fn load_init(&self) -> Result<RefMut<'_, T>> {
// AccountInfo api allows you to borrow mut even if the account isn't // AccountInfo api allows you to borrow mut even if the account isn't
// writable, so add this check for a better dev experience. // writable, so add this check for a better dev experience.
if !self.acc_info.is_writable { if !self.acc_info.is_writable {

View File

@ -319,7 +319,7 @@ impl From<TryFromIntError> for Error {
Self::AnchorError(Box::new(AnchorError { Self::AnchorError(Box::new(AnchorError {
error_name: ErrorCode::InvalidNumericConversion.name(), error_name: ErrorCode::InvalidNumericConversion.name(),
error_code_number: ErrorCode::InvalidNumericConversion.into(), error_code_number: ErrorCode::InvalidNumericConversion.into(),
error_msg: format!("{}", e), error_msg: format!("{e}"),
error_origin: None, error_origin: None,
compared_values: None, compared_values: None,
})) }))

View File

@ -7,7 +7,7 @@ use std::fmt::Display;
use super::constraints; use super::constraints;
pub fn generate_bumps_name<T: Display>(anchor_ident: &T) -> Ident { pub fn generate_bumps_name<T: Display>(anchor_ident: &T) -> Ident {
Ident::new(&format!("{}Bumps", anchor_ident), Span::call_site()) Ident::new(&format!("{anchor_ident}Bumps"), Span::call_site())
} }
pub fn generate(accs: &AccountsStruct) -> proc_macro2::TokenStream { pub fn generate(accs: &AccountsStruct) -> proc_macro2::TokenStream {

View File

@ -365,8 +365,7 @@ pub fn generate_constraint_owner(f: &Field, c: &ConstraintOwner) -> proc_macro2:
| Ty::InterfaceAccount(InterfaceAccountTy { boxed, .. }) => *boxed, | Ty::InterfaceAccount(InterfaceAccountTy { boxed, .. }) => *boxed,
_ => false, _ => false,
} }
.then(|| quote!(*)) .then_some(quote!(*));
.unwrap_or_default();
let owner_address = &c.owner_address; let owner_address = &c.owner_address;
let error = generate_custom_error( let error = generate_custom_error(
ident, ident,

View File

@ -20,7 +20,7 @@ pub fn sighash(namespace: &str, name: &str) -> [u8; 8] {
pub fn gen_discriminator(namespace: &str, name: impl ToString) -> proc_macro2::TokenStream { pub fn gen_discriminator(namespace: &str, name: impl ToString) -> proc_macro2::TokenStream {
let discriminator = sighash(namespace, name.to_string().as_str()); let discriminator = sighash(namespace, name.to_string().as_str());
format!("&{:?}", discriminator).parse().unwrap() format!("&{discriminator:?}").parse().unwrap()
} }
pub fn generate_ix_variant(name: &str, args: &[IxArg]) -> proc_macro2::TokenStream { pub fn generate_ix_variant(name: &str, args: &[IxArg]) -> proc_macro2::TokenStream {

View File

@ -38,11 +38,11 @@ impl CrateContext {
self.modules.iter().flat_map(|(_, ctx)| ctx.type_aliases()) self.modules.iter().flat_map(|(_, ctx)| ctx.type_aliases())
} }
pub fn modules(&self) -> impl Iterator<Item = ModuleContext> { pub fn modules(&self) -> impl Iterator<Item = ModuleContext<'_>> {
self.modules.values().map(|detail| ModuleContext { detail }) self.modules.values().map(|detail| ModuleContext { detail })
} }
pub fn root_module(&self) -> ModuleContext { pub fn root_module(&self) -> ModuleContext<'_> {
ModuleContext { ModuleContext {
detail: self.modules.get("crate").unwrap(), detail: self.modules.get("crate").unwrap(),
} }