Skip to content

Commit

Permalink
Persist payment attempts before starting
Browse files Browse the repository at this point in the history
  • Loading branch information
danielgranhao committed Nov 20, 2023
1 parent f016df3 commit d01b703
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
36 changes: 36 additions & 0 deletions libs/sdk-core/src/breez_services.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use std::cmp::max;
use std::fs::OpenOptions;
use std::io::Write;
use std::str::FromStr;
Expand Down Expand Up @@ -264,12 +265,15 @@ impl BreezServices {
});
}

let amount_msat = max(provided_amount_msat, invoice_amount_msat);

match self
.persister
.get_completed_payment_by_hash(&parsed_invoice.payment_hash)?
{
Some(_) => Err(SendPaymentError::AlreadyPaid),
None => {
self.persist_pending_payment(&parsed_invoice, amount_msat)?;
let payment_res = self
.node_api
.send_payment(req.bolt11.clone(), req.amount_msat)
Expand Down Expand Up @@ -905,6 +909,38 @@ impl BreezServices {
Ok(())
}

fn persist_pending_payment(
&self,
invoice: &LNInvoice,
amount_msat: u64,
) -> Result<(), SendPaymentError> {
self.persister.insert_or_update_payments(&[Payment {
id: invoice.payment_hash.clone(),
payment_type: PaymentType::Sent,
payment_time: SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs() as i64,
amount_msat,
fee_msat: 0,
status: PaymentStatus::Pending,
description: invoice.description.clone(),
details: PaymentDetails::Ln {
data: LnPaymentDetails {
payment_hash: invoice.payment_hash.clone(),
label: String::new(),
destination_pubkey: invoice.payee_pubkey.clone(),
payment_preimage: String::new(),
keysend: false,
bolt11: invoice.bolt11.clone(),
lnurl_success_action: None,
ln_address: None,
lnurl_metadata: None,
lnurl_withdraw_endpoint: None,
swap_info: None,
},
},
}])?;
Ok(())
}

async fn on_payment_completed(
&self,
node_id: String,
Expand Down
9 changes: 9 additions & 0 deletions libs/sdk-core/src/error.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use anyhow::Result;
use bitcoin::util::bip32;
use std::time::SystemTimeError;
use thiserror::Error;

use crate::{
Expand Down Expand Up @@ -676,6 +677,14 @@ impl From<SdkError> for SendPaymentError {
}
}

impl From<SystemTimeError> for SendPaymentError {
fn from(err: SystemTimeError) -> Self {
Self::Generic {
err: err.to_string(),
}
}
}

#[macro_export]
macro_rules! ensure_sdk {
($cond:expr, $err:expr) => {
Expand Down

0 comments on commit d01b703

Please sign in to comment.