Skip to content

Commit

Permalink
chore: Set hodl invoice to Settled on lnd event
Browse files Browse the repository at this point in the history
It's better to update our state only if the same state has been applied to lnd.
  • Loading branch information
holzeis committed Jun 4, 2024
1 parent c507a18 commit 2434857
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 4 deletions.
17 changes: 15 additions & 2 deletions coordinator/src/db/hodl_invoice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,19 @@ pub fn get_r_hash_by_order_id(conn: &mut PgConnection, order_id: Uuid) -> QueryR
.get_result(conn)
}

/// Returns the pre image of the hodl invoice associated with the order id
/// If the hodl invoice can not be found a [`Not Found`] error is returned
/// If the hodl invoice is found the pre_image is optional, as it might have not yet been set.
pub fn get_pre_image_by_order_id(
conn: &mut PgConnection,
order_id: Uuid,
) -> QueryResult<Option<String>> {
hodl_invoices::table
.filter(hodl_invoices::order_id.eq(order_id))
.select(hodl_invoices::pre_image)
.get_result(conn)
}

pub fn update_hodl_invoice_to_accepted(
conn: &mut PgConnection,
hash: &str,
Expand All @@ -91,10 +104,10 @@ pub fn update_hodl_invoice_to_accepted(

pub fn update_hodl_invoice_to_settled(
conn: &mut PgConnection,
order_id: Uuid,
r_hash: String,
) -> QueryResult<Option<String>> {
diesel::update(hodl_invoices::table)
.filter(hodl_invoices::order_id.eq(order_id))
.filter(hodl_invoices::r_hash.eq(r_hash))
.set((
hodl_invoices::updated_at.eq(OffsetDateTime::now_utc()),
hodl_invoices::invoice_state.eq(InvoiceState::Settled),
Expand Down
18 changes: 18 additions & 0 deletions coordinator/src/node/invoice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,24 @@ pub fn spawn_invoice_watch(
}
InvoiceState::Settled => {
tracing::info!(%trader_pubkey, r_hash, "Accepted hodl invoice has been settled.");
if let Err(e) = spawn_blocking({
let r_hash = r_hash.clone();
move || {
let mut conn = pool.get()?;
db::hodl_invoice::update_hodl_invoice_to_settled(
&mut conn, r_hash,
)?;
anyhow::Ok(())
}
})
.await
.expect("task to finish")
{
tracing::error!(
r_hash,
"Failed to set hodl invoice to failed. Error: {e:#}"
);
}
break;
}
InvoiceState::Canceled => {
Expand Down
3 changes: 1 addition & 2 deletions coordinator/src/trade/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -225,8 +225,7 @@ impl TradeExecutor {
let pool = self.node.pool.clone();
move || {
let mut conn = pool.get()?;
let pre_image =
db::hodl_invoice::update_hodl_invoice_to_settled(&mut conn, order_id)?;
let pre_image = db::hodl_invoice::get_pre_image_by_order_id(&mut conn, order_id)?;

anyhow::Ok(pre_image)
}
Expand Down

0 comments on commit 2434857

Please sign in to comment.