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

No currency exchange rate #183

Merged
merged 5 commits into from
Jan 8, 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
33 changes: 27 additions & 6 deletions src/app/order.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,34 @@ pub async fn order_action(
) -> Result<()> {
if let Some(order) = msg.get_inner_message_kind().get_order() {
let mostro_settings = Settings::get_mostro();
let quote = match get_market_quote(&order.fiat_amount, &order.fiat_code, &0).await {
Ok(amount) => amount,
Err(e) => {
error!("{:?}", e.to_string());
return Ok(());
}

let quote = match order.amount {
0 => match get_market_quote(&order.fiat_amount, &order.fiat_code, &0).await {
Ok(amount) => amount,
Err(e) => {
error!("{:?}", e.to_string());
return Ok(());
}
},
_ => order.amount,
};

// Check amount is positive - extra safety check
if quote < 0 {
let message = Message::cant_do(
order.id,
None,
Some(Content::TextMessage(format!(
"Amount must be positive {} is not valid",
order.amount
))),
);
let message = message.as_json()?;
send_dm(client, my_keys, &event.pubkey, message).await?;

return Ok(());
}

if quote > mostro_settings.max_order_amount as i64 {
let message = Message::cant_do(
order.id,
Expand Down
6 changes: 6 additions & 0 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ pub enum MostroError {
MinAmountError,
WrongAmountError,
NoAPIResponse,
NoCurrency,
MalformedAPIRes,
NegativeAmount,
}

impl std::error::Error for MostroError {}
Expand All @@ -23,6 +26,9 @@ impl fmt::Display for MostroError {
MostroError::MinAmountError => write!(f, "Minimal payment amount"),
MostroError::WrongAmountError => write!(f, "The amount on this invoice is wrong"),
MostroError::NoAPIResponse => write!(f, "Price API not answered - retry"),
MostroError::NoCurrency => write!(f, "Currency requested is not present in the exchange list, please specify a fixed rate"),
MostroError::MalformedAPIRes => write!(f, "Malformed answer from exchange quoting request"),
MostroError::NegativeAmount => write!(f, "Negative amount is not valid"),
}
}
}
Expand Down
49 changes: 39 additions & 10 deletions src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,31 @@ use tracing::error;
use tracing::info;
use uuid::Uuid;

pub async fn retries_yadio_request(req_string: &str) -> Result<reqwest::Response> {
pub type FiatNames = std::collections::HashMap<String, String>;
const MAX_RETRY: u16 = 4;

pub async fn retries_yadio_request(
req_string: &str,
fiat_code: &str,
) -> Result<(Option<reqwest::Response>, bool)> {
// Get Fiat list and check if currency exchange is available
let api_req_string = "https://api.yadio.io/currencies".to_string();
let fiat_list_check = reqwest::get(api_req_string)
.await?
.json::<FiatNames>()
.await?
.contains_key(fiat_code);

// Exit with error - no currency
if !fiat_list_check {
return Ok((None, fiat_list_check));
}

let res = reqwest::get(req_string)
.await
.context("Something went wrong with API request, try again!")?;

Ok(res)
Ok((Some(res), fiat_list_check))
}

/// Request market quote from Yadio to have sats amount at actual market price
Expand All @@ -46,32 +65,42 @@ pub async fn get_market_quote(
);
info!("Requesting API price: {}", req_string);

let mut req = None;
let mut req = (None, false);
let mut no_answer_api = false;

// Retry for 4 times
for retries_num in 1..=4 {
match retries_yadio_request(&req_string).await {
for retries_num in 1..=MAX_RETRY {
match retries_yadio_request(&req_string, fiat_code).await {
Ok(response) => {
req = Some(response);
req = response;
break;
}
Err(_e) => {
if retries_num == MAX_RETRY {
no_answer_api = true;
}
println!(
"API price request failed retrying - {} tentatives left.",
(4 - retries_num)
(MAX_RETRY - retries_num)
);
thread::sleep(std::time::Duration::from_secs(2));
}
};
}

// Case no answers from Yadio
if req.is_none() {
if no_answer_api {
return Err(MostroError::NoAPIResponse);
}

let quote = req.unwrap().json::<Yadio>().await;
// No currency present
if !req.1 {
return Err(MostroError::NoCurrency);
}

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

Expand Down