Skip to content

Commit

Permalink
fix clippy issues
Browse files Browse the repository at this point in the history
  • Loading branch information
ASuciuX committed Mar 5, 2025
1 parent 4514a3b commit d83303a
Show file tree
Hide file tree
Showing 39 changed files with 351 additions and 389 deletions.
4 changes: 2 additions & 2 deletions .cargo/config.toml
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
[alias]
bitcoin-indexer-install = "install --path components/ordhook-cli --locked --force"
bitcoin-indexer-fmt = "fmt -- --config group_imports=StdExternalCrate,imports_granularity=Crate"
bitcoin-indexer-clippy = "clippy --tests --all-features --all-targets -- -D warnings"
bitcoin-indexer-clippy-cli = "clippy --tests --all-features --all-targets --message-format=short -- -D warnings"
bitcoin-indexer-clippy = "clippy --tests --all-features --all-targets -- -A clippy::too_many_arguments -A clippy::needless_return -A clippy::type_complexity -A clippy::ptr_arg"
bitcoin-indexer-clippy-cli = "clippy --tests --all-features --all-targets --message-format=short -- -A clippy::too_many_arguments -A clippy::needless_return -A clippy::type_complexity -A clippy::ptr_arg -D warnings"

[env]
RUST_TEST_THREADS = "1"
4 changes: 2 additions & 2 deletions components/chainhook-postgres/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,9 @@ pub fn pg_pool(config: &PgDatabaseConfig) -> Result<Pool, String> {
if let Some(size) = config.pool_max_size {
pool_builder = pool_builder.max_size(size);
}
Ok(pool_builder
pool_builder
.build()
.map_err(|e| format!("unable to build pg connection pool: {e}"))?)
.map_err(|e| format!("unable to build pg connection pool: {e}"))
}

/// Returns a new pg connection client taken from a pool.
Expand Down
10 changes: 5 additions & 5 deletions components/chainhook-sdk/src/utils/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use std::{
collections::{BTreeSet, VecDeque},
fs::{self, OpenOptions},
io::{Read, Write},
path::PathBuf,
path::Path,
};

use chainhook_types::{BitcoinBlockData, BlockHeader, BlockIdentifier};
Expand Down Expand Up @@ -293,10 +293,10 @@ fn test_block_heights_blocks_limits_entries() {
};
}

