Skip to content

Commit

Permalink
Bug fixes and refactoring related bot fee (#80)
Browse files Browse the repository at this point in the history
  • Loading branch information
grunch committed May 12, 2023
1 parent d4f3f7a commit f71082a
Show file tree
Hide file tree
Showing 7 changed files with 59 additions and 35 deletions.
20 changes: 10 additions & 10 deletions sqlx-data.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,6 @@
},
"query": "\n UPDATE orders\n SET\n master_seller_pubkey = ?1\n WHERE id = ?2\n "
},
"0f0f1e46225de7a094cc1450847078c0c1d5070e8af44e1961172dc2d28e3380": {
"describe": {
"columns": [],
"nullable": [],
"parameters": {
"Right": 4
}
},
"query": "\n UPDATE orders\n SET\n status = ?1,\n amount = ?2,\n event_id = ?3\n WHERE id = ?4\n "
},
"1a4f24e4d6c6447e7f6b9c7207bd12bc23e87f37d2c8676bffd8f4eb86c31405": {
"describe": {
"columns": [],
Expand Down Expand Up @@ -149,5 +139,15 @@
}
},
"query": "\n UPDATE orders\n SET\n seller_pubkey = ?1\n WHERE id = ?2\n "
},
"f7e4e95f502724efa0a7b67e3d69fb77c84c141ab9482a99ff254f0964b6eff2": {
"describe": {
"columns": [],
"nullable": [],
"parameters": {
"Right": 5
}
},
"query": "\n UPDATE orders\n SET\n status = ?1,\n amount = ?2,\n fee = ?3,\n event_id = ?4\n WHERE id = ?5\n "
}
}
6 changes: 5 additions & 1 deletion src/app/add_invoice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,11 @@ pub async fn add_invoice_action(
// If a buyer sent me a lightning invoice we get it
if let Some(payment_request) = msg.get_payment_request() {
// Verify if invoice is valid
match is_valid_invoice(&payment_request, Some(order.amount as u64)) {
match is_valid_invoice(
&payment_request,
Some(order.amount as u64),
Some(order.fee as u64),
) {
Ok(_) => {}
Err(e) => match e {
MostroError::ParsingInvoiceError
Expand Down
20 changes: 14 additions & 6 deletions src/app/take_sell.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use crate::util::{send_dm, set_market_order_sats_amount, show_hold_invoice};
use anyhow::Result;
use log::error;
use mostro_core::order::Order;
use mostro_core::{Action, Message, Status};
use mostro_core::{Action, Content, Message, Status};
use nostr_sdk::prelude::*;
use sqlx::{Pool, Sqlite};
use sqlx_crud::Crud;
Expand Down Expand Up @@ -55,15 +55,24 @@ pub async fn take_sell_action(
};

// Verify if invoice is valid
match is_valid_invoice(&payment_request, order_amount) {
match is_valid_invoice(&payment_request, order_amount, Some(order.fee as u64)) {
Ok(_) => {}
Err(e) => match e {
MostroError::ParsingInvoiceError
| MostroError::InvoiceExpiredError
| MostroError::MinExpirationTimeError
| MostroError::WrongAmountError
| MostroError::MinAmountError => {
send_dm(client, my_keys, &buyer_pubkey, e.to_string()).await?;
// We create a Message
let message = Message::new(
0,
Some(order.id),
None,
Action::CantDo,
Some(Content::TextMessage(e.to_string())),
);
let message = message.as_json()?;
send_dm(client, my_keys, &buyer_pubkey, message).await?;
error!("{e}");
return Ok(());
}
Expand All @@ -82,7 +91,7 @@ pub async fn take_sell_action(
return Ok(());
}
};
// Buyer can take pending orders only
// Buyer can take Pending or WaitingBuyerInvoice orders only
match order_status {
Status::Pending | Status::WaitingBuyerInvoice => {}
_ => {
Expand Down Expand Up @@ -122,8 +131,7 @@ pub async fn take_sell_action(
}
// Check market price value in sats - if order was with market price then calculate it and send a DM to buyer
if order.amount == 0 {
order.amount =
set_market_order_sats_amount(&mut order, buyer_pubkey, my_keys, pool, client).await?;
set_market_order_sats_amount(&mut order, buyer_pubkey, my_keys, pool, client).await?;
} else {
show_hold_invoice(
pool,
Expand Down
10 changes: 8 additions & 2 deletions src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -208,17 +208,23 @@ pub async fn update_order_event_id_status(
) -> anyhow::Result<bool> {
let mut conn = pool.acquire().await?;
let status = status.to_string();
// We calculate the bot fee
let fee = var("FEE").unwrap().parse::<f64>().unwrap() / 2.0;
let fee = fee * amount as f64;

let rows_affected = sqlx::query!(
r#"
UPDATE orders
SET
status = ?1,
amount = ?2,
event_id = ?3
WHERE id = ?4
fee = ?3,
event_id = ?4
WHERE id = ?5
"#,
status,
amount,
fee,
event_id,
order_id,
)
Expand Down
6 changes: 5 additions & 1 deletion src/flow.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::util::send_dm;
use dotenvy::var;
use log::info;
use mostro_core::{order::SmallOrder, Action, Content, Message, Status};
use nostr_sdk::prelude::*;
Expand All @@ -24,7 +25,7 @@ pub async fn hold_invoice_paid(hash: &str) {
}

// We send this data related to the order to the parties
let order_data = SmallOrder::new(
let mut order_data = SmallOrder::new(
order.id,
order.amount,
order.fiat_code.clone(),
Expand Down Expand Up @@ -63,6 +64,9 @@ pub async fn hold_invoice_paid(hash: &str) {
.unwrap();
status = Status::Active;
} else {
let buyer_fee = var("FEE").unwrap().parse::<f64>().unwrap() / 2.0;
let new_amount = order_data.amount as f64 - (buyer_fee * order_data.amount as f64);
order_data.amount = new_amount as i64;
// We ask to buyer for a new invoice
let message = Message::new(
0,
Expand Down
14 changes: 8 additions & 6 deletions src/lightning/invoice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,20 +12,22 @@ pub fn decode_invoice(payment_request: &str) -> Result<Invoice, MostroError> {
Ok(invoice)
}

/// Verify if an invoice is valid
/// Verify if a buyer invoice is valid
pub fn is_valid_invoice(
payment_request: &str,
amount: Option<u64>,
fee: Option<u64>,
) -> Result<Invoice, MostroError> {
let invoice = Invoice::from_str(payment_request)?;
let min_payment_amount = var("MIN_PAYMENT_AMT")
.expect("INVOICE_EXPIRATION_WINDOW is not set")
.expect("MIN_PAYMENT_AMT is not set")
.parse::<u64>()?;

let amount_msat = invoice.amount_milli_satoshis().unwrap_or(0) / 1000;
let fee = fee.unwrap_or(0);

if let Some(amt) = amount {
if amount_msat > 0 && amount_msat != amt {
if amount_msat > 0 && amount_msat != (amt - fee) {
return Err(MostroError::WrongAmountError);
}
}
Expand Down Expand Up @@ -62,21 +64,21 @@ mod tests {
#[test]
fn test_wrong_amount_invoice() {
let payment_request = "lnbcrt500u1p3l8zyapp5nc0ctxjt98xq9tgdgk9m8fepnp0kv6mnj6a83mfsannw46awdp4sdqqcqzpgxqyz5vqsp5a3axmz77s5vafmheq56uh49rmy59r9a3d0dm0220l8lzdp5jrtxs9qyyssqu0ft47j0r4lu997zuqgf92y8mppatwgzhrl0hzte7mzmwrqzf2238ylch82ehhv7pfcq6qcyu070dg85vu55het2edyljuezvcw5pzgqfncf3d";
let wrong_amount_err = is_valid_invoice(payment_request, Some(23));
let wrong_amount_err = is_valid_invoice(payment_request, Some(23), None);
assert_eq!(Err(MostroError::WrongAmountError), wrong_amount_err);
}

#[test]
fn test_is_expired_invoice() {
let payment_request = "lnbcrt500u1p3lzwdzpp5t9kgwgwd07y2lrwdscdnkqu4scrcgpm5pt9uwx0rxn5rxawlxlvqdqqcqzpgxqyz5vqsp5a6k7syfxeg8jy63rteywwjla5rrg2pvhedx8ajr2ltm4seydhsqq9qyyssq0n2uwlumsx4d0mtjm8tp7jw3y4da6p6z9gyyjac0d9xugf72lhh4snxpugek6n83geafue9ndgrhuhzk98xcecu2t3z56ut35mkammsqscqp0n";
let expired_err = is_valid_invoice(payment_request, None);
let expired_err = is_valid_invoice(payment_request, None, None);
assert_eq!(Err(MostroError::InvoiceExpiredError), expired_err);
}

#[test]
fn test_min_amount_invoice() {
let payment_request = "lnbcrt10n1p3l8ysvpp5scf3rd8e8j2f9k7qktfjmpqr4xazj5dr5ygp84wa22sen3wxcevsdqqcqzpgxqyz5vqsp55wp60pzn4889l56538zt7jcr2sgag4xreen3yuzpudlmac3acqls9qyyssqu8rmewmly2xyuqn03vttwsysnnelr0thjstavk2qu6ygs7ampe08h74u9a7qlkuudagpy6mc06gz6qgmq3x582u54rd8gdx3nfvxmlqqrttwdj";
let min_amount_err = is_valid_invoice(payment_request, None);
let min_amount_err = is_valid_invoice(payment_request, None, None);
assert_eq!(Err(MostroError::MinAmountError), min_amount_err);
}
}
18 changes: 9 additions & 9 deletions src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,7 @@ pub async fn show_hold_invoice(
let mut ln_client = lightning::LndConnector::new().await;
// Add fee of seller to hold invoice
let seller_fee = var("FEE").unwrap().parse::<f64>().unwrap_or(0.003) / 2.0;
let seller_total_amout = (seller_fee * order.amount as f64) + order.amount as f64;
let seller_total_amount = (seller_fee * order.amount as f64) + order.amount as f64;

// Now we generate the hold invoice that seller should pay
let (invoice_response, preimage, hash) = ln_client
Expand All @@ -235,7 +235,7 @@ pub async fn show_hold_invoice(
&order.fiat_code,
&order.fiat_amount.to_string(),
)?,
seller_total_amout as i64,
seller_total_amount as i64,
)
.await?;
if let Some(invoice) = payment_request {
Expand Down Expand Up @@ -319,17 +319,17 @@ pub async fn set_market_order_sats_amount(
client: &Client,
) -> Result<i64> {
// Update amount order
let new_sats_amout =
let new_sats_amount =
get_market_quote(&order.fiat_amount, &order.fiat_code, &order.premium).await?;

// Add fee of seller to hold invoice
let buyer_fee = var("FEE").unwrap().parse::<f64>().unwrap_or(0.003) / 2.0;
let buyer_total_amout = new_sats_amout as f64 - (buyer_fee * new_sats_amout as f64);
// We calculate the bot fee
let fee = var("FEE").unwrap().parse::<f64>().unwrap() / 2.0;
let buyer_total_amount = new_sats_amount as f64 - (fee * new_sats_amount as f64);

// We send this data related to the order to the parties
// We send this data related to the buyer
let order_data = SmallOrder::new(
order.id,
buyer_total_amout as i64,
buyer_total_amount as i64,
order.fiat_code.clone(),
order.fiat_amount,
order.payment_method.clone(),
Expand All @@ -350,7 +350,7 @@ pub async fn set_market_order_sats_amount(
send_dm(client, my_keys, &buyer_pubkey, message).await?;

// Update order with new sats value
order.amount = buyer_total_amout as i64;
order.amount = buyer_total_amount as i64;
update_order_event(
pool,
client,
Expand Down

0 comments on commit f71082a

Please sign in to comment.