Skip to content
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
57 changes: 7 additions & 50 deletions src/app/restore_session.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use crate::app::context::AppContext;
use crate::db::{find_failed_payment_for_master_key, RestoreSessionManager};
use crate::util::{enqueue_order_msg, enqueue_restore_session_msg};
use crate::{db::RestoreSessionManager, util::enqueue_restore_session_msg};
use mostro_core::prelude::*;
use nostr_sdk::prelude::*;

Expand All @@ -11,7 +10,7 @@ pub async fn restore_session_action(
ctx: &AppContext,
event: &UnwrappedMessage,
) -> Result<(), MostroError> {
let pool = ctx.pool_arc();
let pool = ctx.pool();
// Get user master key from the event sender
let master_key = event.identity.to_string();
// Get trade key from the event rumor
Expand All @@ -34,27 +33,23 @@ pub async fn restore_session_action(

// Create a new manager for this specific restore session
let manager = RestoreSessionManager::new();
let pool_clone = pool.clone();

// Start the background processing
manager
.start_restore_session(pool.as_ref().clone(), master_key.clone())
.start_restore_session(pool_clone, master_key.clone())
.await?;

// Start a background task to handle the results
tokio::spawn(async move {
handle_restore_session_results(manager, trade_key, master_key, pool).await;
handle_restore_session_results(manager, trade_key).await;
});

Ok(())
}

/// Handle restore session results in the background
async fn handle_restore_session_results(
mut manager: RestoreSessionManager,
trade_key: String,
master_key: String,
pool: std::sync::Arc<sqlx::SqlitePool>,
) {
async fn handle_restore_session_results(mut manager: RestoreSessionManager, trade_key: String) {
// Wait for the result with a timeout
let timeout = tokio::time::Duration::from_secs(60 * 60); // 1 hour timeout

Expand All @@ -63,10 +58,8 @@ async fn handle_restore_session_results(
// Send the restore session response
if let Err(e) = send_restore_session_response(
&trade_key,
&master_key,
result.restore_orders,
result.restore_disputes,
pool.clone(),
)
Comment on lines 59 to 63
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Restore AddInvoice resend for failed payments

This revert drops the only restore-session path that re-queues Action::AddInvoice for orders stuck in settled-hold-invoice with failed_payment=true. In the current flow, send_restore_session_response now only sends RestoreData, so if the buyer was offline when the original failure notification was emitted, reconnecting via restore-session will not trigger the invoice re-prompt and that order can remain blocked until manual intervention. Please keep restore-session tied to failed-payment lookup so those buyers reliably receive the retry prompt after reconnect.

Useful? React with 👍 / 👎.

.await
{
Expand All @@ -89,19 +82,13 @@ async fn handle_restore_session_results(
/// Send restore session response to the user
async fn send_restore_session_response(
trade_key: &str,
master_key: &str,
orders: Vec<RestoredOrdersInfo>,
disputes: Vec<RestoredDisputesInfo>,
pool: std::sync::Arc<sqlx::SqlitePool>,
) -> Result<(), MostroError> {
// Convert trade_key string to PublicKey
let trade_pubkey =
PublicKey::from_hex(trade_key).map_err(|_| MostroCantDo(CantDoReason::InvalidPubkey))?;

// Collect restored order IDs before moving orders into the payload
let restored_ids: std::collections::HashSet<uuid::Uuid> =
orders.iter().map(|o| o.order_id).collect();

// Send the order data using the flat structure
enqueue_restore_session_msg(
Some(Payload::RestoreData(RestoreSessionInfo {
Expand All @@ -112,37 +99,7 @@ async fn send_restore_session_response(
)
.await;

tracing::info!("Restore session response sent to user {}", trade_key);

// Re-send AddInvoice for any orders stuck in settled-hold-invoice with failed payment

match find_failed_payment_for_master_key(&pool, master_key).await {
Ok(failed_orders) => {
for order in failed_orders {
if restored_ids.contains(&order.id) {
enqueue_order_msg(
None,
Some(order.id),
Action::AddInvoice,
Some(Payload::Order(SmallOrder::from(order.clone()))),
trade_pubkey,
None,
)
.await;
tracing::info!(
"Re-sent AddInvoice for order {} on restore-session (failed payment)",
order.id
);
}
}
}
Err(e) => {
tracing::error!(
"Failed to query failed payments during restore-session: {}",
e
);
}
}
tracing::info!("Restore session response sent to user {}", trade_key,);

Ok(())
}
Expand Down
106 changes: 0 additions & 106 deletions src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -568,29 +568,6 @@ pub async fn edit_pubkeys_order(pool: &SqlitePool, order: &Order) -> Result<Orde
Ok(order)
}

/// Returns orders with `failed_payment = true` and `status = "settled-hold-invoice"`
/// for the given `master_buyer_pubkey`. Used during restore-session to re-send
/// `Action::AddInvoice` to buyers whose payment failed and need to provide a new invoice.
pub async fn find_failed_payment_for_master_key(
pool: &SqlitePool,
master_key: &str,
) -> Result<Vec<Order>, MostroError> {
let orders = sqlx::query_as::<_, Order>(
r#"
SELECT *
FROM orders
WHERE failed_payment = true
AND status = 'settled-hold-invoice'
AND master_buyer_pubkey = ?1
"#,
)
.bind(master_key)
.fetch_all(pool)
.await
.map_err(|e| MostroInternalErr(ServiceError::DbAccessError(e.to_string())))?;
Ok(orders)
}

pub async fn find_order_by_hash(pool: &SqlitePool, hash: &str) -> Result<Order, MostroError> {
let order = sqlx::query_as::<_, Order>(
r#"
Expand Down Expand Up @@ -1683,89 +1660,6 @@ mod tests {
);
}

// -- Tests for find_failed_payment_for_master_key --
#[tokio::test]
async fn test_find_failed_payment_for_master_key_returns_matching() {
let pool = setup_orders_db().await.unwrap();
let master_key = "a".repeat(64);
// Insert matching order: correct master_buyer_pubkey, failed_payment=true, correct status
sqlx::query(
r#"INSERT INTO orders (id, kind, event_id, status, premium, payment_method,
amount, fiat_code, fiat_amount, created_at, expires_at,
failed_payment, payment_attempts, dev_fee, dev_fee_paid,
master_buyer_pubkey)
VALUES (?1, 'buy', 'ev1', 'settled-hold-invoice', 0, 'lightning',
100000, 'USD', 100, 1700000000, 1700086400,
1, 3, 0, 0, ?2)"#,
)
.bind(uuid::Uuid::new_v4())
.bind(&master_key)
.execute(&pool)
.await
.unwrap();
let result = super::find_failed_payment_for_master_key(&pool, &master_key)
.await
.unwrap();
assert_eq!(result.len(), 1, "Should find matching failed payment order");
}

#[tokio::test]
async fn test_find_failed_payment_for_master_key_ignores_different_key() {
let pool = setup_orders_db().await.unwrap();
let master_key = "a".repeat(64);
let other_key = "b".repeat(64);
// Insert order for a different master key
sqlx::query(
r#"INSERT INTO orders (id, kind, event_id, status, premium, payment_method,
amount, fiat_code, fiat_amount, created_at, expires_at,
failed_payment, payment_attempts, dev_fee, dev_fee_paid,
master_buyer_pubkey)
VALUES (?1, 'buy', 'ev1', 'settled-hold-invoice', 0, 'lightning',
100000, 'USD', 100, 1700000000, 1700086400,
1, 3, 0, 0, ?2)"#,
)
.bind(uuid::Uuid::new_v4())
.bind(&other_key)
.execute(&pool)
.await
.unwrap();
let result = super::find_failed_payment_for_master_key(&pool, &master_key)
.await
.unwrap();
assert!(
result.is_empty(),
"Should not return orders for different master key"
);
}

#[tokio::test]
async fn test_find_failed_payment_for_master_key_ignores_non_failed() {
let pool = setup_orders_db().await.unwrap();
let master_key = "a".repeat(64);
// Insert order with failed_payment = false
sqlx::query(
r#"INSERT INTO orders (id, kind, event_id, status, premium, payment_method,
amount, fiat_code, fiat_amount, created_at, expires_at,
failed_payment, payment_attempts, dev_fee, dev_fee_paid,
master_buyer_pubkey)
VALUES (?1, 'buy', 'ev1', 'settled-hold-invoice', 0, 'lightning',
100000, 'USD', 100, 1700000000, 1700086400,
0, 0, 0, 0, ?2)"#,
)
.bind(uuid::Uuid::new_v4())
.bind(&master_key)
.execute(&pool)
.await
.unwrap();
let result = super::find_failed_payment_for_master_key(&pool, &master_key)
.await
.unwrap();
assert!(
result.is_empty(),
"Should not return orders where failed_payment is false"
);
}

// -- Tests for find_order_by_hash --

#[tokio::test]
Expand Down