pub fn read_file_content_at_path(file_path: &PathBuf) -> Result<Vec<u8>, String> {
pub fn read_file_content_at_path(file_path: &Path) -> Result<Vec<u8>, String> {
use std::{fs::File, io::BufReader};

let file = File::open(file_path.clone())
let file = File::open(file_path)
.map_err(|e| format!("unable to read file {}\n{:?}", file_path.display(), e))?;
let mut file_reader = BufReader::new(file);
let mut file_buffer = vec![];
Expand All @@ -306,9 +306,9 @@ pub fn read_file_content_at_path(file_path: &PathBuf) -> Result<Vec<u8>, String>
Ok(file_buffer)
}

pub fn write_file_content_at_path(file_path: &PathBuf, content: &[u8]) -> Result<(), String> {
pub fn write_file_content_at_path(file_path: &Path, content: &[u8]) -> Result<(), String> {
use std::fs::File;
let mut parent_directory = file_path.clone();
let mut parent_directory = file_path.to_path_buf();
parent_directory.pop();
fs::create_dir_all(&parent_directory).map_err(|e| {
format!(
Expand Down
2 changes: 1 addition & 1 deletion components/chainhook-types-rs/src/bitcoin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ pub struct OutPoint {

impl TxOut {
pub fn get_script_pubkey_bytes(&self) -> Vec<u8> {
hex::decode(&self.get_script_pubkey_hex()).expect("not provided for coinbase txs")
hex::decode(self.get_script_pubkey_hex()).expect("not provided for coinbase txs")
}

pub fn get_script_pubkey_hex(&self) -> &str {
Expand Down
20 changes: 2 additions & 18 deletions components/chainhook-types-rs/src/rosetta.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ impl BlockIdentifier {
}

pub fn get_hash_bytes(&self) -> Vec<u8> {
hex::decode(&self.get_hash_bytes_str()).unwrap()
hex::decode(self.get_hash_bytes_str()).unwrap()
}
}

Expand Down Expand Up @@ -146,7 +146,7 @@ impl TransactionIdentifier {
}

pub fn get_hash_bytes(&self) -> Vec<u8> {
hex::decode(&self.get_hash_bytes_str()).unwrap()
hex::decode(self.get_hash_bytes_str()).unwrap()
}

pub fn get_8_hash_bytes(&self) -> [u8; 8] {
Expand Down Expand Up @@ -429,22 +429,6 @@ impl std::fmt::Display for BitcoinNetwork {
}
}
impl BitcoinNetwork {
pub fn from_str(network: &str) -> Result<BitcoinNetwork, String> {
let value = match network {
"regtest" => BitcoinNetwork::Regtest,
"testnet" => BitcoinNetwork::Testnet,
"mainnet" => BitcoinNetwork::Mainnet,
"signet" => BitcoinNetwork::Signet,
_ => {
return Err(format!(
"network '{}' unsupported (mainnet, testnet, regtest, signet)",
network
))
}
};
Ok(value)
}

pub fn as_str(&self) -> &str {
match self {
BitcoinNetwork::Regtest => "regtest",
Expand Down
8 changes: 2 additions & 6 deletions components/config/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -196,18 +196,14 @@ impl Config {

pub fn assert_ordinals_config(&self) -> Result<(), String> {
if self.ordinals.is_none() {
return Err(format!(
"Config entry for `ordinals` not found in config file."
));
return Err("Config entry for `ordinals` not found in config file.".to_string());
}
Ok(())
}

pub fn assert_runes_config(&self) -> Result<(), String> {
if self.runes.is_none() {
return Err(format!(
"Config entry for `runes` not found in config file."
));
return Err("Config entry for `runes` not found in config file.".to_string());
}
Ok(())
}
Expand Down
24 changes: 11 additions & 13 deletions components/config/src/toml.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,14 @@ pub struct PgDatabaseConfigToml {
}

impl PgDatabaseConfigToml {
fn to_config(self) -> PgDatabaseConfig {
fn to_config(&self) -> PgDatabaseConfig {
PgDatabaseConfig {
dbname: self.database,
host: self.host,
dbname: self.database.clone(),
host: self.host.clone(),
port: self.port,
user: self.username,
password: self.password,
search_path: self.search_path,
user: self.username.clone(),
password: self.password.clone(),
search_path: self.search_path.clone(),
pool_max_size: self.pool_max_size,
}
}
Expand Down Expand Up @@ -155,13 +155,11 @@ impl ConfigToml {
}),
None => None,
};
let metrics = match toml.metrics {
Some(metrics) => Some(MetricsConfig {
enabled: metrics.enabled,
prometheus_port: metrics.prometheus_port,
}),
None => None,
};
let metrics = toml.metrics.map(|metrics| MetricsConfig {
enabled: metrics.enabled,
prometheus_port: metrics.prometheus_port,
});

let config = Config {
storage: StorageConfig {
working_dir: toml
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ pub async fn get_unsent_token_transfers<T: GenericClient>(
)
.await
.map_err(|e| format!("get_unsent_token_transfers: {e}"))?;
results.extend(rows.iter().map(|row| DbOperation::from_pg_row(row)));
results.extend(rows.iter().map(DbOperation::from_pg_row));
}
Ok(results)
}
Expand All @@ -116,7 +116,7 @@ pub async fn insert_tokens<T: GenericClient>(
tokens: &Vec<DbToken>,
client: &T,
) -> Result<(), String> {
if tokens.len() == 0 {
if tokens.is_empty() {
return Ok(());
}
for chunk in tokens.chunks(BATCH_QUERY_CHUNK_SIZE) {
Expand Down Expand Up @@ -158,7 +158,7 @@ pub async fn insert_operations<T: GenericClient>(
operations: &Vec<DbOperation>,
client: &T,
) -> Result<(), String> {
if operations.len() == 0 {
if operations.is_empty() {
return Ok(());
}
for chunk in operations.chunks(BATCH_QUERY_CHUNK_SIZE) {
Expand Down Expand Up @@ -248,7 +248,7 @@ pub async fn update_operation_counts<T: GenericClient>(
counts: &HashMap<String, i32>,
client: &T,
) -> Result<(), String> {
if counts.len() == 0 {
if counts.is_empty() {
return Ok(());
}
let mut params: Vec<&(dyn ToSql + Sync)> = vec![];
Expand All @@ -274,7 +274,7 @@ pub async fn update_address_operation_counts<T: GenericClient>(
counts: &HashMap<String, HashMap<String, i32>>,
client: &T,
) -> Result<(), String> {
if counts.len() == 0 {
if counts.is_empty() {
return Ok(());
}
for chunk in counts
Expand Down Expand Up @@ -312,7 +312,7 @@ pub async fn update_token_operation_counts<T: GenericClient>(
counts: &HashMap<String, i32>,
client: &T,
) -> Result<(), String> {
if counts.len() == 0 {
if counts.is_empty() {
return Ok(());
}
for chunk in counts
Expand Down Expand Up @@ -353,7 +353,7 @@ pub async fn update_token_minted_supplies<T: GenericClient>(
supplies: &HashMap<String, PgNumericU128>,
client: &T,
) -> Result<(), String> {
if supplies.len() == 0 {
if supplies.is_empty() {
return Ok(());
}
for chunk in supplies
Expand Down
10 changes: 4 additions & 6 deletions components/ordhook-core/src/core/meta_protocols/brc20/cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,7 @@ use crate::core::protocol::satoshi_tracking::parse_output_and_offset_from_satpoi

/// If the given `config` has BRC-20 enabled, returns a BRC-20 memory cache.
pub fn brc20_new_cache(config: &Config) -> Option<Brc20MemoryCache> {
let Some(brc20) = config.ordinals_brc20_config() else {
return None;
};
let brc20 = config.ordinals_brc20_config()?;
if !brc20.enabled {
return None;
}
Expand Down Expand Up @@ -116,7 +114,7 @@ impl Brc20MemoryCache {
client: &T,
) -> Result<Option<u128>, String> {
if let Some(minted) = self.token_minted_supplies.get(tick) {
return Ok(Some(minted.clone()));
return Ok(Some(*minted));
}
self.handle_cache_miss(client).await?;
if let Some(minted_supply) = brc20_pg::get_token_minted_supply(tick, client).await? {
Expand All @@ -135,7 +133,7 @@ impl Brc20MemoryCache {
) -> Result<Option<u128>, String> {
let key = format!("{}:{}", tick, address);
if let Some(balance) = self.token_addr_avail_balances.get(&key) {
return Ok(Some(balance.clone()));
return Ok(Some(*balance));
}
self.handle_cache_miss(client).await?;
if let Some(balance) =
Expand All @@ -156,7 +154,7 @@ impl Brc20MemoryCache {
let mut cache_missed_ordinal_numbers = HashSet::new();
for ordinal_number in ordinal_numbers.iter() {
// Use `get` instead of `contains` so we promote this value in the LRU.
if let Some(_) = self.ignored_inscriptions.get(*ordinal_number) {
if self.ignored_inscriptions.get(*ordinal_number).is_some() {
continue;
}
if let Some(row) = self.unsent_transfers.get(*ordinal_number) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ async fn index_unverified_brc20_transfers(
}
let mut results = vec![];
let mut verified_brc20_transfers =
verify_brc20_transfers(transfers, brc20_cache, &brc20_db_tx, &ctx).await?;
verify_brc20_transfers(transfers, brc20_cache, brc20_db_tx, ctx).await?;
// Sort verified transfers by tx_index to make sure they are applied in the order they came through.
verified_brc20_transfers.sort_by(|a, b| a.2.tx_index.cmp(&b.2.tx_index));

Expand Down Expand Up @@ -118,8 +118,8 @@ pub async fn index_block_and_insert_brc20_operations(
&block.block_identifier,
&block.metadata.network,
brc20_cache,
&brc20_db_tx,
&ctx,
brc20_db_tx,
ctx,
)
.await?
else {
Expand Down
6 changes: 3 additions & 3 deletions components/ordhook-core/src/core/meta_protocols/brc20/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ pub fn brc20_self_mint_activation_height(network: &BitcoinNetwork) -> u64 {
pub fn decimals_str_amount_to_u128(amt: &String, decimals: u8) -> Result<u128, String> {
let parts: Vec<&str> = amt.split('.').collect();
let first = parts
.get(0)
.first()
.ok_or("decimals_str_amount_to_u128: first part not found")?;
let integer = (*first)
.parse::<u128>()
Expand All @@ -40,7 +40,7 @@ pub fn decimals_str_amount_to_u128(amt: &String, decimals: u8) -> Result<u128, S
let mut fractional = 0u128;
if let Some(second) = parts.get(1) {
let mut padded = String::with_capacity(decimals as usize);
padded.push_str(*second);
padded.push_str(second);
padded.push_str(&"0".repeat(decimals as usize - (*second).len()));
fractional = padded
.parse::<u128>()
Expand All @@ -58,7 +58,7 @@ pub fn u128_amount_to_decimals_str(amount: u128, decimals: u8) -> String {
}
let decimal_point = num_str.len() as i32 - decimals as i32;
if decimal_point < 0 {
let padding = "0".repeat(decimal_point.abs() as usize);
let padding = "0".repeat(decimal_point.unsigned_abs() as usize);
format!("0.{padding}{num_str}")
} else {
let (integer, fractional) = num_str.split_at(decimal_point as usize);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,12 @@ pub struct Brc20RevealBuilder {
pub parents: Vec<String>,
}

impl Default for Brc20RevealBuilder {
fn default() -> Self {
Self::new()
}
}

impl Brc20RevealBuilder {
pub fn new() -> Self {
Brc20RevealBuilder {
Expand Down Expand Up @@ -101,6 +107,12 @@ pub struct Brc20TransferBuilder {
pub tx_index: usize,
}

impl Default for Brc20TransferBuilder {
fn default() -> Self {
Self::new()
}
}

impl Brc20TransferBuilder {
pub fn new() -> Self {
Brc20TransferBuilder {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ pub async fn verify_brc20_operation(
return Ok(None);
};
if data.tick.len() == 5 {
if reveal.parents.len() == 0 {
if reveal.parents.is_empty() {
try_debug!(
ctx,
"BRC-20: Attempting to mint self-minted token {} without a parent ref",
Expand Down Expand Up @@ -187,7 +187,7 @@ pub async fn verify_brc20_operation(
return Ok(None);
}
let Some(avail_balance) = cache
.get_token_address_avail_balance(&token.ticker, &inscriber_address, db_tx)
.get_token_address_avail_balance(&token.ticker, inscriber_address, db_tx)
.await?
else {
try_debug!(
Expand Down Expand Up @@ -293,7 +293,7 @@ pub async fn verify_brc20_transfers(
(*tx_identifier).clone(),
));
}
return Ok(results);
Ok(results)
}

#[cfg(test)]
Expand Down
Loading

0 comments on commit d83303a

Please sign in to comment.