Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Removing some unwraps to cool down my mind #336

Merged
merged 3 commits into from
Aug 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 4 additions & 3 deletions src/app/cancel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -215,9 +215,10 @@ pub async fn cancel_pay_hold_invoice(
) -> Result<()> {
if order.hash.is_some() {
// We return funds to seller
let hash = order.hash.as_ref().unwrap();
ln_client.cancel_hold_invoice(hash).await?;
info!("Order Id {}: Funds returned to seller", &order.id);
if let Some(hash) = order.hash.as_ref() {
ln_client.cancel_hold_invoice(hash).await?;
info!("Order Id {}: Funds returned to seller", &order.id);
}
}
let user_pubkey = event.pubkey.to_string();

Expand Down
23 changes: 12 additions & 11 deletions src/app/dispute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,18 +34,19 @@ pub async fn dispute_action(

let mut order = match Order::by_id(pool, order_id).await? {
Some(order) => {
if matches!(
Status::from_str(&order.status).unwrap(),
Status::Active | Status::FiatSent
) {
order
if let Ok(st) = Status::from_str(&order.status) {
if matches!(st, Status::Active | Status::FiatSent) {
order
} else {
send_cant_do_msg(
Some(order.id),
Some("Not allowed".to_string()),
&event.pubkey,
)
.await;
return Ok(());
}
} else {
send_cant_do_msg(
Some(order.id),
Some("Not allowed".to_string()),
&event.pubkey,
)
.await;
return Ok(());
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/app/order.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,13 +54,13 @@ pub async fn order_action(
}
}

for (_, fiat_amount) in amount_vec.iter().enumerate() {
for fiat_amount in amount_vec.iter() {
let quote = match order.amount {
0 => match get_bitcoin_price(&order.fiat_code) {
Ok(price) => {
let quote = *fiat_amount as f64 / price;
(quote * 1E8) as i64
},
}
Err(e) => {
error!("{:?}", e.to_string());
return Ok(());
Expand Down
127 changes: 70 additions & 57 deletions src/app/release.rs
Original file line number Diff line number Diff line change
Expand Up @@ -251,66 +251,79 @@ async fn payment_success(
new_order.seller_pubkey = None;
new_order.master_seller_pubkey = None;
}
match new_max.cmp(&order.min_amount.unwrap()) {
Ordering::Equal => {
// Update order in case max == min
let pool = db::connect().await?;
new_order.fiat_amount = new_max;
new_order.max_amount = None;
new_order.min_amount = None;
new_order.status = Status::Pending.to_string();
new_order.id = uuid::Uuid::new_v4();
new_order.status = Status::Pending.to_string();
// We transform the order fields to tags to use in the event
let tags = crate::nip33::order_to_tags(&new_order, None);
if let Some(min_amount) = &order.min_amount {
match new_max.cmp(min_amount) {
Ordering::Equal => {
// Update order in case max == min
let pool = db::connect().await?;
new_order.fiat_amount = new_max;
new_order.max_amount = None;
new_order.min_amount = None;
new_order.status = Status::Pending.to_string();
new_order.id = uuid::Uuid::new_v4();
new_order.status = Status::Pending.to_string();
// We transform the order fields to tags to use in the event
let tags = crate::nip33::order_to_tags(&new_order, None);

info!("range order tags to be republished: {:#?}", tags);
// nip33 kind with order fields as tags and order id as identifier
let event =
crate::nip33::new_event(my_keys, "", new_order.id.to_string(), tags)?;
let event_id = event.id.to_string();
// We update the order with the new event_id
new_order.event_id = event_id;
// CRUD order creation
new_order.clone().create(&pool).await?;
let _ = NOSTR_CLIENT
.get()
.unwrap()
.send_event(event)
.await
.map(|_s| ())
.map_err(|err| err.to_string());
}
Ordering::Greater => {
// Update order in case new max is still greater the min amount
let pool = db::connect().await?;
// let mut new_order = order.clone();
new_order.max_amount = Some(new_max);
new_order.fiat_amount = 0;
new_order.id = uuid::Uuid::new_v4();
new_order.status = Status::Pending.to_string();
// CRUD order creation
// We transform the order fields to tags to use in the event
let tags = crate::nip33::order_to_tags(&new_order, None);
info!("range order tags to be republished: {:#?}", tags);
// nip33 kind with order fields as tags and order id as identifier
let event = crate::nip33::new_event(
my_keys,
"",
new_order.id.to_string(),
tags,
)?;
let event_id = event.id.to_string();
// We update the order with the new event_id
new_order.event_id = event_id;
// CRUD order creation
new_order.clone().create(&pool).await?;
let _ = NOSTR_CLIENT
.get()
.unwrap()
.send_event(event)
.await
.map(|_s| ())
.map_err(|err| err.to_string());
}
Ordering::Greater => {
// Update order in case new max is still greater the min amount
let pool = db::connect().await?;
// let mut new_order = order.clone();
new_order.max_amount = Some(new_max);
new_order.fiat_amount = 0;
new_order.id = uuid::Uuid::new_v4();
new_order.status = Status::Pending.to_string();
// CRUD order creation
// We transform the order fields to tags to use in the event
let tags = crate::nip33::order_to_tags(&new_order, None);

info!("range order tags to be republished: {:#?}", tags);
// nip33 kind with order fields as tags and order id as identifier
let event =
crate::nip33::new_event(my_keys, "", new_order.id.to_string(), tags)?;
let event_id = event.id.to_string();
// We update the order with the new event_id
new_order.event_id = event_id;
new_order.clone().create(&pool).await?;
let _ = NOSTR_CLIENT
.get()
.unwrap()
.send_event(event)
.await
.map(|_s| ())
.map_err(|err| err.to_string());
info!("range order tags to be republished: {:#?}", tags);
// nip33 kind with order fields as tags and order id as identifier
let event = crate::nip33::new_event(
my_keys,
"",
new_order.id.to_string(),
tags,
)?;
let event_id = event.id.to_string();
// We update the order with the new event_id
new_order.event_id = event_id;
new_order.clone().create(&pool).await?;
let _ = NOSTR_CLIENT
.get()
.unwrap()
.send_event(event)
.await
.map(|_s| ())
.map_err(|err| err.to_string());
}
// Update order status in case new max is smaller the min amount
Ordering::Less => {}
}
// Update order status in case new max is smaller the min amount
Ordering::Less => {}
} else {
send_cant_do_msg(Some(order.id), None, buyer_pubkey).await;
send_cant_do_msg(Some(order.id), None, seller_pubkey).await;
}
}
}
Expand Down
13 changes: 7 additions & 6 deletions src/bitcoin_price.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
use anyhow::Result;
use once_cell::sync::Lazy;
use serde::Deserialize;
use std::collections::HashMap;
use std::sync::RwLock;
use serde::Deserialize;
use anyhow::Result;
use tracing::info;
use once_cell::sync::Lazy;

const YADIO_API_URL: &str = "https://api.yadio.io/exrates/BTC";

Expand All @@ -13,7 +13,8 @@ struct YadioResponse {
btc: HashMap<String, f64>,
}

static BITCOIN_PRICES: Lazy<RwLock<HashMap<String, f64>>> = Lazy::new(|| RwLock::new(HashMap::new()));
static BITCOIN_PRICES: Lazy<RwLock<HashMap<String, f64>>> =
Lazy::new(|| RwLock::new(HashMap::new()));

pub struct BitcoinPriceManager;

Expand All @@ -22,7 +23,7 @@ impl BitcoinPriceManager {
let response = reqwest::get(YADIO_API_URL).await?;
let yadio_response: YadioResponse = response.json().await?;
info!(
"Bitcoin prices updated. Got BTC price in {} fiat currencies",
"Bitcoin prices updated. Got BTC price in {} fiat currencies",
yadio_response.btc.keys().collect::<Vec<&String>>().len()
);

Expand All @@ -35,4 +36,4 @@ impl BitcoinPriceManager {
let prices_read = BITCOIN_PRICES.read().unwrap();
prices_read.get(currency).cloned()
}
}
}
2 changes: 1 addition & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
pub mod app;
mod bitcoin_price;
pub mod cli;
pub mod db;
pub mod error;
Expand All @@ -10,7 +11,6 @@ pub mod models;
pub mod nip33;
pub mod scheduler;
pub mod util;
mod bitcoin_price;

use crate::app::run;
use crate::cli::settings::{init_global_settings, Settings};
Expand Down
17 changes: 9 additions & 8 deletions src/nip33.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,14 +46,15 @@ fn create_rating_string(rating: Option<Rating>) -> String {
}

fn create_fiat_amt_array(order: &Order) -> Vec<String> {
if order.min_amount.is_some()
&& order.max_amount.is_some()
&& order.status == Status::Pending.to_string()
{
vec![
order.min_amount.unwrap().to_string(),
order.max_amount.unwrap().to_string(),
]
if order.status == Status::Pending.to_string() {
match (order.min_amount, order.max_amount) {
(Some(min), Some(max)) => {
vec![min.to_string(), max.to_string()]
}
_ => {
vec![order.fiat_amount.to_string()]
}
}
} else {
vec![order.fiat_amount.to_string()]
}
Expand Down
7 changes: 5 additions & 2 deletions src/scheduler.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
use crate::app::release::do_payment;
use crate::bitcoin_price::BitcoinPriceManager;
use crate::cli::settings::Settings;
use crate::db::*;
use crate::lightning::LndConnector;
use crate::util;
use crate::NOSTR_CLIENT;
use crate::bitcoin_price::BitcoinPriceManager;

use chrono::{TimeDelta, Utc};
use mostro_core::order::{Kind, Status};
Expand Down Expand Up @@ -72,7 +72,10 @@ async fn job_info_event_send() {
let tags = crate::nip33::info_to_tags(&mostro_pubkey.public_key());
let id = format!("info-{}", mostro_pubkey.public_key());

let info_ev = crate::nip33::new_event(&mostro_pubkey, "", id, tags).unwrap();
let info_ev = match crate::nip33::new_event(&mostro_pubkey, "", id, tags) {
Ok(info) => info,
Err(e) => return error!("{e}"),
};
let _ = NOSTR_CLIENT.get().unwrap().send_event(info_ev).await;

tokio::time::sleep(tokio::time::Duration::from_secs(300)).await;
Expand Down
8 changes: 4 additions & 4 deletions src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,11 +111,11 @@ pub async fn get_market_quote(
return Err(MostroError::MalformedAPIRes);
}

let quote = req.0.unwrap().json::<Yadio>().await;
if quote.is_err() {
let quote = if let Some(q) = req.0 {
q.json::<Yadio>().await?
} else {
return Err(MostroError::MalformedAPIRes);
}
let quote = quote?;
};

let mut sats = quote.result * 100_000_000_f64;

Expand Down
Loading