diff --git a/Cargo.lock b/Cargo.lock index 64ab97b..3265644 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -552,6 +552,12 @@ version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + [[package]] name = "form_urlencoded" version = "1.2.1" @@ -722,6 +728,9 @@ name = "hashbrown" version = "0.15.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "84b26c544d002229e640969970a2e74021aadf6e2f96372b9c58eff97de08eb3" +dependencies = [ + "foldhash", +] [[package]] name = "hashlink" @@ -978,6 +987,15 @@ dependencies = [ "windows-sys 0.59.0", ] +[[package]] +name = "itertools" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" +dependencies = [ + "either", +] + [[package]] name = "itoa" version = "1.0.15" @@ -1006,6 +1024,12 @@ version = "0.2.172" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d750af042f7ef4f724306de029d18836c26c1765a54a6a3f094cbd23a7267ffa" +[[package]] +name = "libm" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9fbbcab51052fe104eb5e5d351cf728d30a5be1fe14d9be8a3b097481fb97de" + [[package]] name = "libsqlite3-sys" version = "0.28.0" @@ -1059,6 +1083,40 @@ dependencies = [ "tracing-subscriber", ] +[[package]] +name = "malachite" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec410515e231332b14cd986a475d1c3323bcfa4c7efc038bfa1d5b410b1c57e4" +dependencies = [ + "malachite-base", + "malachite-nz", +] + +[[package]] +name = "malachite-base" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c738d3789301e957a8f7519318fcbb1b92bb95863b28f6938ae5a05be6259f34" +dependencies = [ + "hashbrown 0.15.3", + "itertools", + "libm", + "ryu", +] + +[[package]] +name = "malachite-nz" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1707c9a1fa36ce21749b35972bfad17bbf34cf5a7c96897c0491da321e387d3b" +dependencies = [ + "itertools", + "libm", + "malachite-base", + "wide", +] + [[package]] name = "man" version = "0.1.1" @@ -1572,6 +1630,7 @@ dependencies = [ "electrum-client-netagnostic", "hex", "log", + "malachite", "r2d2", "r2d2_sqlite", "rand 0.8.5", @@ -1864,6 +1923,15 @@ version = "1.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "28d3b2b1366ec20994f1fd18c3c594f05c5dd4bc44d8bb0c1c632c8d6829481f" +[[package]] +name = "safe_arch" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96b02de82ddbe1b636e6170c21be622223aea188ef2e139be0a5b219ec215323" +dependencies = [ + "bytemuck", +] + [[package]] name = "scheduled-thread-pool" version = "0.2.7" @@ -2602,6 +2670,16 @@ dependencies = [ "rustls-pki-types", ] +[[package]] +name = "wide" +version = "0.7.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ce5da8ecb62bcd8ec8b7ea19f69a51275e91299be594ea5cc6ef7819e16cd03" +dependencies = [ + "bytemuck", + "safe_arch", +] + [[package]] name = "winapi" version = "0.3.9" diff --git a/Cargo.toml b/Cargo.toml index c523eb8..fccdde5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -37,8 +37,17 @@ configure_me = "0.4.0" [build-dependencies] configure_me_codegen = "0.4.8" +[dependencies.malachite] +version = "0.6.1" +default-features = false +features = [ "naturals_and_integers"] + [package.metadata.configure_me] spec = "internal/config_specification.toml" [profile.release] debug = true + +[lints.clippy] +# workaround for generated code in depdencendy configure_me +uninlined_format_args = "allow" diff --git a/src/bcmr/bcmrdownloader.rs b/src/bcmr/bcmrdownloader.rs index a27ea71..52cda81 100644 --- a/src/bcmr/bcmrdownloader.rs +++ b/src/bcmr/bcmrdownloader.rs @@ -51,14 +51,14 @@ fn get_download_candidates(db: &DBPool) -> Vec { let conn = match db.get() { Ok(c) => c, Err(e) => { - warn!("bcmr: Failed to get a db connection: {}", e); + warn!("bcmr: Failed to get a db connection: {e}"); return Vec::default(); } }; match get_entries_missing_bcmr_download(&conn) { Ok(c) => c, Err(e) => { - warn!("bcmr: Failed to fetch bcmr download candidates: {}", e); + warn!("bcmr: Failed to fetch bcmr download candidates: {e}"); Vec::default() } } @@ -83,7 +83,7 @@ fn fetch_bcmr( stripped ) } else if !url.starts_with("https://") { - format!("https://{}", url) + format!("https://{url}") } else { url.to_string() }; @@ -173,7 +173,7 @@ impl BCMRDownloader { let conn = match db_cpy.get() { Ok(c) => c, Err(e) => { - warn!("bcmr: Failed to get BCMR db connection: {}", e); + warn!("bcmr: Failed to get BCMR db connection: {e}"); return; } }; @@ -184,10 +184,10 @@ impl BCMRDownloader { if let Err(e) = update_bcmr_failure( &conn, &entry.utxo, - &format!("Failed to fetch BCMR: {}", error), + &format!("Failed to fetch BCMR: {error}"), is_fatal, ) { - warn!("bcmr: Failed to set BCMR error: {}", e) + warn!("bcmr: Failed to set BCMR error: {e}") } return; } @@ -199,10 +199,10 @@ impl BCMRDownloader { if let Err(e) = update_bcmr_failure( &conn, &entry.utxo, - &format!("BCMR invalid JSON error: {}", e), + &format!("BCMR invalid JSON error: {e}"), true, ) { - warn!("bcmr: Failed to set BCMR error: {}", e) + warn!("bcmr: Failed to set BCMR error: {e}") } return; } @@ -220,17 +220,17 @@ impl BCMRDownloader { if let Err(e) = update_bcmr_failure( &conn, &entry.utxo, - &format!("BCMR contents error: {}", err), + &format!("BCMR contents error: {err}"), true, ) { - warn!("bcmr: Failed to set BCMR error: {}", e) + warn!("bcmr: Failed to set BCMR error: {e}") } return; } }; if let Err(err) = insert_bcmr_data(&conn, &entry.utxo, &bcmr_parsed) { - warn!("bcmr: Failed to insert BCMR data {}", err) + warn!("bcmr: Failed to insert BCMR data {err}") } }); }); @@ -254,7 +254,7 @@ impl Drop for BCMRDownloader { match thread.join() { Ok(_) => info!("bcmr download thread done"), - Err(e) => warn!("Failed to join bcmr download thread: {:?}", e), + Err(e) => warn!("Failed to join bcmr download thread: {e:?}"), } } } diff --git a/src/bcmr/wellknowndowloader.rs b/src/bcmr/wellknowndowloader.rs index 46a9dad..d8ab70c 100644 --- a/src/bcmr/wellknowndowloader.rs +++ b/src/bcmr/wellknowndowloader.rs @@ -70,12 +70,12 @@ impl WellKnownDownloader { for (source, url) in WELL_KNOWN { - info!("bcmr: Fetching well known '{}' token list", source); + info!("bcmr: Fetching well known '{source}' token list"); let json_str: String = match get_url(url, DOWNLOAD_TIMEOUT, MAX_BCMR_SIZE) { Ok((json_str, _)) => json_str, Err(e) => { - info!("bcmr: Failed to download well known url {}: {}", url, e); + info!("bcmr: Failed to download well known url {url}: {e}"); continue; } }; @@ -83,7 +83,7 @@ impl WellKnownDownloader { let json: Value = match serde_json::from_str(&json_str) { Ok(j) => j, Err(e) => { - info!("bcmr: Failed to parse well known url {}: {}", url, e); + info!("bcmr: Failed to parse well known url {url}: {e}"); continue; } }; @@ -91,7 +91,7 @@ impl WellKnownDownloader { let bcmr_entries = match parse_all_bcmr_identities(&json, true, source) { Ok(entries) => entries, Err(e) => { - info!("bcmr: Failed to parse bcmr from well known url {}: {}", url, e); + info!("bcmr: Failed to parse bcmr from well known url {url}: {e}"); continue; } }; @@ -99,29 +99,29 @@ impl WellKnownDownloader { let mut tx = match db_cpy.get() { Ok(conn) => conn, Err(e) => { - warn!("bcmr: Failed to get DB connection: {}", e); + warn!("bcmr: Failed to get DB connection: {e}"); continue; } }; let tx = match tx.transaction() { Ok(tx) => tx, Err(e) => { - warn!("bcmr: Failed to initiate DB transaction: {}", e); + warn!("bcmr: Failed to initiate DB transaction: {e}"); continue; } }; if let Err(e) = delete_entries_for_well_known(&tx, source) { - warn!("bcmr: Failed to delete entries for well known source {}: {}", source, e); + warn!("bcmr: Failed to delete entries for well known source {source}: {e}"); } for bcmr in bcmr_entries { if let Err(e) = insert_well_known_bcmr(&tx, source, &bcmr) { - warn!("bcmr: Failed to insert an entry from well known source {}: {}", source, e); + warn!("bcmr: Failed to insert an entry from well known source {source}: {e}"); } } if let Err(e) = tx.commit() { - warn!("bcmr: Failed to update DB entries for {}: {}", source, e); + warn!("bcmr: Failed to update DB entries for {source}: {e}"); } } @@ -144,7 +144,7 @@ impl Drop for WellKnownDownloader { match thread.join() { Ok(_) => info!("bcmr well knownthread done"), - Err(e) => warn!("Failed to join bcmr wellknown thread: {:?}", e), + Err(e) => warn!("Failed to join bcmr wellknown thread: {e:?}"), } } } diff --git a/src/cashaddr/errors.rs b/src/cashaddr/errors.rs index a95653f..7f9c0b5 100644 --- a/src/cashaddr/errors.rs +++ b/src/cashaddr/errors.rs @@ -52,15 +52,15 @@ impl fmt::Display for DecodingError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { DecodingError::ChecksumFailed(actual) => { - write!(f, "invalid checksum (actual {} != 0)", actual) + write!(f, "invalid checksum (actual {actual} != 0)") } - DecodingError::InvalidChar(index) => write!(f, "invalid char ({})", index), + DecodingError::InvalidChar(index) => write!(f, "invalid char ({index})"), DecodingError::NoPrefix => write!(f, "zero or multiple prefixes"), DecodingError::MixedCase => write!(f, "mixed case string"), - DecodingError::InvalidVersion(c) => write!(f, "invalid version byte ({})", c), - DecodingError::InvalidPrefix(prefix) => write!(f, "invalid prefix ({})", prefix), - DecodingError::InvalidLength(length) => write!(f, "invalid length ({})", length), - DecodingError::Other(error) => write!(f, "other error ({})", error), + DecodingError::InvalidVersion(c) => write!(f, "invalid version byte ({c})"), + DecodingError::InvalidPrefix(prefix) => write!(f, "invalid prefix ({prefix})"), + DecodingError::InvalidLength(length) => write!(f, "invalid length ({length})"), + DecodingError::Other(error) => write!(f, "other error ({error})"), } } } diff --git a/src/cashaddr/mod.rs b/src/cashaddr/mod.rs index 396122c..11b9b93 100644 --- a/src/cashaddr/mod.rs +++ b/src/cashaddr/mod.rs @@ -190,8 +190,7 @@ pub fn decode(addr_str: &str) -> Result<(Vec, u8, Network), DecodingError> { 2 => (parts[0], parts[1]), _ => { return Err(DecodingError::Other(format!( - "Invalid address: '{}'", - addr_str + "Invalid address: '{addr_str}'" ))) } }; diff --git a/src/chain.rs b/src/chain.rs index f84011e..a86ed92 100644 --- a/src/chain.rs +++ b/src/chain.rs @@ -254,7 +254,7 @@ impl Chain { for (hash, header) in headers.drain(rewind as usize..) { let height = heights.remove(&hash).expect("heights map missing entry"); - info!("Chain: Undoing block {} (height {})", hash, height); + info!("Chain: Undoing block {hash} (height {height})"); undoer.undo_block(&header)?; } @@ -308,7 +308,7 @@ pub fn download_all_headers(electrum: &Client) -> Result> { let batch_end = std::cmp::min(batch_start + 999, tip); // Ensure we don't exceed the tip let mut batch = Batch::default(); - info!("Fetching headers {} -> {}", batch_start, batch_end); + info!("Fetching headers {batch_start} -> {batch_end}"); for height in batch_start..=batch_end { batch.raw( @@ -412,7 +412,7 @@ pub fn get_new_headers( } let header = download_block_header(electrum, &blockhash) - .context(format!("failed to get {} header", blockhash))?; + .context(format!("failed to get {blockhash} header"))?; blockhash = header.header.prev_blockhash; new_headers.push(header); } diff --git a/src/crc20/crc20fetcher.rs b/src/crc20/crc20fetcher.rs index 930cc50..ff71f34 100644 --- a/src/crc20/crc20fetcher.rs +++ b/src/crc20/crc20fetcher.rs @@ -80,7 +80,7 @@ impl CRC20Fetcher { let db = match db.get() { Ok(db) => db, Err(e) => { - warn!("Failed to get crc20 db connection {}", e); + warn!("Failed to get crc20 db connection {e}"); thread::sleep(LOOP_SLEEP_TIME); continue; } @@ -88,7 +88,7 @@ impl CRC20Fetcher { match get_not_indexed_tokens(&db) { Ok(tokens) => tokens, Err(e) => { - warn!("Failed to get unindexed crc20 tokens {}", e); + warn!("Failed to get unindexed crc20 tokens {e}"); thread::sleep(LOOP_SLEEP_TIME); continue; } @@ -114,7 +114,7 @@ impl CRC20Fetcher { { Ok(i) => Some(i), Err(e) => { - info!("Failed to fetch crc20 info for {}: {}", token, e); + info!("Failed to fetch crc20 info for {token}: {e}"); None } }; @@ -122,14 +122,14 @@ impl CRC20Fetcher { let db = match db.get() { Ok(db) => db, Err(e) => { - warn!("Failed to get crc20 db connection {}", e); + warn!("Failed to get crc20 db connection {e}"); break; } }; if genesis_info.is_none() { if let Err(e) = bump_failed_attempts(&db, &token) { - warn!("Failed to bump failed attempts for {}: {}", token, e); + warn!("Failed to bump failed attempts for {token}: {e}"); } continue; } @@ -143,7 +143,7 @@ impl CRC20Fetcher { }; if let Err(e) = res { - warn!("Failed to update crc20 for token {}: {}", token, e); + warn!("Failed to update crc20 for token {token}: {e}"); } } @@ -166,7 +166,7 @@ impl Drop for CRC20Fetcher { match thread.join() { Ok(_) => info!("crc20 fetcher thread done"), - Err(e) => warn!("Failed to join crc20 fetcher thread: {:?}", e), + Err(e) => warn!("Failed to join crc20 fetcher thread: {e:?}"), } } } diff --git a/src/db/bcmr/mod.rs b/src/db/bcmr/mod.rs index a724688..8b19f7c 100644 --- a/src/db/bcmr/mod.rs +++ b/src/db/bcmr/mod.rs @@ -169,8 +169,7 @@ pub fn get_matching_autheaders<'a>( for chunk in keys.chunks(chunk_size) { let in_clause = chunk.join("','"); let sql = format!( - "SELECT token_id, txid, height, bcmr_data, utxo FROM auth_chain_entry WHERE utxo IN ('{}')", - in_clause + "SELECT token_id, txid, height, bcmr_data, utxo FROM auth_chain_entry WHERE utxo IN ('{in_clause}')" ); let mut stmt = conn.prepare(&sql)?; @@ -334,10 +333,9 @@ pub fn update_bcmr_failure( attempts = bcmr_failure.attempts + 1, error_message = excluded.error_message, give_up = CASE - WHEN bcmr_failure.attempts + 1 > {} THEN true + WHEN bcmr_failure.attempts + 1 > {MAX_DOWNLOAD_ATTEMPTS} THEN true ELSE excluded.give_up - END", - MAX_DOWNLOAD_ATTEMPTS + END" ); conn.execute(&sql, params![&utxo.to_hex(), error_message, give_up])?; Ok(()) diff --git a/src/db/cauldron/header.rs b/src/db/cauldron/header.rs index d5fa373..f0b8c19 100644 --- a/src/db/cauldron/header.rs +++ b/src/db/cauldron/header.rs @@ -24,8 +24,7 @@ pub fn load_all_headers(conn: &Connection) -> Result> { for header in headers_iter { let (blob, height) = header?; headers.push(( - deserialize(&blob) - .unwrap_or_else(|_| panic!("Failed to deserialize header {}", height)), + deserialize(&blob).unwrap_or_else(|_| panic!("Failed to deserialize header {height}")), height, )); } diff --git a/src/db/cauldron/mempool.rs b/src/db/cauldron/mempool.rs index 783ea4d..b727997 100644 --- a/src/db/cauldron/mempool.rs +++ b/src/db/cauldron/mempool.rs @@ -33,10 +33,7 @@ where .map(|_| "?") .collect::>() .join(", "); - let query = format!( - "DELETE FROM tx WHERE txid IN ({}) AND blockhash is NULL", - placeholders - ); + let query = format!("DELETE FROM tx WHERE txid IN ({placeholders}) AND blockhash is NULL"); let params: Vec<&dyn rusqlite::ToSql> = txid_hexes .iter() diff --git a/src/db/cauldron/pool.rs b/src/db/cauldron/pool.rs index b59eb5e..4eb7471 100644 --- a/src/db/cauldron/pool.rs +++ b/src/db/cauldron/pool.rs @@ -15,12 +15,22 @@ use crate::{ use anyhow::{Context, Result}; use bitcoin_hashes::hex::{FromHex, ToHex}; use log::{debug, info, warn}; +use malachite::Integer; use riftenlabs_defi::{cauldron::ParsedContract, chainutil::OutPointHash}; use rusqlite::{params, Connection, Row}; use rust_decimal::prelude::Zero; +use serde::{Serialize, Serializer}; use crate::rpc::apy::PoolSnapshot; +// Custom serialization function for malachite::Integer +fn serialize_integer_as_string(integer: &Integer, serializer: S) -> Result +where + S: Serializer, +{ + serializer.serialize_str(&integer.to_string()) +} + pub fn create_table(conn: &Connection) { conn.execute( " @@ -374,7 +384,7 @@ pub fn get_pool_period_snapshot( let end_pool = match pools_end.remove(&start_pool_id) { Some(end) => end, None => { - warn!("Found no 'end pool' for {}", start_pool_id); + warn!("Found no 'end pool' for {start_pool_id}"); continue; } }; @@ -398,7 +408,8 @@ pub struct PoolHistoryEntry { sats: u64, token_amount: u64, timestamp: u64, - k: u128, + #[serde(serialize_with = "serialize_integer_as_string")] + k: Integer, } pub fn db_pool_history( @@ -427,7 +438,7 @@ pub fn db_pool_history( let sats = row.get(1)?; let token_amount = row.get(2)?; - let k = sats as u128 * token_amount as u128; + let k = Integer::from(sats) * Integer::from(token_amount); Ok(PoolHistoryEntry { txid: row.get(0)?, diff --git a/src/db/oracle/mod.rs b/src/db/oracle/mod.rs index 5866082..bd98c67 100644 --- a/src/db/oracle/mod.rs +++ b/src/db/oracle/mod.rs @@ -101,7 +101,7 @@ pub fn index_oracle(conn: &Connection, txs: &[Transaction], blockhash: &BlockHas oracle_sequence: update.sequence as i64, token_id: update.token_id.to_string(), }; - debug!("inserting delphi entry: {:?}", entry); + debug!("inserting delphi entry: {entry:?}"); insert_delphi_entry(conn, &entry)?; } } diff --git a/src/db/search/mod.rs b/src/db/search/mod.rs index 8c512d4..1757ab9 100644 --- a/src/db/search/mod.rs +++ b/src/db/search/mod.rs @@ -45,7 +45,7 @@ fn search_bcmr(bcmr_conn: &Connection, search_query: &str) -> Result = Vec::new(); @@ -83,7 +83,7 @@ fn search_crc20(crc20_conn: &Connection, search_query: &str) -> Result = Vec::new(); @@ -194,7 +194,7 @@ mod tests { let write_conn = mock_db.cauldron_w.get().unwrap(); match insert_mock_data(&write_conn) { Ok(_) => println!("Mock data inserted successfully."), - Err(e) => println!("Failed to insert mock data: {:?}", e), + Err(e) => println!("Failed to insert mock data: {e:?}"), } let token_id_hex = "dadadadadadadadadadadadadadadadada"; @@ -217,7 +217,7 @@ mod tests { let write_conn = mock_db.cauldron_w.get().unwrap(); match insert_mock_data(&write_conn) { Ok(_) => println!("Mock data inserted successfully."), - Err(e) => println!("Failed to insert mock data: {:?}", e), + Err(e) => println!("Failed to insert mock data: {e:?}"), } let token_id_hex = "dadadadadadadadadadadadadadadadadadadadadadadadadadadadadadadada"; @@ -241,7 +241,7 @@ mod tests { let write_conn = mock_db.cauldron_w.get().unwrap(); match insert_mock_data(&write_conn) { Ok(_) => println!("Mock data inserted successfully."), - Err(e) => println!("Failed to insert mock data: {:?}", e), + Err(e) => println!("Failed to insert mock data: {e:?}"), } let result: Vec<(String, Option, Option, u64)> = search_tokens_by_volume( @@ -251,7 +251,7 @@ mod tests { "", ) .expect("Failed to search tokens by volume"); - println!("Test Results: {:?}", result); + println!("Test Results: {result:?}"); assert_eq!(result.len(), 4); // We expect 4 tokens in total (3 BCMR + 1 CRC20) @@ -269,7 +269,7 @@ mod tests { let write_conn = mock_db.cauldron_w.get().unwrap(); match insert_mock_data(&write_conn) { Ok(_) => println!("Mock data inserted successfully."), - Err(e) => println!("Failed to insert mock data: {:?}", e), + Err(e) => println!("Failed to insert mock data: {e:?}"), } let result = search_tokens_by_volume( @@ -310,7 +310,7 @@ mod tests { match insert_mock_data(&write_conn) { Ok(_) => println!("Mock data inserted successfully."), - Err(e) => println!("Failed to insert mock data: {:?}", e), + Err(e) => println!("Failed to insert mock data: {e:?}"), } let token_tests = vec![ @@ -408,7 +408,7 @@ mod tests { filemeta: filemeta1, }; if let Err(e) = insert_bcmr_data(conn, &utxo1, &parsed_bcmr1) { - println!("Failed to insert BCMR data for token1: {:?}", e); + println!("Failed to insert BCMR data for token1: {e:?}"); } // Step 2: Insert Pool for token1 @@ -416,7 +416,7 @@ mod tests { let token_id1: TokenID = TokenID::from_inner([0xda; 32]); let cauldron1 = dummy_cauldron(&txid1, &utxo1, &token_id1, 1000, 500, &owner_pkh); if let Err(e) = insert_new_pool(conn, &cauldron1) { - println!("Failed to insert pool for token1: {:?}", e); + println!("Failed to insert pool for token1: {e:?}"); } // Step 3: Insert auth_chain_entry for token1 @@ -429,20 +429,20 @@ mod tests { 10, Some(Vec::from("bcmr_data1".as_bytes())), ) { - println!("Failed to insert auth_chain_entry for token1: {:?}", e); + println!("Failed to insert auth_chain_entry for token1: {e:?}"); } // Step 4: Insert the initial UTXO funding for token1 if let Err(e) = insert_utxo_funding(conn, &vec![cauldron1.clone()], &txid1, true) { - println!("Failed to insert initial UTXO funding for token1: {:?}", e); + println!("Failed to insert initial UTXO funding for token1: {e:?}"); } // Step 5: Insert the transaction for utxo1 if let Err(e) = insert_block_tx(conn, &txid1, &block_zero, thirty_days_ago) { - println!("Failed to insert block transaction for utxo1: {:?}", e); + println!("Failed to insert block transaction for utxo1: {e:?}"); } if let Err(e) = insert_mempool_tx(conn, &txid1, thirty_days_ago as u64) { - println!("Failed to insert mempool transaction for utxo1: {:?}", e); + println!("Failed to insert mempool transaction for utxo1: {e:?}"); } // Step 6: Simulate Volume - Insert second funding for token1 @@ -461,15 +461,15 @@ mod tests { }; if let Err(e) = insert_utxo_funding(conn, &vec![cauldron2.clone()], &txid2, true) { - println!("Failed to insert second UTXO funding for token1: {:?}", e); + println!("Failed to insert second UTXO funding for token1: {e:?}"); } // Step 7: Insert the transaction for utxo2 (spending utxo1) if let Err(e) = insert_block_tx(conn, &txid2, &block_zero, current_timestamp) { - println!("Failed to insert block transaction for utxo2: {:?}", e); + println!("Failed to insert block transaction for utxo2: {e:?}"); } if let Err(e) = insert_mempool_tx(conn, &txid2, current_timestamp as u64) { - println!("Failed to insert mempool transaction for utxo2: {:?}", e); + println!("Failed to insert mempool transaction for utxo2: {e:?}"); } // Step 8: Insert pool history entries for initial funding and spending @@ -480,10 +480,7 @@ mod tests { Some(thirty_days_ago as u64), Some(thirty_days_ago as u64), ) { - println!( - "Failed to insert pool history entry for initial funding of token1: {:?}", - e - ); + println!("Failed to insert pool history entry for initial funding of token1: {e:?}"); } if let Err(e) = insert_pool_history_entry( conn, @@ -492,10 +489,7 @@ mod tests { Some(current_timestamp as u64), Some(current_timestamp as u64), ) { - println!( - "Failed to insert pool history entry for spending of token1: {:?}", - e - ); + println!("Failed to insert pool history entry for spending of token1: {e:?}"); } // ================== TOKEN 2 (BCMR Token) ================== @@ -526,7 +520,7 @@ mod tests { filemeta: filemeta2, }; if let Err(e) = insert_bcmr_data(conn, &utxo2, &parsed_bcmr2) { - println!("Failed to insert BCMR data for token2: {:?}", e); + println!("Failed to insert BCMR data for token2: {e:?}"); } // Step 2: Insert Pool for token2 @@ -551,7 +545,7 @@ mod tests { 15, Some(Vec::from("bcmr_data2".as_bytes())), ) { - println!("Failed to insert auth_chain_entry for TOKEN 3: {:?}", e); + println!("Failed to insert auth_chain_entry for TOKEN 3: {e:?}"); }; // Step 3: Insert the initial UTXO funding for token2 @@ -637,7 +631,7 @@ mod tests { }; if let Err(e) = insert_bcmr_data(conn, &utxo3, &parsed_bcmr3) { - println!("Failed to insert BCMR data for TOKEN 3: {:?}", e); + println!("Failed to insert BCMR data for TOKEN 3: {e:?}"); } // Insert Pool for TOKEN 3 @@ -647,7 +641,7 @@ mod tests { dummy_cauldron(&txid3_initial, &utxo3, &token_id3, 1000, 500, &owner_pkh); if let Err(e) = insert_new_pool(conn, &cauldron3_initial) { - println!("Failed to insert pool for TOKEN 3: {:?}", e); + println!("Failed to insert pool for TOKEN 3: {e:?}"); } // Insert auth_chain_entry for TOKEN 3 @@ -660,28 +654,22 @@ mod tests { 20, Some(Vec::from("bcmr_data3".as_bytes())), ) { - println!("Failed to insert auth_chain_entry for TOKEN 3: {:?}", e); + println!("Failed to insert auth_chain_entry for TOKEN 3: {e:?}"); } // Insert the initial UTXO funding for TOKEN 3 (No additional funding to keep volume at 0) if let Err(e) = insert_utxo_funding(conn, &vec![cauldron3_initial.clone()], &txid3_initial, true) { - println!("Failed to insert initial UTXO funding for TOKEN 3: {:?}", e); + println!("Failed to insert initial UTXO funding for TOKEN 3: {e:?}"); } // Insert transaction for the initial funding without spending if let Err(e) = insert_block_tx(conn, &txid3_initial, &block_zero, thirty_days_ago) { - println!( - "Failed to insert block transaction for TOKEN 3 initial funding: {:?}", - e - ); + println!("Failed to insert block transaction for TOKEN 3 initial funding: {e:?}"); } if let Err(e) = insert_mempool_tx(conn, &txid3_initial, thirty_days_ago as u64) { - println!( - "Failed to insert mempool transaction for TOKEN 3 initial funding: {:?}", - e - ); + println!("Failed to insert mempool transaction for TOKEN 3 initial funding: {e:?}"); } // Insert pool history entry for the initial funding of TOKEN 3 (no spending history) @@ -692,10 +680,7 @@ mod tests { Some(thirty_days_ago as u64), Some(thirty_days_ago as u64), ) { - println!( - "Failed to insert pool history entry for TOKEN 3 initial funding: {:?}", - e - ); + println!("Failed to insert pool history entry for TOKEN 3 initial funding: {e:?}"); } // ================== TOKEN 4 (CRC20 Token with Volume) ================== @@ -724,21 +709,15 @@ mod tests { if let Err(e) = insert_utxo_funding(conn, &vec![cauldron4_initial.clone()], &txid4_initial, true) { - println!("Failed to insert initial UTXO funding for TOKEN 4: {:?}", e); + println!("Failed to insert initial UTXO funding for TOKEN 4: {e:?}"); } // Insert transaction for the initial funding if let Err(e) = insert_block_tx(conn, &txid4_initial, &block_zero, thirty_days_ago) { - println!( - "Failed to insert block transaction for TOKEN 4 initial funding: {:?}", - e - ); + println!("Failed to insert block transaction for TOKEN 4 initial funding: {e:?}"); } if let Err(e) = insert_mempool_tx(conn, &txid4_initial, thirty_days_ago as u64) { - println!( - "Failed to insert mempool transaction for TOKEN 4 initial funding: {:?}", - e - ); + println!("Failed to insert mempool transaction for TOKEN 4 initial funding: {e:?}"); } // Step 2: Insert second funding entry to simulate volume @@ -759,21 +738,15 @@ mod tests { if let Err(e) = insert_utxo_funding(conn, &vec![cauldron4_spent.clone()], &txid4_spend, true) { - println!("Failed to insert spent UTXO funding for TOKEN 4: {:?}", e); + println!("Failed to insert spent UTXO funding for TOKEN 4: {e:?}"); } // Insert transaction for the spending UTXO if let Err(e) = insert_block_tx(conn, &txid4_spend, &block_zero, current_timestamp) { - println!( - "Failed to insert block transaction for TOKEN 4 spending: {:?}", - e - ); + println!("Failed to insert block transaction for TOKEN 4 spending: {e:?}"); } if let Err(e) = insert_mempool_tx(conn, &txid4_spend, current_timestamp as u64) { - println!( - "Failed to insert mempool transaction for TOKEN 4 spending: {:?}", - e - ); + println!("Failed to insert mempool transaction for TOKEN 4 spending: {e:?}"); } // Step 3: Insert pool history entries for funding and spending @@ -784,10 +757,7 @@ mod tests { Some(thirty_days_ago as u64), Some(thirty_days_ago as u64), ) { - println!( - "Failed to insert pool history entry for TOKEN 4 initial funding: {:?}", - e - ); + println!("Failed to insert pool history entry for TOKEN 4 initial funding: {e:?}"); } if let Err(e) = insert_pool_history_entry( conn, @@ -796,10 +766,7 @@ mod tests { Some(current_timestamp as u64), Some(current_timestamp as u64), ) { - println!( - "Failed to insert pool history entry for TOKEN 4 spending: {:?}", - e - ); + println!("Failed to insert pool history entry for TOKEN 4 spending: {e:?}"); } Ok(()) diff --git a/src/electrum.rs b/src/electrum.rs index cfeb879..17a2e14 100644 --- a/src/electrum.rs +++ b/src/electrum.rs @@ -59,12 +59,12 @@ pub fn electrum_fetch_mempool(client: &Client) -> Result<(HashSet, HashSet Some(txid_hex) => match Txid::from_str(txid_hex) { Ok(txid) => Some(txid), Err(e) => { - info!("Txid not hex: {}", e); + info!("Txid not hex: {e}"); None } }, None => { - info!("Failed to read txid from electrum response {:?}", txid); + info!("Failed to read txid from electrum response {txid:?}"); None } }) diff --git a/src/index.rs b/src/index.rs index 5bd475e..469bf50 100644 --- a/src/index.rs +++ b/src/index.rs @@ -59,7 +59,7 @@ pub fn update_mempool( |txid| match electrum_get_tx(&electrum.lock().unwrap(), txid) { Ok(tx) => Some(tx), Err(e) => { - info!("Failed to get mempool tx {}: {}", txid, e); + info!("Failed to get mempool tx {txid}: {e}"); None } }, @@ -118,7 +118,7 @@ pub fn update_mempool( |txid| match electrum_get_tx(&electrum.lock().unwrap(), &txid) { Ok(tx) => Some(tx), Err(e) => { - info!("Failed to get mempool tx {}: {}", txid, e); + info!("Failed to get mempool tx {txid}: {e}"); None } }, @@ -200,7 +200,7 @@ pub fn index_blocks( loop { if tip_header.block_hash() == last_indexed { if let Err(e) = block_send.send(None) { - warn!("Failed to end EOL to block reader: {}", e); + warn!("Failed to end EOL to block reader: {e}"); } break; } @@ -227,7 +227,7 @@ pub fn index_blocks( chain.lock().unwrap().get_mtp(next_height).unwrap(), block, ))) { - warn!("Failed to send block to reader: {}", e); + warn!("Failed to send block to reader: {e}"); break; } diff --git a/src/main.rs b/src/main.rs index ed27843..9f642f3 100644 --- a/src/main.rs +++ b/src/main.rs @@ -66,23 +66,23 @@ fn set_panic_hook() { panic::set_hook(Box::new(|panic_info| { error!("A thread panicked, terminating the program."); if let Some(error) = panic_info.payload().downcast_ref::() { - error!("Panic occurred: {:?}", error); + error!("Panic occurred: {error:?}"); error!("Anyhow backtrace:\n{}", error.backtrace()); let mut source = error.source(); while let Some(cause) = source { - error!("Caused by: {:?}", cause); + error!("Caused by: {cause:?}"); source = cause.source(); } } else if let Some(message) = panic_info.payload().downcast_ref::<&str>() { - error!("Panic occurred: {}", message); + error!("Panic occurred: {message}"); } else if let Some(message) = panic_info.payload().downcast_ref::() { - error!("Panic occurred: {}", message); + error!("Panic occurred: {message}"); } else { - error!("Panic info: {:?}", panic_info); + error!("Panic info: {panic_info:?}"); } let backtrace = Backtrace::capture(); - error!("Backtrace (if RUST_BACKTRACE=1):\n{}", backtrace); + error!("Backtrace (if RUST_BACKTRACE=1):\n{backtrace}"); process::exit(1); })); } @@ -121,8 +121,7 @@ fn db_sanity_check(c: &rusqlite::Connection) -> rusqlite::Result<()> { let foreign_keys_enabled: i32 = stmt.query_row([], |row| row.get(0))?; if foreign_keys_enabled != 1 { panic!( - "Foreign key enforcement is not enabled for the connection. (result: {})", - foreign_keys_enabled + "Foreign key enforcement is not enabled for the connection. (result: {foreign_keys_enabled})" ); } Ok(()) @@ -134,7 +133,7 @@ fn start_program( let create_db_pool = |db_path| -> (bool, DBPool, DBPool) { let db_exists = Path::new(db_path).exists(); - info!("Initializing connection to {}", db_path); + info!("Initializing connection to {db_path}"); let write_manager = r2d2_sqlite::SqliteConnectionManager::file(db_path) .with_flags(OpenFlags::SQLITE_OPEN_READ_WRITE | OpenFlags::SQLITE_OPEN_CREATE) @@ -250,7 +249,7 @@ fn start_program( Ok(tip) => tip, Err(e) => { if e.to_string().contains("database is locked") { - warn!("initial index error, trying again: {}", e); + warn!("initial index error, trying again: {e}"); continue; } panic!("Initial index failed: {}\n {}", e, e.backtrace()); @@ -261,7 +260,7 @@ fn start_program( let new_tip = match electrum_get_tip(&client.lock().unwrap()) { Ok(t) => t.0.block_hash(), Err(e) => { - warn!("Failed to get block chain tip from electrum: {}", e); + warn!("Failed to get block chain tip from electrum: {e}"); thread::sleep(Duration::from_secs(5)); continue; } @@ -279,7 +278,7 @@ fn start_program( if let Err(e) = update_mempool(db.cauldron_w.clone(), db.oracle_w.clone(), client.clone()) { - error!("Failed to update mempool: {}", e); + error!("Failed to update mempool: {e}"); } thread::sleep(Duration::from_secs(5)); } @@ -311,8 +310,8 @@ fn launch() -> _ { Ok(db) => db, Err(e) => { let backtrace = Backtrace::capture(); - error!("Backtrace (if RUST_BACKTRACE=1):\n{}", backtrace); - error!("Error: {}", e); + error!("Backtrace (if RUST_BACKTRACE=1):\n{backtrace}"); + error!("Error: {e}"); panic!("Failed at program startup") } }; diff --git a/src/rpc/apy/mod.rs b/src/rpc/apy/mod.rs index edf2f95..6a0cd76 100644 --- a/src/rpc/apy/mod.rs +++ b/src/rpc/apy/mod.rs @@ -63,20 +63,20 @@ pub fn aggregate_apy( let conn = db .cauldron_r .get() - .map_err(|e| Custom(Status::InternalServerError, format!("DB error: {}", e)))?; + .map_err(|e| Custom(Status::InternalServerError, format!("DB error: {e}")))?; let pools: anyhow::Result> = get_pool_period_snapshot(&conn, token, pkh, start, end) - .map_err(|e| Custom(Status::InternalServerError, format!("Error: {}", e)))? + .map_err(|e| Custom(Status::InternalServerError, format!("Error: {e}")))? .into_iter() .map(|(start, end)| PoolPeriod::new(start, end)) .collect(); - let pools = pools.map_err(|e| Custom(Status::InternalServerError, format!("Error: {}", e)))?; + let pools = pools.map_err(|e| Custom(Status::InternalServerError, format!("Error: {e}")))?; let pools_count = pools.len(); let apy = apyaggregator::APYAggregator::aggregate_apy(pools.into_iter(), Some(start as u64)) - .map_err(|e| Custom(Status::InternalServerError, format!("Error: {}", e)))?; + .map_err(|e| Custom(Status::InternalServerError, format!("Error: {e}")))?; Ok(Json(json!({ "apy": apy.to_string(), diff --git a/src/rpc/apy/poolperiod.rs b/src/rpc/apy/poolperiod.rs index b070771..b3540cc 100644 --- a/src/rpc/apy/poolperiod.rs +++ b/src/rpc/apy/poolperiod.rs @@ -135,9 +135,7 @@ mod tests { assert!((expected_yield - pool_yield).abs() < dec!(1e-12)); assert!( (expected_apy - pool_apy).abs() < dec!(1e-7), - "expected {} != actual {}", - expected_apy, - pool_apy + "expected {expected_apy} != actual {pool_apy}" ); } } diff --git a/src/rpc/bcmr.rs b/src/rpc/bcmr.rs index cb6f0ed..a8b9bbc 100644 --- a/src/rpc/bcmr.rs +++ b/src/rpc/bcmr.rs @@ -18,17 +18,17 @@ use crate::db::{bcmr::get_token_bcmr, DB}; pub fn token_bcmr(category: Option<&str>, db: &State) -> Result, Custom> { let token_id_hex = category .context("category missing") - .map_err(|e| Custom(Status::BadRequest, format!("Error: {}", e)))?; + .map_err(|e| Custom(Status::BadRequest, format!("Error: {e}")))?; // validate input by parsing it into TokenID let token_id = TokenID::from_hex(token_id_hex) - .map_err(|e| Custom(Status::BadRequest, format!("Error: {}", e)))?; + .map_err(|e| Custom(Status::BadRequest, format!("Error: {e}")))?; let conn = db .bcmr_r .get() - .map_err(|e| Custom(Status::InternalServerError, format!("Error: {}", e)))?; + .map_err(|e| Custom(Status::InternalServerError, format!("Error: {e}")))?; let bcmr = get_token_bcmr(&conn, &token_id.to_hex()) - .map_err(|e| Custom(Status::InternalServerError, format!("Error: {}", e)))?; + .map_err(|e| Custom(Status::InternalServerError, format!("Error: {e}")))?; Ok(Json(json!(bcmr))) } @@ -41,21 +41,21 @@ pub fn token_bcmr_all( ) -> Result, Custom> { let token_id_hex = category .context("category missing") - .map_err(|e| Custom(Status::BadRequest, format!("Error: {}", e)))?; + .map_err(|e| Custom(Status::BadRequest, format!("Error: {e}")))?; // validate input by parsing it into TokenID let token_id = TokenID::from_hex(token_id_hex) - .map_err(|e| Custom(Status::BadRequest, format!("Error: {}", e)))?; + .map_err(|e| Custom(Status::BadRequest, format!("Error: {e}")))?; let conn = db .bcmr_r .get() - .map_err(|e| Custom(Status::InternalServerError, format!("Error: {}", e)))?; + .map_err(|e| Custom(Status::InternalServerError, format!("Error: {e}")))?; let onchain_bcmr = get_token_bcmr(&conn, &token_id.to_hex()) - .map_err(|e| Custom(Status::InternalServerError, format!("Error: {}", e)))?; + .map_err(|e| Custom(Status::InternalServerError, format!("Error: {e}")))?; let mut bcmr_entries = get_well_known_bcmr(&conn, &token_id.to_hex()) - .map_err(|e| Custom(Status::InternalServerError, format!("Error: {}", e)))?; + .map_err(|e| Custom(Status::InternalServerError, format!("Error: {e}")))?; if let Some(bcmr) = onchain_bcmr { bcmr_entries.push(bcmr) diff --git a/src/rpc/candlesticks.rs b/src/rpc/candlesticks.rs index ffdc4ab..f8def33 100644 --- a/src/rpc/candlesticks.rs +++ b/src/rpc/candlesticks.rs @@ -255,17 +255,14 @@ pub fn price_candlesticks( if total_intervals > MAX_INTERVALS { return Err(Custom( Status::BadRequest, - format!( - "Too many intervals ({} > {})", - total_intervals, MAX_INTERVALS - ), + format!("Too many intervals ({total_intervals} > {MAX_INTERVALS})"), )); } let db = conn .cauldron_r .get() - .map_err(|e| Custom(Status::InternalServerError, format!("Error: {}", e)))?; + .map_err(|e| Custom(Status::InternalServerError, format!("Error: {e}")))?; let candlesticks = candlesticks( &db, @@ -274,7 +271,7 @@ pub fn price_candlesticks( stepsize.unwrap_or(3600), // default 1 hour token, ) - .map_err(|e| Custom(Status::BadRequest, format!("Error: {}", e)))?; + .map_err(|e| Custom(Status::BadRequest, format!("Error: {e}")))?; let candlesticks_json: Vec = candlesticks .iter() @@ -336,13 +333,13 @@ mod tests { pkh: &PubkeyHash, ) -> ParsedContract { ParsedContract { - pkh: pkh.clone(), + pkh: *pkh, is_withdrawn: false, spent_utxo_hash: OutPointHash::all_zeros(), - new_utxo_hash: Some(utxo.clone()), - new_utxo_txid: Some(txid.clone()), + new_utxo_hash: Some(*utxo), + new_utxo_txid: Some(*txid), new_utxo_n: Some(0), - token_id: Some(token.clone()), + token_id: Some(*token), sats: Some(sats), token_amount: Some(tokens), } @@ -448,8 +445,7 @@ mod tests { let response = client .get(format!( - "/api/price/{}/candlesticks?end={}", - token_id_zero, future_end + "/api/price/{token_id_zero}/candlesticks?end={future_end}" )) .dispatch(); @@ -473,8 +469,7 @@ mod tests { let response = client .get(format!( - "/api/price/{}/candlesticks?start={}", - token_id_zero, start_after_end + "/api/price/{token_id_zero}/candlesticks?start={start_after_end}" )) .dispatch(); @@ -501,8 +496,7 @@ mod tests { // This yields 2 candles: one in [3300..3900), another in [3900..4500). let response = client .get(format!( - "/api/price/{}/candlesticks?start=1727963300&end=1727964500&stepsize=600", - token_id_zero + "/api/price/{token_id_zero}/candlesticks?start=1727963300&end=1727964500&stepsize=600" )) .dispatch(); @@ -516,7 +510,7 @@ mod tests { // ----- Candle #1 ----- let cndl1 = &cndl_array[0]; - println!("First candlestick: {:?}", cndl1); + println!("First candlestick: {cndl1:?}"); // Candle #1 => time=1727963300 // trades at 1727963300 => ratio=40, 1727963600 => ratio=60 // open=40, close=60, low=40, high=60, volume_sats=200k, volume_tokens=4k, transaction_count=2 @@ -531,7 +525,7 @@ mod tests { // ----- Candle #2 ----- let cndl2 = &cndl_array[1]; - println!("Second candlestick: {:?}", cndl2); + println!("Second candlestick: {cndl2:?}"); // Candle #2 => time=1727963900 // trades at 1727963900 => ratio=80, 1727964200 => ratio=100 // open=80, close=100, low=80, high=100, volume_sats=360k, volume_tokens=4k, transaction_count=2 @@ -586,15 +580,15 @@ mod tests { // Insert a tx row for the transaction insert_block_tx(conn, &txid_multi, &block_zero, time as i64).unwrap(); - insert_mempool_tx(conn, &txid_multi, time as u64).unwrap(); + insert_mempool_tx(conn, &txid_multi, time).unwrap(); // Insert pool_history_entry for each pool related to the transaction pool::insert_pool_history_entry( conn, &pool_hash, &cauldron, - Some(time as u64), - Some(time as u64), + Some(time), + Some(time), ) .unwrap(); } diff --git a/src/rpc/contract.rs b/src/rpc/contract.rs index cacd00c..3858d5b 100644 --- a/src/rpc/contract.rs +++ b/src/rpc/contract.rs @@ -74,9 +74,9 @@ pub fn contract_count_all(conn: &State) -> Result, Custom) -> Result let db = conn .cauldron_r .get() - .map_err(|e| Custom(Status::InternalServerError, format!("Error: {}", e)))?; + .map_err(|e| Custom(Status::InternalServerError, format!("Error: {e}")))?; let count = db_contract_count_by_token(&db, token) - .map_err(|e| Custom(Status::BadRequest, format!("Error: {}", e)))?; + .map_err(|e| Custom(Status::BadRequest, format!("Error: {e}")))?; Ok(Json(json!(count))) } @@ -104,9 +104,9 @@ pub fn contract_volume( let db = conn .cauldron_r .get() - .map_err(|e| Custom(Status::InternalServerError, format!("Error: {}", e)))?; + .map_err(|e| Custom(Status::InternalServerError, format!("Error: {e}")))?; let volume = super::contract_volume(&db, end_timestamp as u64) - .map_err(|e| Custom(Status::BadRequest, format!("Error: {}", e)))?; + .map_err(|e| Custom(Status::BadRequest, format!("Error: {e}")))?; let result: Vec = volume .into_par_iter() diff --git a/src/rpc/err.rs b/src/rpc/err.rs index f1d379b..367e1a4 100644 --- a/src/rpc/err.rs +++ b/src/rpc/err.rs @@ -6,5 +6,5 @@ use rocket::{http::Status, response::status::Custom}; pub fn to_internal_error(e: E) -> Custom { - Custom(Status::InternalServerError, format!("Error: {}", e)) + Custom(Status::InternalServerError, format!("Error: {e}")) } diff --git a/src/rpc/oracle.rs b/src/rpc/oracle.rs index 0cc554a..0e38501 100644 --- a/src/rpc/oracle.rs +++ b/src/rpc/oracle.rs @@ -28,7 +28,7 @@ pub fn oracle_get_closest( let token_id = token_id .map(|t| { TokenID::from_hex(&t) - .map_err(|e| Custom(Status::BadRequest, format!("Invalid token ID: {}", e))) + .map_err(|e| Custom(Status::BadRequest, format!("Invalid token ID: {e}"))) }) .transpose()?; let entry = get_closest(&conn, &token_id, current_timestamp) @@ -54,7 +54,7 @@ pub fn oracle_get_range( let token_id = token_id .map(|t| { TokenID::from_hex(&t) - .map_err(|e| Custom(Status::BadRequest, format!("Invalid token ID: {}", e))) + .map_err(|e| Custom(Status::BadRequest, format!("Invalid token ID: {e}"))) }) .transpose()?; let entries = get_range(&conn, &token_id, start_timestamp, end_timestamp) @@ -80,21 +80,21 @@ pub fn oracle_get_history( let conn = db .oracle_r .get() - .map_err(|e| Custom(Status::InternalServerError, format!("DB error: {}", e)))?; + .map_err(|e| Custom(Status::InternalServerError, format!("DB error: {e}")))?; let token_id = token .parse::() - .map_err(|e| Custom(Status::BadRequest, format!("Invalid token ID: {}", e)))?; + .map_err(|e| Custom(Status::BadRequest, format!("Invalid token ID: {e}")))?; let start_ts = start.unwrap_or(current_timestamp - 30 * 24 * 3600); // default: 30 days ago let end_ts = end.unwrap_or(current_timestamp); let entries = if let Some(step) = stepsize { get_range_with_step(&conn, &Some(token_id), start_ts, end_ts, step) - .map_err(|e| Custom(Status::BadRequest, format!("Query error: {}", e)))? + .map_err(|e| Custom(Status::BadRequest, format!("Query error: {e}")))? } else { get_range(&conn, &Some(token_id), start_ts, end_ts) - .map_err(|e| Custom(Status::BadRequest, format!("Query error: {}", e)))? + .map_err(|e| Custom(Status::BadRequest, format!("Query error: {e}")))? }; let json_entries: Vec = entries diff --git a/src/rpc/pool.rs b/src/rpc/pool.rs index 2e26ef6..35963b0 100644 --- a/src/rpc/pool.rs +++ b/src/rpc/pool.rs @@ -146,10 +146,10 @@ pub fn list_pools_by_apy(conn: &State) -> Result, Custom let db = conn .cauldron_r .get() - .map_err(|e| Custom(Status::InternalServerError, format!("Error: {}", e)))?; + .map_err(|e| Custom(Status::InternalServerError, format!("Error: {e}")))?; let pools: Vec = - pools_by_apy(&db).map_err(|e| Custom(Status::BadRequest, format!("Error: {}", e)))?; + pools_by_apy(&db).map_err(|e| Custom(Status::BadRequest, format!("Error: {e}")))?; Ok(Json(json!({ "pools": json!(pools) @@ -165,14 +165,14 @@ pub fn list_active_pools( let db = conn .cauldron_r .get() - .map_err(|e| Custom(Status::InternalServerError, format!("Error: {}", e)))?; + .map_err(|e| Custom(Status::InternalServerError, format!("Error: {e}")))?; if token.is_none() && pkh.is_none() { return Err(Custom(Status::BadRequest, "Provide token or pkh".into())); } let active = db_list_active_pools(token, pkh, &db, true) - .map_err(|e| Custom(Status::InternalServerError, format!("Error: {}", e)))?; + .map_err(|e| Custom(Status::InternalServerError, format!("Error: {e}")))?; Ok(Json(json!({ "active": active, @@ -188,18 +188,18 @@ pub fn pool_history( let db = conn .cauldron_r .get() - .map_err(|e| Custom(Status::InternalServerError, format!("Error: {}", e)))?; + .map_err(|e| Custom(Status::InternalServerError, format!("Error: {e}")))?; let start = start.unwrap_or(time_now() as u64 - (30 * 3600 * 24) /* 30 days ago */); let pool_id = PoolID::from_hex(pool_id) - .map_err(|e| Custom(Status::BadRequest, format!("Invalid pool ID: {}", e)))?; + .map_err(|e| Custom(Status::BadRequest, format!("Invalid pool ID: {e}")))?; let (token_id, owner_pkh) = db_pool_get_details(&db, &pool_id) - .map_err(|e| Custom(Status::BadRequest, format!("Error: {}", e)))?; + .map_err(|e| Custom(Status::BadRequest, format!("Error: {e}")))?; let history = db_pool_history(&db, &pool_id, start) - .map_err(|e| Custom(Status::InternalServerError, format!("Error: {}", e)))?; + .map_err(|e| Custom(Status::InternalServerError, format!("Error: {e}")))?; Ok(Json(json!({ "history": history, diff --git a/src/rpc/price.rs b/src/rpc/price.rs index 5d65135..469f56d 100644 --- a/src/rpc/price.rs +++ b/src/rpc/price.rs @@ -264,7 +264,7 @@ pub fn price_at( let db = conn .cauldron_r .get() - .map_err(|e| Custom(Status::InternalServerError, format!("Error: {}", e)))?; + .map_err(|e| Custom(Status::InternalServerError, format!("Error: {e}")))?; let current_time = time_now(); if timestamp > current_time { @@ -273,8 +273,8 @@ pub fn price_at( "Timestamp is in the future".to_string(), )); } - let token = TokenID::from_hex(token) - .map_err(|e| Custom(Status::BadRequest, format!("Error: {}", e)))?; + let token = + TokenID::from_hex(token).map_err(|e| Custom(Status::BadRequest, format!("Error: {e}")))?; match price_at_or_before(&db, timestamp, &token) { Ok((latest_timestamp, price)) => Ok(Json(json!({ @@ -283,7 +283,7 @@ pub fn price_at( }))), Err(e) => Err(Custom( Status::InternalServerError, - format!("Error fetching price: {}", e), + format!("Error fetching price: {e}"), )), } } @@ -293,10 +293,10 @@ pub fn price_current(token: &str, conn: &State) -> Result, Custo let db = conn .cauldron_r .get() - .map_err(|e| Custom(Status::InternalServerError, format!("Error: {}", e)))?; + .map_err(|e| Custom(Status::InternalServerError, format!("Error: {e}")))?; let price = current_price(&db, token) - .map_err(|e| Custom(Status::InternalServerError, format!("Error: {}", e)))?; + .map_err(|e| Custom(Status::InternalServerError, format!("Error: {e}")))?; Ok(Json(json!({ "price": price, @@ -316,7 +316,7 @@ pub fn price_history( let db = conn .cauldron_r .get() - .map_err(|e| Custom(Status::InternalServerError, format!("Error: {}", e)))?; + .map_err(|e| Custom(Status::InternalServerError, format!("Error: {e}")))?; let history = historic_price( &db, @@ -325,7 +325,7 @@ pub fn price_history( stepsize.unwrap_or(3600 /* 1 hour */), token, ) - .map_err(|e| Custom(Status::BadRequest, format!("Error: {}", e)))?; + .map_err(|e| Custom(Status::BadRequest, format!("Error: {e}")))?; let history_json: Vec = history .iter() @@ -528,7 +528,7 @@ mod tests { // Test 1: Querying at a timestamp that exactly matches test_txid1 let timestamp = TIME_1; let response = client - .get(format!("/cauldron/price/{}/at/{}", token_id, timestamp)) + .get(format!("/cauldron/price/{token_id}/at/{timestamp}")) .dispatch(); assert_eq!(response.status(), Status::Ok); @@ -545,7 +545,7 @@ mod tests { // Test 2: Querying at a timestamp that includes Pool 1 and Pool 2 let timestamp = TIME_2; let response = client - .get(format!("/cauldron/price/{}/at/{}", token_id, timestamp)) + .get(format!("/cauldron/price/{token_id}/at/{timestamp}")) .dispatch(); assert_eq!(response.status(), Status::Ok); let json_value: serde_json::Value = @@ -558,15 +558,13 @@ mod tests { let expected_price = 36.67; assert!( (actual_price - expected_price).abs() < 0.01, - "expected {} != actual {}", - expected_price, - actual_price + "expected {expected_price} != actual {actual_price}" ); // Test 3: Querying a timestamp that includes Pool 1, Pool 2, and Pool 3 let timestamp = TIME_3; let response = client - .get(format!("/cauldron/price/{}/at/{}", token_id, timestamp)) + .get(format!("/cauldron/price/{token_id}/at/{timestamp}")) .dispatch(); assert_eq!(response.status(), Status::Ok); let json_value: serde_json::Value = @@ -595,7 +593,7 @@ mod tests { // Test: Query at a newer timestamp (1727963500) for pool1 and ensure it only accounts for the newer entry let timestamp = 1727963500; // Newer timestamp let response = client - .get(format!("/cauldron/price/{}/at/{}", token_id, timestamp)) + .get(format!("/cauldron/price/{token_id}/at/{timestamp}")) .dispatch(); assert_eq!(response.status(), Status::Ok); @@ -609,9 +607,7 @@ mod tests { let expected_price = 33.85; // Rounded to 2 decimal places assert!( (actual_price - expected_price).abs() < 0.01, - "expected {} != actual {}", - expected_price, - actual_price + "expected {expected_price} != actual {actual_price}" ); } @@ -648,7 +644,7 @@ mod tests { // Test: Query at the timestamp matching test_txid1 (1727963300) and check the price let timestamp = TIME_1; let response = client - .get(format!("/cauldron/price/{}/at/{}", token_id, timestamp)) + .get(format!("/cauldron/price/{token_id}/at/{timestamp}")) .dispatch(); assert_eq!(response.status(), Status::Ok); @@ -678,7 +674,7 @@ mod tests { let timestamp = 1727963432; // Arbitrary timestamp let response = client - .get(format!("/cauldron/price/{}/at/{}", bad_token_id, timestamp)) + .get(format!("/cauldron/price/{bad_token_id}/at/{timestamp}")) .dispatch(); assert_eq!(response.status(), Status::BadRequest); } @@ -697,10 +693,7 @@ mod tests { let future_timestamp = (time_now() + 100000).to_string(); let response = client - .get(format!( - "/cauldron/price/{}/at/{}", - token_id, future_timestamp - )) + .get(format!("/cauldron/price/{token_id}/at/{future_timestamp}")) .dispatch(); assert_eq!(response.status(), Status::BadRequest); @@ -723,10 +716,7 @@ mod tests { let invalid_timestamp = "ASDASD:"; let response = client - .get(format!( - "/cauldron/price/{}/at/{}", - token_id, invalid_timestamp - )) + .get(format!("/cauldron/price/{token_id}/at/{invalid_timestamp}")) .dispatch(); assert_eq!(response.status(), Status::BadRequest); diff --git a/src/rpc/tokens.rs b/src/rpc/tokens.rs index cd283f5..46b0605 100644 --- a/src/rpc/tokens.rs +++ b/src/rpc/tokens.rs @@ -74,7 +74,7 @@ pub fn list_by_volume( } }; if needs_update { - info!("Update for {} triggered.", cache_key); + info!("Update for {cache_key} triggered."); if let Some(entry) = response_cache.lock().unwrap().get_mut(&cache_key) { entry.in_progress = true; }; @@ -88,7 +88,7 @@ pub fn list_by_volume( update_timestamp: time_now(), }, Err(e) => { - warn!("Failed to update cache for {}: {:?}", cache_key, e); + warn!("Failed to update cache for {cache_key}: {e:?}"); ResponseCacheInner { value: None, in_progress: false, @@ -100,7 +100,7 @@ pub fn list_by_volume( .lock() .unwrap() .insert(cache_key.clone(), new_entry); - info!("Updated cached value for {}", cache_key); + info!("Updated cached value for {cache_key}"); }); } @@ -131,7 +131,7 @@ pub fn search_by_volume( &crc20_db, search_query, ) - .map_err(|e| Custom(Status::InternalServerError, format!("Error: {}", e)))?; + .map_err(|e| Custom(Status::InternalServerError, format!("Error: {e}")))?; let result: Vec = list .into_par_iter() diff --git a/src/rpc/tvl.rs b/src/rpc/tvl.rs index d827bca..73c9d91 100644 --- a/src/rpc/tvl.rs +++ b/src/rpc/tvl.rs @@ -96,10 +96,10 @@ pub fn deprecated_tvl(time: usize, conn: &State) -> Result>, let db = conn .cauldron_r .get() - .map_err(|e| Custom(Status::InternalServerError, format!("Error: {}", e)))?; + .map_err(|e| Custom(Status::InternalServerError, format!("Error: {e}")))?; let tvl: Vec<(String, u64, u64)> = get_all_token_tvl(&db, time) - .map_err(|e| Custom(Status::InternalServerError, format!("Error: {}", e)))?; + .map_err(|e| Custom(Status::InternalServerError, format!("Error: {e}")))?; let result: Vec = tvl .into_par_iter() @@ -130,7 +130,7 @@ pub fn valuelocked_all( let time_filter = time.unwrap_or_else(|| time_now() as usize); let tvl: Vec<(String, u64, u64)> = get_all_token_tvl(&db, time_filter) - .map_err(|e| Custom(Status::InternalServerError, format!("Error: {}", e)))?; + .map_err(|e| Custom(Status::InternalServerError, format!("Error: {e}")))?; let result: Vec = tvl .into_par_iter() @@ -162,7 +162,7 @@ pub fn valuelocked_token( let time_filter = time.unwrap_or_else(|| time_now() as usize); let (sats, token_amount) = get_token_tvl(&db, time_filter, token) - .map_err(|e| Custom(Status::InternalServerError, format!("Error: {}", e)))?; + .map_err(|e| Custom(Status::InternalServerError, format!("Error: {e}")))?; Ok(Json(json!({ "token_amount": token_amount, diff --git a/src/rpc/tx.rs b/src/rpc/tx.rs index d6a55c2..be972e4 100644 --- a/src/rpc/tx.rs +++ b/src/rpc/tx.rs @@ -37,7 +37,7 @@ pub fn tx_latest( }; let txs = crate::db::cauldron::tx::latest(&db, limit, offset, token) - .map_err(|e| Custom(Status::InternalServerError, format!("Error: {}", e)))?; + .map_err(|e| Custom(Status::InternalServerError, format!("Error: {e}")))?; let txs_json: Vec = txs .into_iter() diff --git a/src/rpc/user.rs b/src/rpc/user.rs index 56a15f9..4285ad8 100644 --- a/src/rpc/user.rs +++ b/src/rpc/user.rs @@ -20,7 +20,7 @@ pub fn unique_addresses(conn: &State) -> Result, Custom> })?; let users = get_unique_per_month_accumilating(&db) - .map_err(|e| Custom(Status::InternalServerError, format!("Error: {}", e)))?; + .map_err(|e| Custom(Status::InternalServerError, format!("Error: {e}")))?; Ok(Json(json!(users))) }