From e8f7226258345bf387f0f261dfda59ade781ee16 Mon Sep 17 00:00:00 2001 From: arkanoider Date: Wed, 26 Feb 2025 22:01:37 +0100 Subject: [PATCH 1/4] remove of anyhow dependency start --- Cargo.lock | 2 -- Cargo.toml | 3 +++ src/app/add_invoice.rs | 2 -- src/app/admin_add_solver.rs | 1 - src/app/rate_user.rs | 1 - src/app/take_buy.rs | 1 - src/app/take_sell.rs | 1 - src/bitcoin_price.rs | 14 ++++++++------ src/cli.rs | 9 ++++----- src/cli/settings.rs | 29 +++++++++++++++-------------- src/lightning/mod.rs | 1 - src/messages.rs | 2 -- src/scheduler.rs | 8 +++++--- src/util.rs | 2 +- 14 files changed, 36 insertions(+), 40 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 84316dce..b44cac58 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1976,8 +1976,6 @@ dependencies = [ [[package]] name = "mostro-core" version = "0.6.28" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc439d283bc64ae1d8b6d7f83994ceec750f402d3e7515c97757ba684271eef4" dependencies = [ "anyhow", "bitcoin", diff --git a/Cargo.toml b/Cargo.toml index 09b44b15..c1437b65 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -50,3 +50,6 @@ bitcoin = "0.32.5" [dev-dependencies] tokio = { version = "1.40.0", features = ["full", "test-util", "macros"] } + +[patch.crates-io] +mostro-core = { path = "../mostro-core" } \ No newline at end of file diff --git a/src/app/add_invoice.rs b/src/app/add_invoice.rs index cc1bae5b..4ef97639 100644 --- a/src/app/add_invoice.rs +++ b/src/app/add_invoice.rs @@ -2,8 +2,6 @@ use crate::util::{ enqueue_order_msg, get_order, show_hold_invoice, update_order_event, validate_invoice, }; -use anyhow::Result; - use mostro_core::error::MostroError::{self, *}; use mostro_core::error::{CantDoReason, ServiceError}; use mostro_core::message::{Action, Message, Payload}; diff --git a/src/app/admin_add_solver.rs b/src/app/admin_add_solver.rs index 1a97db02..a5047c69 100644 --- a/src/app/admin_add_solver.rs +++ b/src/app/admin_add_solver.rs @@ -1,7 +1,6 @@ use crate::db::add_new_user; use crate::util::send_dm; -use anyhow::Result; use mostro_core::error::{ MostroError::{self, *}, ServiceError, diff --git a/src/app/rate_user.rs b/src/app/rate_user.rs index 679015bf..9743f5e5 100644 --- a/src/app/rate_user.rs +++ b/src/app/rate_user.rs @@ -1,7 +1,6 @@ use crate::util::{enqueue_order_msg, get_order, update_user_rating_event}; use crate::db::{is_user_present, update_user_rating}; -use anyhow::Result; use mostro_core::error::MostroError::{self, *}; use mostro_core::error::{CantDoReason, ServiceError}; use mostro_core::message::{Action, Message, Payload}; diff --git a/src/app/take_buy.rs b/src/app/take_buy.rs index 6fbaa308..7f885730 100644 --- a/src/app/take_buy.rs +++ b/src/app/take_buy.rs @@ -3,7 +3,6 @@ use crate::util::{ }; use crate::db::{seller_has_pending_order, update_user_trade_index}; -use anyhow::Result; use mostro_core::error::MostroError::{self, *}; use mostro_core::error::{CantDoReason, ServiceError}; use mostro_core::message::Message; diff --git a/src/app/take_sell.rs b/src/app/take_sell.rs index 681881cd..adb1a644 100644 --- a/src/app/take_sell.rs +++ b/src/app/take_sell.rs @@ -7,7 +7,6 @@ use mostro_core::error::MostroError::{self, *}; use mostro_core::error::{CantDoReason, ServiceError}; use crate::db::{buyer_has_pending_order, update_user_trade_index}; -use anyhow::Result; use mostro_core::message::Message; use mostro_core::order::{Order, Status}; use nostr::nips::nip59::UnwrappedGift; diff --git a/src/bitcoin_price.rs b/src/bitcoin_price.rs index af9b222b..4afe62f6 100644 --- a/src/bitcoin_price.rs +++ b/src/bitcoin_price.rs @@ -1,5 +1,7 @@ -use anyhow::Result; + use once_cell::sync::Lazy; +use mostro_core::error::MostroError::{self, *}; +use mostro_core::error::ServiceError; use serde::Deserialize; use std::collections::HashMap; use std::sync::RwLock; @@ -19,21 +21,21 @@ static BITCOIN_PRICES: Lazy>> = pub struct BitcoinPriceManager; impl BitcoinPriceManager { - pub async fn update_prices() -> Result<()> { - let response = reqwest::get(YADIO_API_URL).await?; - let yadio_response: YadioResponse = response.json().await?; + pub async fn update_prices() -> Result<(), MostroError> { + let response = reqwest::get(YADIO_API_URL).await.map_err(|e| MostroInternalErr(ServiceError::NoAPIResponse))?; + let yadio_response: YadioResponse = response.json().await.map_err(|e| MostroInternalErr(ServiceError::MessageSerializationError))?; info!( "Bitcoin prices updated. Got BTC price in {} fiat currencies", yadio_response.btc.keys().collect::>().len() ); - let mut prices_write = BITCOIN_PRICES.write().unwrap(); + let mut prices_write = BITCOIN_PRICES.write().map_err(|e| MostroInternalErr(ServiceError::IOError(e.to_string())))?; *prices_write = yadio_response.btc; Ok(()) } pub fn get_price(currency: &str) -> Option { - let prices_read = BITCOIN_PRICES.read().unwrap(); + let prices_read = BITCOIN_PRICES.read().map_err(|e| MostroInternalErr(ServiceError::IOError(e.to_string())))?; prices_read.get(currency).cloned() } } diff --git a/src/cli.rs b/src/cli.rs index 1a4aefc3..a0f65086 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -1,8 +1,7 @@ pub mod settings; use crate::cli::settings::init_default_dir; - -use anyhow::Result; +use mostro_core::error::MostroError; use clap::Parser; use std::path::PathBuf; @@ -30,12 +29,12 @@ pub struct Cli { dirsettings: Option, } -pub fn settings_init() -> Result { +pub fn settings_init() -> Result { let cli = Cli::parse(); if let Some(path) = cli.dirsettings.as_deref() { - init_default_dir(Some(path.to_string())) + Ok(init_default_dir(Some(path.to_string()))?) } else { - init_default_dir(None) + Ok(init_default_dir(None)?) } } diff --git a/src/cli/settings.rs b/src/cli/settings.rs index 1c4dc8ce..9279e004 100644 --- a/src/cli/settings.rs +++ b/src/cli/settings.rs @@ -1,6 +1,7 @@ use crate::MOSTRO_CONFIG; -use anyhow::{Error, Result}; use config::{Config, ConfigError, Environment, File}; +use mostro_core::error::MostroError::{self, *}; +use mostro_core::error::ServiceError; use serde::Deserialize; use std::ffi::OsString; use std::io::Write; @@ -46,9 +47,9 @@ pub struct Database { } impl TryFrom for Database { - type Error = Error; + type Error = MostroError; - fn try_from(_: Settings) -> Result { + fn try_from(_: Settings) -> Result { Ok(MOSTRO_CONFIG.get().unwrap().database.clone()) } } @@ -66,9 +67,9 @@ pub struct Lightning { } impl TryFrom for Lightning { - type Error = Error; + type Error = MostroError; - fn try_from(_: Settings) -> Result { + fn try_from(_: Settings) -> Result { Ok(MOSTRO_CONFIG.get().unwrap().lightning.clone()) } } @@ -80,9 +81,9 @@ pub struct Nostr { } impl TryFrom for Nostr { - type Error = Error; + type Error = MostroError; - fn try_from(_: Settings) -> Result { + fn try_from(_: Settings) -> Result { Ok(MOSTRO_CONFIG.get().unwrap().nostr.clone()) } } @@ -103,9 +104,9 @@ pub struct Mostro { } impl TryFrom for Mostro { - type Error = Error; + type Error = MostroError; - fn try_from(_: Settings) -> Result { + fn try_from(_: Settings) -> Result { Ok(MOSTRO_CONFIG.get().unwrap().mostro.clone()) } } @@ -169,7 +170,7 @@ impl Settings { } } -pub fn init_default_dir(config_path: Option) -> Result { +pub fn init_default_dir(config_path: Option) -> Result { // , final_path : &mut PathBuf) -> Result<()> { // Dir prefix let home_dir: OsString; @@ -183,7 +184,7 @@ pub fn init_default_dir(config_path: Option) -> Result { settings_dir_default.push(home_dir); } else { // Get $HOME from env - let tmp = std::env::var("HOME")?; + let tmp = std::env::var("HOME").map_err(|e| MostroInternalErr(ServiceError::EnvVarError(e.to_string())))?; // Os String home_dir = tmp.into(); // Create default path with default .mostro value @@ -199,10 +200,10 @@ pub fn init_default_dir(config_path: Option) -> Result { if std::fs::create_dir(settings_dir_default.clone()).is_ok() { tracing::info!("Created mostro default directory!"); let mut config_file = - std::fs::File::create_new(settings_dir_default.join("settings.toml"))?; + std::fs::File::create_new(settings_dir_default.join("settings.toml")).map_err(|e| MostroInternalErr(ServiceError::IOError(e.to_string())))?; let buf = include_bytes!("../../settings.tpl.toml"); - config_file.write_all(buf)?; - config_file.flush()?; + config_file.write_all(buf).map_err(|e| MostroInternalErr(ServiceError::IOError(e.to_string())))?; + config_file.flush().map_err(|e| MostroInternalErr(ServiceError::IOError(e.to_string())))?; } tracing::info!( "Created settings file based on template and copied to {} directory", diff --git a/src/lightning/mod.rs b/src/lightning/mod.rs index 944c5fa3..8a0836bd 100644 --- a/src/lightning/mod.rs +++ b/src/lightning/mod.rs @@ -4,7 +4,6 @@ use crate::cli::settings::Settings; use crate::lightning::invoice::decode_invoice; use crate::util::bytes_to_string; -use anyhow::Result; use easy_hasher::easy_hasher::*; use fedimint_tonic_lnd::invoicesrpc::{ AddHoldInvoiceRequest, AddHoldInvoiceResp, CancelInvoiceMsg, CancelInvoiceResp, diff --git a/src/messages.rs b/src/messages.rs index ad394abe..d6f8af78 100644 --- a/src/messages.rs +++ b/src/messages.rs @@ -1,5 +1,3 @@ -use anyhow::Result; - pub fn hold_invoice_description( order_id: &str, fiat_code: &str, diff --git a/src/scheduler.rs b/src/scheduler.rs index 0685bf71..6d0669cf 100644 --- a/src/scheduler.rs +++ b/src/scheduler.rs @@ -9,6 +9,8 @@ use crate::{db::*, MESSAGE_QUEUES}; use crate::{Keys, PublicKey}; use chrono::{TimeDelta, Utc}; +use mostro_core::error::MostroError::{self, *}; +use mostro_core::error::ServiceError; use mostro_core::message::Message; use mostro_core::order::{Kind, Status}; use nostr_sdk::EventBuilder; @@ -230,16 +232,16 @@ async fn job_update_rate_events() { }); } -async fn job_cancel_orders() -> anyhow::Result<()> { +async fn job_cancel_orders() -> Result<(), MostroError> { info!("Create a pool to connect to db"); let pool = match connect().await { Ok(p) => p, - Err(e) => return Err(anyhow::Error::msg(e.to_string())), + Err(e) => return Err(MostroInternalErr(ServiceError::DbAccessError(e.to_string()))), }; let keys = match get_keys() { Ok(keys) => keys, - Err(e) => return Err(anyhow::Error::msg(e.to_string())), + Err(e) => return Err(MostroInternalErr(ServiceError::DbAccessError(e.to_string()))), }; let mut ln_client = LndConnector::new().await?; diff --git a/src/util.rs b/src/util.rs index 79b5c862..00d3cf4f 100644 --- a/src/util.rs +++ b/src/util.rs @@ -540,7 +540,7 @@ pub async fn show_hold_invoice( } // Create function to reuse in case of resubscription -pub async fn invoice_subscribe(hash: Vec, request_id: Option) -> anyhow::Result<()> { +pub async fn invoice_subscribe(hash: Vec, request_id: Option) -> Result<(), MostroError> { let mut ln_client_invoices = lightning::LndConnector::new().await?; let (tx, mut rx) = channel(100); From 8c21b901eac730c5ff033e2ecc469f580712f6d3 Mon Sep 17 00:00:00 2001 From: arkanoider Date: Sun, 2 Mar 2025 11:56:28 +0100 Subject: [PATCH 2/4] removed anyhow dependecy --- Cargo.lock | 1 - Cargo.toml | 1 - src/app.rs | 3 +- src/bitcoin_price.rs | 27 +++-- src/cli.rs | 2 +- src/cli/settings.rs | 14 ++- src/db.rs | 252 ++++++++++++++++++++++++------------------- src/main.rs | 5 +- src/messages.rs | 4 +- src/scheduler.rs | 12 ++- src/util.rs | 1 - 11 files changed, 186 insertions(+), 136 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b44cac58..9e6f20b5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1949,7 +1949,6 @@ dependencies = [ name = "mostro" version = "0.13.1" dependencies = [ - "anyhow", "bitcoin", "chrono", "clap", diff --git a/Cargo.toml b/Cargo.toml index c1437b65..45efeed6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,7 +13,6 @@ name = "mostrod" path = "src/main.rs" [dependencies] -anyhow = "1.0.89" chrono = "0.4.35" easy-hasher = "2.2.1" lightning-invoice = { version = "0.33.1", features = ["std"] } diff --git a/src/app.rs b/src/app.rs index a329280d..c1e3631a 100644 --- a/src/app.rs +++ b/src/app.rs @@ -40,7 +40,6 @@ use crate::util::enqueue_cant_do_msg; use crate::Settings; // External dependencies -use anyhow::Result; use mostro_core::error::CantDoReason; use mostro_core::error::MostroError; use mostro_core::error::ServiceError; @@ -354,7 +353,7 @@ pub async fn run( { match e.downcast::() { Ok(err) => { - manage_errors(err, message, event, &action).await; + manage_errors(*err, message, event, &action).await; } Err(e) => { tracing::error!("Unexpected error type: {}", e); diff --git a/src/bitcoin_price.rs b/src/bitcoin_price.rs index 4afe62f6..a4686746 100644 --- a/src/bitcoin_price.rs +++ b/src/bitcoin_price.rs @@ -1,7 +1,6 @@ - -use once_cell::sync::Lazy; use mostro_core::error::MostroError::{self, *}; use mostro_core::error::ServiceError; +use once_cell::sync::Lazy; use serde::Deserialize; use std::collections::HashMap; use std::sync::RwLock; @@ -22,20 +21,32 @@ pub struct BitcoinPriceManager; impl BitcoinPriceManager { pub async fn update_prices() -> Result<(), MostroError> { - let response = reqwest::get(YADIO_API_URL).await.map_err(|e| MostroInternalErr(ServiceError::NoAPIResponse))?; - let yadio_response: YadioResponse = response.json().await.map_err(|e| MostroInternalErr(ServiceError::MessageSerializationError))?; + let response = reqwest::get(YADIO_API_URL) + .await + .map_err(|_| MostroInternalErr(ServiceError::NoAPIResponse))?; + let yadio_response: YadioResponse = response + .json() + .await + .map_err(|_| MostroInternalErr(ServiceError::MessageSerializationError))?; info!( "Bitcoin prices updated. Got BTC price in {} fiat currencies", yadio_response.btc.keys().collect::>().len() ); - let mut prices_write = BITCOIN_PRICES.write().map_err(|e| MostroInternalErr(ServiceError::IOError(e.to_string())))?; + let mut prices_write = BITCOIN_PRICES + .write() + .map_err(|e| MostroInternalErr(ServiceError::IOError(e.to_string())))?; *prices_write = yadio_response.btc; Ok(()) } - pub fn get_price(currency: &str) -> Option { - let prices_read = BITCOIN_PRICES.read().map_err(|e| MostroInternalErr(ServiceError::IOError(e.to_string())))?; - prices_read.get(currency).cloned() + pub fn get_price(currency: &str) -> Result { + let prices_read: std::sync::RwLockReadGuard<'_, HashMap> = BITCOIN_PRICES + .read() + .map_err(|e| MostroInternalErr(ServiceError::IOError(e.to_string())))?; + prices_read + .get(currency) + .cloned() + .ok_or(MostroInternalErr(ServiceError::NoAPIResponse)) } } diff --git a/src/cli.rs b/src/cli.rs index a0f65086..92092a98 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -1,8 +1,8 @@ pub mod settings; use crate::cli::settings::init_default_dir; -use mostro_core::error::MostroError; use clap::Parser; +use mostro_core::error::MostroError; use std::path::PathBuf; #[derive(Parser)] diff --git a/src/cli/settings.rs b/src/cli/settings.rs index 9279e004..83447df8 100644 --- a/src/cli/settings.rs +++ b/src/cli/settings.rs @@ -184,7 +184,8 @@ pub fn init_default_dir(config_path: Option) -> Result) -> Result Result> { +pub async fn connect() -> Result, MostroError> { // Get mostro settings let db_settings = Settings::get_db(); let mut db_url = db_settings.url; @@ -29,13 +28,8 @@ pub async fn connect() -> Result> { let tmp = db_url.replace("sqlite://", ""); let db_path = Path::new(&tmp); let conn = if !db_path.exists() { - let _file = std::fs::File::create_new(db_path).map_err(|e| { - anyhow::anyhow!( - "Failed to create database file at {}: {}", - db_path.display(), - e - ) - })?; + let _file = std::fs::File::create_new(db_path) + .map_err(|e| MostroInternalErr(ServiceError::DbAccessError(e.to_string())))?; match SqlitePool::connect(&db_url).await { Ok(pool) => { match sqlx::migrate!().run(&pool).await { @@ -54,11 +48,9 @@ pub async fn connect() -> Result> { "Failed to create database connection" ); } - return Err(anyhow::anyhow!( - "Failed to create database connection at {}: {}", - db_path.display(), - e - )); + return Err(MostroInternalErr(ServiceError::DbAccessError( + e.to_string(), + ))); } } pool @@ -69,21 +61,15 @@ pub async fn connect() -> Result> { path = %db_path.display(), "Failed to create database connection" ); - return Err(anyhow::anyhow!( - "Failed to create database connection at {}: {}", - db_path.display(), - e - )); + return Err(MostroInternalErr(ServiceError::DbAccessError( + e.to_string(), + ))); } } } else { - SqlitePool::connect(&db_url).await.map_err(|e| { - anyhow::anyhow!( - "Failed to connect to existing database at {}: {}", - db_path.display(), - e - ) - })? + SqlitePool::connect(&db_url) + .await + .map_err(|e| MostroInternalErr(ServiceError::DbAccessError(e.to_string())))? }; Ok(conn) } @@ -92,9 +78,12 @@ pub async fn edit_buyer_pubkey_order( pool: &SqlitePool, order_id: Uuid, buyer_pubkey: Option, -) -> anyhow::Result { - let mut conn = pool.acquire().await?; - let rows_affected = sqlx::query!( +) -> Result { + let mut conn = pool + .acquire() + .await + .map_err(|e| MostroInternalErr(ServiceError::DbAccessError(e.to_string())))?; + let result = sqlx::query!( r#" UPDATE orders SET @@ -105,8 +94,9 @@ pub async fn edit_buyer_pubkey_order( order_id ) .execute(&mut conn) - .await? - .rows_affected(); + .await + .map_err(|e| MostroInternalErr(ServiceError::DbAccessError(e.to_string())))?; + let rows_affected = result.rows_affected(); Ok(rows_affected > 0) } @@ -115,9 +105,12 @@ pub async fn edit_seller_pubkey_order( pool: &SqlitePool, order_id: Uuid, seller_pubkey: Option, -) -> anyhow::Result { - let mut conn = pool.acquire().await?; - let rows_affected = sqlx::query!( +) -> Result { + let mut conn = pool + .acquire() + .await + .map_err(|e| MostroInternalErr(ServiceError::DbAccessError(e.to_string())))?; + let result = sqlx::query!( r#" UPDATE orders SET @@ -128,13 +121,14 @@ pub async fn edit_seller_pubkey_order( order_id ) .execute(&mut conn) - .await? - .rows_affected(); + .await + .map_err(|e| MostroInternalErr(ServiceError::DbAccessError(e.to_string())))?; + let rows_affected = result.rows_affected(); Ok(rows_affected > 0) } -pub async fn find_order_by_hash(pool: &SqlitePool, hash: &str) -> anyhow::Result { +pub async fn find_order_by_hash(pool: &SqlitePool, hash: &str) -> Result { let order = sqlx::query_as::<_, Order>( r#" SELECT * @@ -144,12 +138,13 @@ pub async fn find_order_by_hash(pool: &SqlitePool, hash: &str) -> anyhow::Result ) .bind(hash) .fetch_one(pool) - .await?; + .await + .map_err(|e| MostroInternalErr(ServiceError::DbAccessError(e.to_string())))?; Ok(order) } -pub async fn find_order_by_date(pool: &SqlitePool) -> anyhow::Result> { +pub async fn find_order_by_date(pool: &SqlitePool) -> Result, MostroError> { let expire_time = Timestamp::now(); let order = sqlx::query_as::<_, Order>( r#" @@ -160,12 +155,13 @@ pub async fn find_order_by_date(pool: &SqlitePool) -> anyhow::Result> ) .bind(expire_time.to_string()) .fetch_all(pool) - .await?; + .await + .map_err(|e| MostroInternalErr(ServiceError::DbAccessError(e.to_string())))?; Ok(order) } -pub async fn find_order_by_seconds(pool: &SqlitePool) -> anyhow::Result> { +pub async fn find_order_by_seconds(pool: &SqlitePool) -> Result, MostroError> { let mostro_settings = Settings::get_mostro(); let exp_seconds = mostro_settings.expiration_seconds as u64; let expire_time = Timestamp::now() - exp_seconds; @@ -178,7 +174,8 @@ pub async fn find_order_by_seconds(pool: &SqlitePool) -> anyhow::Result anyhow::Result anyhow::Result { +) -> Result { let dispute = sqlx::query_as::<_, Dispute>( r#" SELECT * @@ -196,7 +193,8 @@ pub async fn find_dispute_by_order_id( ) .bind(order_id) .fetch_one(pool) - .await?; + .await + .map_err(|e| MostroInternalErr(ServiceError::DbAccessError(e.to_string())))?; Ok(dispute) } @@ -206,12 +204,15 @@ pub async fn update_order_to_initial_state( order_id: Uuid, amount: i64, fee: i64, -) -> anyhow::Result { - let mut conn = pool.acquire().await?; +) -> Result { + let mut conn = pool + .acquire() + .await + .map_err(|e| MostroInternalErr(ServiceError::DbAccessError(e.to_string())))?; let status = Status::Pending.to_string(); let hash: Option = None; let preimage: Option = None; - let rows_affected = sqlx::query!( + let result = sqlx::query!( r#" UPDATE orders SET @@ -234,8 +235,9 @@ pub async fn update_order_to_initial_state( order_id, ) .execute(&mut conn) - .await? - .rows_affected(); + .await + .map_err(|e| MostroInternalErr(ServiceError::DbAccessError(e.to_string())))?; + let rows_affected = result.rows_affected(); Ok(rows_affected > 0) } @@ -244,9 +246,12 @@ pub async fn edit_master_buyer_pubkey_order( pool: &SqlitePool, order_id: Uuid, master_buyer_pubkey: Option, -) -> anyhow::Result { - let mut conn = pool.acquire().await?; - let rows_affected = sqlx::query!( +) -> Result { + let mut conn = pool + .acquire() + .await + .map_err(|e| MostroInternalErr(ServiceError::DbAccessError(e.to_string())))?; + let result = sqlx::query!( r#" UPDATE orders SET @@ -257,8 +262,9 @@ pub async fn edit_master_buyer_pubkey_order( order_id ) .execute(&mut conn) - .await? - .rows_affected(); + .await + .map_err(|e| MostroInternalErr(ServiceError::DbAccessError(e.to_string())))?; + let rows_affected = result.rows_affected(); Ok(rows_affected > 0) } @@ -267,9 +273,12 @@ pub async fn edit_master_seller_pubkey_order( pool: &SqlitePool, order_id: Uuid, master_seller_pubkey: Option, -) -> anyhow::Result { - let mut conn = pool.acquire().await?; - let rows_affected = sqlx::query!( +) -> Result { + let mut conn = pool + .acquire() + .await + .map_err(|e| MostroInternalErr(ServiceError::DbAccessError(e.to_string())))?; + let result = sqlx::query!( r#" UPDATE orders SET @@ -280,17 +289,24 @@ pub async fn edit_master_seller_pubkey_order( order_id ) .execute(&mut conn) - .await? - .rows_affected(); + .await + .map_err(|e| MostroInternalErr(ServiceError::DbAccessError(e.to_string())))?; + let rows_affected = result.rows_affected(); Ok(rows_affected > 0) } -pub async fn reset_order_taken_at_time(pool: &SqlitePool, order_id: Uuid) -> anyhow::Result { - let mut conn = pool.acquire().await?; +pub async fn reset_order_taken_at_time( + pool: &SqlitePool, + order_id: Uuid, +) -> Result { + let mut conn = pool + .acquire() + .await + .map_err(|e| MostroInternalErr(ServiceError::DbAccessError(e.to_string())))?; let taken_at = 0; - let rows_affected = sqlx::query!( + let result = sqlx::query!( r#" UPDATE orders SET @@ -301,8 +317,9 @@ pub async fn reset_order_taken_at_time(pool: &SqlitePool, order_id: Uuid) -> any order_id, ) .execute(&mut conn) - .await? - .rows_affected(); + .await + .map_err(|e| MostroInternalErr(ServiceError::DbAccessError(e.to_string())))?; + let rows_affected = result.rows_affected(); Ok(rows_affected > 0) } @@ -311,9 +328,12 @@ pub async fn update_order_invoice_held_at_time( pool: &SqlitePool, order_id: Uuid, invoice_held_at: i64, -) -> anyhow::Result { - let mut conn = pool.acquire().await?; - let rows_affected = sqlx::query!( +) -> Result { + let mut conn = pool + .acquire() + .await + .map_err(|e| MostroInternalErr(ServiceError::DbAccessError(e.to_string())))?; + let result = sqlx::query!( r#" UPDATE orders SET @@ -324,13 +344,14 @@ pub async fn update_order_invoice_held_at_time( order_id, ) .execute(&mut conn) - .await? - .rows_affected(); + .await + .map_err(|e| MostroInternalErr(ServiceError::DbAccessError(e.to_string())))?; + let rows_affected = result.rows_affected(); Ok(rows_affected > 0) } -pub async fn find_held_invoices(pool: &SqlitePool) -> anyhow::Result> { +pub async fn find_held_invoices(pool: &SqlitePool) -> Result, MostroError> { let order = sqlx::query_as::<_, Order>( r#" SELECT * @@ -339,12 +360,13 @@ pub async fn find_held_invoices(pool: &SqlitePool) -> anyhow::Result> "#, ) .fetch_all(pool) - .await?; + .await + .map_err(|e| MostroInternalErr(ServiceError::DbAccessError(e.to_string())))?; Ok(order) } -pub async fn find_failed_payment(pool: &SqlitePool) -> anyhow::Result> { +pub async fn find_failed_payment(pool: &SqlitePool) -> Result, MostroError> { let order = sqlx::query_as::<_, Order>( r#" SELECT * @@ -353,12 +375,16 @@ pub async fn find_failed_payment(pool: &SqlitePool) -> anyhow::Result "#, ) .fetch_all(pool) - .await?; + .await + .map_err(|e| MostroInternalErr(ServiceError::DbAccessError(e.to_string())))?; Ok(order) } -pub async fn find_solver_pubkey(pool: &SqlitePool, solver_npub: String) -> anyhow::Result { +pub async fn find_solver_pubkey( + pool: &SqlitePool, + solver_npub: String, +) -> Result { let user = sqlx::query_as::<_, User>( r#" SELECT * @@ -369,12 +395,13 @@ pub async fn find_solver_pubkey(pool: &SqlitePool, solver_npub: String) -> anyho ) .bind(solver_npub) .fetch_one(pool) - .await?; + .await + .map_err(|e| MostroInternalErr(ServiceError::DbAccessError(e.to_string())))?; Ok(user) } -pub async fn is_user_present(pool: &SqlitePool, public_key: String) -> anyhow::Result { +pub async fn is_user_present(pool: &SqlitePool, public_key: String) -> Result { let user = sqlx::query_as::<_, User>( r#" SELECT * @@ -385,15 +412,16 @@ pub async fn is_user_present(pool: &SqlitePool, public_key: String) -> anyhow::R ) .bind(public_key) .fetch_one(pool) - .await?; + .await + .map_err(|e| MostroInternalErr(ServiceError::DbAccessError(e.to_string())))?; Ok(user) } -pub async fn add_new_user(pool: &SqlitePool, new_user: User) -> anyhow::Result<()> { +pub async fn add_new_user(pool: &SqlitePool, new_user: User) -> Result<(), MostroError> { // Validate public key format (32-bytes hex) let created_at: Timestamp = Timestamp::now(); - let result = sqlx::query( + let _result = sqlx::query( " INSERT INTO users (pubkey, is_admin, is_solver, is_banned, category, last_trade_index, total_reviews, total_rating, last_rating, max_rating, min_rating, created_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12) @@ -412,34 +440,32 @@ pub async fn add_new_user(pool: &SqlitePool, new_user: User) -> anyhow::Result<( .bind(new_user.min_rating) .bind(created_at.to_string()) .execute(pool) - .await; + .await + .map_err(|e| MostroInternalErr(ServiceError::DbAccessError(e.to_string())))?; - match result { - Ok(_) => { - tracing::info!("New user created successfully"); - Ok(()) - } - Err(e) => Err(anyhow::anyhow!("Error creating new user: {}", e)), - } + Ok(()) } pub async fn update_user_trade_index( pool: &SqlitePool, public_key: String, trade_index: i64, -) -> anyhow::Result { +) -> Result { // Validate public key format (32-bytes hex) if !public_key.chars().all(|c| c.is_ascii_hexdigit()) || public_key.len() != 64 { - return Err(anyhow::anyhow!("Invalid public key format")); + return Err(MostroCantDo(CantDoReason::InvalidPubkey)); } // Validate trade_index if trade_index < 0 { - return Err(anyhow::anyhow!("Invalid trade_index: must be non-negative")); + return Err(MostroCantDo(CantDoReason::InvalidTradeIndex)); } - let mut conn = pool.acquire().await?; + let mut conn = pool + .acquire() + .await + .map_err(|e| MostroInternalErr(ServiceError::DbAccessError(e.to_string())))?; - let rows_affected = sqlx::query!( + let result = sqlx::query!( r#" UPDATE users SET last_trade_index = ?1 WHERE pubkey = ?2 "#, @@ -447,8 +473,9 @@ pub async fn update_user_trade_index( public_key, ) .execute(&mut conn) - .await? - .rows_affected(); + .await + .map_err(|e| MostroInternalErr(ServiceError::DbAccessError(e.to_string())))?; + let rows_affected = result.rows_affected(); Ok(rows_affected > 0) } @@ -457,7 +484,7 @@ pub async fn update_user_trade_index( pub async fn seller_has_pending_order( pool: &SqlitePool, pubkey: String, -) -> anyhow::Result { +) -> Result { // Validate public key format (32-bytes hex) if !pubkey.chars().all(|c| c.is_ascii_hexdigit()) || pubkey.len() != 64 { return Err(MostroCantDo(CantDoReason::InvalidPubkey)); @@ -484,7 +511,7 @@ pub async fn seller_has_pending_order( pub async fn buyer_has_pending_order( pool: &SqlitePool, pubkey: String, -) -> anyhow::Result { +) -> Result { // Validate public key format (32-bytes hex) if !pubkey.chars().all(|c| c.is_ascii_hexdigit()) || pubkey.len() != 64 { return Err(MostroCantDo(CantDoReason::InvalidPubkey)); @@ -515,30 +542,28 @@ pub async fn update_user_rating( max_rating: i64, total_reviews: i64, total_rating: f64, -) -> anyhow::Result { +) -> Result { // Validate public key format (32-bytes hex) if !public_key.chars().all(|c| c.is_ascii_hexdigit()) || public_key.len() != 64 { - return Err(anyhow::anyhow!("Invalid public key format")); + return Err(MostroCantDo(CantDoReason::InvalidPubkey)); } // Validate rating values if !(0..=5).contains(&last_rating) { - return Err(anyhow::anyhow!("Invalid rating value")); + return Err(MostroCantDo(CantDoReason::InvalidRating)); } if !(0..=5).contains(&min_rating) || !(0..=5).contains(&max_rating) { - return Err(anyhow::anyhow!("Invalid min/max rating values")); + return Err(MostroCantDo(CantDoReason::InvalidRating)); } if MIN_RATING as i64 > last_rating || last_rating > MAX_RATING as i64 { - return Err(anyhow::anyhow!( - "Rating values must satisfy: min_rating <= last_rating <= max_rating" - )); + return Err(MostroCantDo(CantDoReason::InvalidRating)); } if total_reviews < 0 { - return Err(anyhow::anyhow!("Invalid total reviews")); + return Err(MostroCantDo(CantDoReason::InvalidRating)); } if total_rating < 0.0 || total_rating > (total_reviews * 5) as f64 { - return Err(anyhow::anyhow!("Invalid total rating")); + return Err(MostroCantDo(CantDoReason::InvalidRating)); } - let rows_affected = sqlx::query!( + let result = sqlx::query!( r#" UPDATE users SET last_rating = ?1, min_rating = ?2, max_rating = ?3, total_reviews = ?4, total_rating = ?5 WHERE pubkey = ?6 "#, @@ -550,8 +575,9 @@ pub async fn update_user_rating( public_key, ) .execute(pool) - .await? - .rows_affected(); + .await + .map_err(|e| MostroInternalErr(ServiceError::DbAccessError(e.to_string())))?; + let rows_affected = result.rows_affected(); Ok(rows_affected > 0) } @@ -560,7 +586,7 @@ pub async fn is_assigned_solver( pool: &SqlitePool, solver_pubkey: &str, order_id: Uuid, -) -> anyhow::Result { +) -> Result { println!("solver_pubkey: {}", solver_pubkey); println!("order_id: {}", order_id); let result = sqlx::query( @@ -570,7 +596,8 @@ pub async fn is_assigned_solver( .bind(order_id) .map(|row: SqliteRow| row.get(0)) .fetch_one(pool) - .await?; + .await + .map_err(|e| MostroInternalErr(ServiceError::DbAccessError(e.to_string())))?; Ok(result) } @@ -579,7 +606,7 @@ pub async fn find_order_by_id( pool: &SqlitePool, order_id: Uuid, user_pubkey: &str, -) -> anyhow::Result { +) -> Result { let order = sqlx::query_as::<_, Order>( r#" SELECT * @@ -590,7 +617,8 @@ pub async fn find_order_by_id( .bind(order_id) .bind(user_pubkey) .fetch_one(pool) - .await?; + .await + .map_err(|e| MostroInternalErr(ServiceError::DbAccessError(e.to_string())))?; Ok(order) } diff --git a/src/main.rs b/src/main.rs index 50f8d889..2893421d 100644 --- a/src/main.rs +++ b/src/main.rs @@ -15,9 +15,8 @@ use crate::app::run; use crate::cli::settings::{init_global_settings, Settings}; use crate::cli::settings_init; use crate::lightning::LnStatus; -use anyhow::Result; -use db::find_held_invoices; -use lightning::LndConnector; +use crate::db::find_held_invoices; +use crate::lightning::LndConnector; use mostro_core::message::Message; use nostr_sdk::prelude::*; use scheduler::start_scheduler; diff --git a/src/messages.rs b/src/messages.rs index d6f8af78..61914afe 100644 --- a/src/messages.rs +++ b/src/messages.rs @@ -1,8 +1,10 @@ +use mostro_core::error::MostroError; + pub fn hold_invoice_description( order_id: &str, fiat_code: &str, fiat_amount: &str, -) -> Result { +) -> Result { Ok(format!( "Escrow amount Order #{order_id}: SELL BTC for {fiat_code} {fiat_amount} - It WILL FREEZE IN WALLET. It will release once you release. It will return if buyer does not confirm the payment" )) diff --git a/src/scheduler.rs b/src/scheduler.rs index 6d0669cf..10d62d4c 100644 --- a/src/scheduler.rs +++ b/src/scheduler.rs @@ -237,11 +237,19 @@ async fn job_cancel_orders() -> Result<(), MostroError> { let pool = match connect().await { Ok(p) => p, - Err(e) => return Err(MostroInternalErr(ServiceError::DbAccessError(e.to_string()))), + Err(e) => { + return Err(MostroInternalErr(ServiceError::DbAccessError( + e.to_string(), + ))) + } }; let keys = match get_keys() { Ok(keys) => keys, - Err(e) => return Err(MostroInternalErr(ServiceError::DbAccessError(e.to_string()))), + Err(e) => { + return Err(MostroInternalErr(ServiceError::DbAccessError( + e.to_string(), + ))) + } }; let mut ln_client = LndConnector::new().await?; diff --git a/src/util.rs b/src/util.rs index 00d3cf4f..a0870dfb 100644 --- a/src/util.rs +++ b/src/util.rs @@ -64,7 +64,6 @@ pub async fn retries_yadio_request( pub fn get_bitcoin_price(fiat_code: &str) -> Result { BitcoinPriceManager::get_price(fiat_code) - .ok_or(MostroError::MostroInternalErr(ServiceError::NoAPIResponse)) } /// Request market quote from Yadio to have sats amount at actual market price From b5d70be376a8e0129f750568be7a25f9aebe4a09 Mon Sep 17 00:00:00 2001 From: arkanoider Date: Sun, 2 Mar 2025 16:24:18 +0100 Subject: [PATCH 3/4] remove patch from cargo.toml --- Cargo.lock | 2 ++ Cargo.toml | 5 +---- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 9e6f20b5..44836892 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1975,6 +1975,8 @@ dependencies = [ [[package]] name = "mostro-core" version = "0.6.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc439d283bc64ae1d8b6d7f83994ceec750f402d3e7515c97757ba684271eef4" dependencies = [ "anyhow", "bitcoin", diff --git a/Cargo.toml b/Cargo.toml index 45efeed6..30cab669 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -48,7 +48,4 @@ once_cell = "1.20.2" bitcoin = "0.32.5" [dev-dependencies] -tokio = { version = "1.40.0", features = ["full", "test-util", "macros"] } - -[patch.crates-io] -mostro-core = { path = "../mostro-core" } \ No newline at end of file +tokio = { version = "1.40.0", features = ["full", "test-util", "macros"] } \ No newline at end of file From d17526cbcd95ef93a9b10b9dec8046bec73f9728 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Francisco=20Calder=C3=B3n?= Date: Mon, 3 Mar 2025 16:46:11 -0300 Subject: [PATCH 4/4] Update mostro-core version --- Cargo.lock | 4 ++-- Cargo.toml | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 44836892..80b17497 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1974,9 +1974,9 @@ dependencies = [ [[package]] name = "mostro-core" -version = "0.6.28" +version = "0.6.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc439d283bc64ae1d8b6d7f83994ceec750f402d3e7515c97757ba684271eef4" +checksum = "f50b052b77839590b542d90c88bed69c9eab9298c647dbccd3b27ccc19c7f1d5" dependencies = [ "anyhow", "bitcoin", diff --git a/Cargo.toml b/Cargo.toml index 30cab669..c581cb4c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -37,7 +37,7 @@ uuid = { version = "1.8.0", features = [ "serde", ] } reqwest = { version = "0.12.1", features = ["json"] } -mostro-core = { version = "0.6.28", features = ["sqlx"] } +mostro-core = { version = "0.6.30", features = ["sqlx"] } tracing = "0.1.40" tracing-subscriber = { version = "0.3.18", features = ["env-filter"] } config = "0.15.8" @@ -48,4 +48,4 @@ once_cell = "1.20.2" bitcoin = "0.32.5" [dev-dependencies] -tokio = { version = "1.40.0", features = ["full", "test-util", "macros"] } \ No newline at end of file +tokio = { version = "1.40.0", features = ["full", "test-util", "macros"] }