mostro 0.17.4

Lightning Network peer-to-peer nostr platform
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
use crate::app::bond;
use crate::app::context::AppContext;
use crate::app::dispute::close_dispute_after_user_resolution;
use crate::lightning::LndConnector;
use crate::lnurl::resolv_ln_address;
use crate::nip33::{new_order_event, order_to_tags};
use crate::util::{enqueue_order_msg, get_order, settle_seller_hold_invoice, update_order_event};

use fedimint_tonic_lnd::lnrpc::payment::PaymentStatus;
use lnurl::lightning_address::LightningAddress;
use mostro_core::prelude::*;
use nostr_sdk::prelude::*;
use sqlx::{Pool, Sqlite};
use sqlx_crud::Crud;
use std::cmp::Ordering;
use std::str::FromStr;
use tokio::sync::mpsc::channel;
use tracing::info;

/// Check if order has failed payment retries
pub async fn check_failure_retries(
    ctx: &AppContext,
    order: &Order,
    request_id: Option<u64>,
) -> Result<Order, MostroError> {
    let mut order = order.clone();

    let pool = ctx.pool();

    // Get max number of retries
    let ln_settings = &ctx.settings().lightning;
    let retries_number = ln_settings.payment_attempts as i64;

    let is_first_failure = order.payment_attempts == 0;

    // Count payment retries up to limit
    order.count_failed_payment(retries_number);

    let buyer_pubkey = order.get_buyer_pubkey().map_err(MostroInternalErr)?;

    // Only send notification on first failure
    if is_first_failure {
        // Create payment failed payload with retry configuration
        let payment_failed_info = PaymentFailedInfo {
            payment_attempts: ln_settings.payment_attempts.saturating_sub(1),
            payment_retries_interval: ln_settings.payment_retries_interval,
        };

        enqueue_order_msg(
            request_id,
            Some(order.id),
            Action::PaymentFailed,
            Some(Payload::PaymentFailed(payment_failed_info)),
            buyer_pubkey,
            None,
        )
        .await;
    } else if order.payment_attempts >= retries_number {
        // Clone order
        let mut order_payment_failed = order.clone();
        // Update amount notified to the buyer (only Mostro fee, not dev fee)
        order_payment_failed.amount = order_payment_failed.amount.saturating_sub(order.fee);
        if order_payment_failed.amount <= 0 {
            return Err(MostroCantDo(CantDoReason::InvalidAmount));
        }
        // Check errors
        if mostro_core::order::Kind::from_str(&order.kind).is_err() {
            return Err(MostroCantDo(CantDoReason::InvalidOrderKind));
        }
        // Check status
        if order_payment_failed.get_order_status().is_err() {
            return Err(MostroInternalErr(ServiceError::InvalidOrderStatus));
        }

        // Send message to buyer indicating payment failed
        enqueue_order_msg(
            request_id,
            Some(order.id),
            Action::AddInvoice,
            Some(Payload::Order(SmallOrder::from(
                order_payment_failed.clone(),
            ))),
            buyer_pubkey,
            None,
        )
        .await;
    }

    // Only update payment-retry fields to avoid overwriting fields modified by
    // concurrent processes (dev_fee_paid, dev_fee_payment_hash, status, etc.)
    sqlx::query("UPDATE orders SET failed_payment = ?, payment_attempts = ? WHERE id = ?")
        .bind(order.failed_payment)
        .bind(order.payment_attempts)
        .bind(order.id)
        .execute(pool)
        .await
        .map_err(|e| MostroInternalErr(ServiceError::DbAccessError(e.to_string())))?;

    Ok(order)
}

/// Handles the release action for an order, managing the release of funds and subsequent order flow.
///
/// This function is responsible for processing the release of funds in a trade, which is a critical
/// step in the order lifecycle. It verifies the seller's identity, manages the settlement of hold
/// invoices, and coordinates the creation of child orders for range orders. The function also
/// handles notifications to both buyer and seller about the release status.
///
/// # Arguments
///
/// * `ctx` - Application context containing the database pool and other dependencies
/// * `msg` - The message containing the release request and associated metadata
/// * `event` - The unwrapped gift event containing the seller's signature and verification data
/// * `my_keys` - The Mostro node's keys used for signing events and messages
/// * `ln_client` - Lightning network client for invoice settlement
///
/// # Returns
///
/// Returns a `Result<(), MostroError>` where:
/// * `Ok(())` indicates successful release of funds and order processing
/// * `Err(MostroError)` indicates an error occurred during the process
///
/// # Flow
///
/// 1. Validates the request:
///    - Verifies the seller's identity matches the order
///    - Checks if the order status allows for release
///
/// 2. Processes the release:
///    - Settles the seller's hold invoice
///    - Updates the order status to SettledHoldInvoice
///    - Notifies the buyer about the release
///
/// 3. Handles child orders (for range orders):
///    - Creates and processes child orders if applicable
///    - Sends notifications to next traders in the sequence
///
/// 4. Sends notifications:
///    - Notifies seller about hold invoice settlement
///    - Requests rating from seller
///    - Initiates payment to buyer
///
/// # Errors
///
/// This function may return the following errors:
/// * `MostroCantDo(CantDoReason::InvalidPeer)` - If the seller's identity doesn't match
/// * `MostroCantDo(CantDoReason::NotAllowedByStatus)` - If the order status doesn't allow release
/// * `MostroInternalErr(ServiceError::DbAccessError)` - If database operations fail
/// * `MostroInternalErr(ServiceError::NostrError)` - If there are issues with Nostr operations
/// * `MostroInternalErr(ServiceError::InvoiceInvalidError)` - If there are issues with the invoice
///
/// # Security Considerations
///
/// * Only the seller can release funds for their order
/// * The seller's identity is verified through the event signature
/// * Hold invoices are settled only after proper verification
pub async fn release_action(
    ctx: &AppContext,
    msg: Message,
    event: &UnwrappedMessage,
    my_keys: &Keys,
    ln_client: &mut LndConnector,
) -> Result<(), MostroError> {
    let pool = ctx.pool();
    // Get request id
    let request_id = msg.get_inner_message_kind().request_id;
    // Get order
    let mut order = get_order(&msg, pool).await?;
    // Get seller pubkey hex
    let seller_pubkey = order.get_seller_pubkey().map_err(MostroInternalErr)?;
    // We send a message to buyer indicating seller released funds
    let buyer_pubkey = order.get_buyer_pubkey().map_err(MostroInternalErr)?;

    // Check if the pubkey is the seller pubkey - Only the seller can release funds
    if seller_pubkey != event.sender {
        return Err(MostroCantDo(CantDoReason::InvalidPeer));
    }

    // Check if order is in status fiat sent or dispute
    if order.check_status(Status::FiatSent).is_err() && order.check_status(Status::Dispute).is_err()
    {
        return Err(MostroCantDo(CantDoReason::NotAllowedByStatus));
    }

    // Get next trade key
    let next_trade = msg
        .get_inner_message_kind()
        .get_next_trade_key()
        .map_err(MostroInternalErr)?;

    // Settle seller hold invoice
    settle_seller_hold_invoice(event, ln_client, Action::Released, false, &order).await?;
    // Update order event with status SettledHoldInvoice
    order = update_order_event(my_keys, Status::SettledHoldInvoice, &order)
        .await
        .map_err(|e| MostroInternalErr(ServiceError::NostrError(e.to_string())))?;

    // Persist the status change to DB before calling do_payment.
    // do_payment spawns async tasks that capture an Order copy; without this
    // explicit write the settled-hold-invoice status only lived in memory and
    // was persisted as a side-effect of the full-row writes in
    // check_failure_retries / payment_success (now replaced by targeted updates).
    let result =
        sqlx::query("UPDATE orders SET status = ?, event_id = ? WHERE id = ? AND status IN (?, ?)")
            .bind(&order.status)
            .bind(&order.event_id)
            .bind(order.id)
            .bind(Status::FiatSent.to_string())
            .bind(Status::Dispute.to_string())
            .execute(pool)
            .await
            .map_err(|e| MostroInternalErr(ServiceError::DbAccessError(e.to_string())))?;

    if result.rows_affected() == 0 {
        tracing::warn!(
            "Order {} not transitioned to settled-hold-invoice: status changed concurrently",
            order.id
        );
        return Ok(());
    }

    // If there was an active dispute on this order, close it since the seller
    // released the funds, resolving the situation.
    close_dispute_after_user_resolution(ctx, &order, DisputeStatus::Settled, my_keys, "release")
        .await;

    enqueue_order_msg(
        None,
        Some(order.id),
        Action::Released,
        None,
        buyer_pubkey,
        None,
    )
    .await;

    // Handle child order for range orders
    if let Ok((Some(child_order), Some(event))) = get_child_order(ctx, order.clone(), my_keys).await
    {
        let client = ctx.nostr_client();
        if client.send_event(&event).await.is_err() {
            tracing::warn!("Failed sending child order event for order id: {}. This may affect order synchronization", child_order.id)
        }
        handle_child_order(child_order, &order, next_trade, ctx.pool(), request_id)
            .await
            .map_err(|e| MostroInternalErr(ServiceError::DbAccessError(e.to_string())))?;
    }

    // We send a HoldInvoicePaymentSettled message to seller, the client should
    // indicate *funds released* message to seller
    enqueue_order_msg(
        request_id,
        Some(order.id),
        Action::HoldInvoicePaymentSettled,
        None,
        seller_pubkey,
        None,
    )
    .await;

    // We send a message to seller indicating seller released funds
    enqueue_order_msg(
        None,
        Some(order.id),
        Action::Rate,
        None,
        seller_pubkey,
        None,
    )
    .await;

    // Phase 1: release any taker bond attached to this order before we
    // hand off to the buyer payment task. Slashing is intentionally not
    // wired in yet — that's Phase 2+. A failed bond release is logged but
    // does not block trade finalization.
    bond::release_bonds_for_order_or_warn(pool, order.id, "release_action").await;

    // Finally we try to pay buyer's invoice
    let _ = do_payment(ctx, order, request_id).await;

    Ok(())
}

/// Helper function to handle buy order case in child order creation
fn handle_buy_child_order(
    child_order: &mut Order,
    order: &Order,
    normal_buyer_idkey: Option<String>,
) -> Result<(Option<String>, Option<i64>), MostroError> {
    let next_buyer_pubkey = order.next_trade_pubkey.clone().ok_or_else(|| {
        MostroInternalErr(ServiceError::UnexpectedError(
            "Next trade buyer pubkey is missing".to_string(),
        ))
    })?;

    child_order.buyer_pubkey = Some(next_buyer_pubkey.clone());
    child_order.trade_index_buyer = order.next_trade_index;
    child_order.creator_pubkey = next_buyer_pubkey.clone();
    // if user is in full privacy mode, use the next trade key
    // if user is in normal mode, use the master buyer pubkey
    match normal_buyer_idkey {
        Some(idkey) => {
            child_order.master_buyer_pubkey = Some(idkey);
        }
        None => {
            child_order.master_buyer_pubkey = Some(next_buyer_pubkey);
        }
    }

    // Clear next trade fields for buy order
    child_order.next_trade_index = None;
    child_order.next_trade_pubkey = None;

    Ok((
        child_order.buyer_pubkey.clone(),
        child_order.trade_index_buyer,
    ))
}

/// Helper function to handle sell order case in child order creation
fn handle_sell_child_order(
    child_order: &mut Order,
    next_trade: Option<(String, u32)>,
    normal_seller_idkey: Option<String>,
) -> Result<(Option<String>, Option<i64>), MostroError> {
    let (next_trade_pubkey, next_trade_index) = next_trade.ok_or_else(|| {
        MostroInternalErr(ServiceError::UnexpectedError(
            "Next trade seller pubkey is missing".to_string(),
        ))
    })?;

    let next_trade_pubkey = PublicKey::from_str(&next_trade_pubkey)
        .map_err(|_| MostroInternalErr(ServiceError::InvalidPubkey))?;

    child_order.seller_pubkey = Some(next_trade_pubkey.to_string());
    child_order.trade_index_seller = Some(next_trade_index as i64);
    child_order.creator_pubkey = next_trade_pubkey.to_string();
    // if user is in full privacy mode, use the next trade key as master seller pubkey
    // if user is in normal mode, use the master seller pubkey as master seller pubkey
    match normal_seller_idkey {
        Some(idkey) => {
            child_order.master_seller_pubkey = Some(idkey);
        }
        None => {
            child_order.master_seller_pubkey = Some(next_trade_pubkey.to_string());
        }
    }

    Ok((
        child_order.seller_pubkey.clone(),
        child_order.trade_index_seller,
    ))
}

/// Manages the creation and update of child orders in a range order sequence.
///
/// This function handles the creation and setup of child orders for range orders, which are orders
/// that can be split into multiple smaller orders. It manages assignment of pubkeys, sets up
/// trade indices, and handles notifications to the next trader in the sequence.
///
/// # Arguments
///
/// * `child_order` - The child order to be created/updated. This is a new order derived from the parent order.
/// * `order` - The parent order from which the child order is derived. Contains the original order details.
/// * `next_trade` - Optional tuple containing the next trader's information:
///   - First element: The public key of the next trader
///   - Second element: The trade index for the next trade
/// * `pool` - Database connection pool for storing the child order
/// * `request_id` - Optional request ID used for message queuing and tracking
///
/// # Returns
///
/// Returns a `Result<(), MostroError>` where:
/// * `Ok(())` indicates successful creation and setup of the child order
/// * `Err(MostroError)` indicates an error occurred during the process
///
/// # Flow
///
/// 1. Determines if users are in rating mode or full privacy mode
/// 2. Based on order type (buy/sell):
///    - For buy orders: Sets up buyer-specific fields and assigns buyer pubkey
///    - For sell orders: Sets up seller-specific fields and assigns seller pubkey
/// 3. Creates a new pending child order
/// 4. If next trade information is available:
///    - Enqueues a notification message to the next trader
/// 5. Stores the child order in the database
///
/// # Errors
///
/// This function may return the following errors:
/// * `MostroInternalErr(ServiceError::UnexpectedError)` - If the order type or creator is invalid
/// * `MostroInternalErr(ServiceError::DbAccessError)` - If database operations fail
/// * `MostroInternalErr(ServiceError::NostrError)` - If there are issues with Nostr operations
async fn handle_child_order(
    mut child_order: Order,
    order: &Order,
    next_trade: Option<(String, u32)>,
    pool: &Pool<Sqlite>,
    request_id: Option<u64>,
) -> Result<(), MostroError> {
    // Check if users are in rating mode or full privacy mode - if a key is Some the user in in normal mode
    // if a key is None the user is in full privacy mode
    let (normal_buyer_idkey, normal_seller_idkey) =
        order.is_full_privacy_order().map_err(|_| {
            MostroInternalErr(ServiceError::UnexpectedError(
                "Error creating order event".to_string(),
            ))
        })?;

    let (notification_pubkey, new_trade_index) = if order.is_buy_order().is_ok()
        && order.buyer_pubkey.as_ref() == Some(&order.creator_pubkey)
    {
        handle_buy_child_order(&mut child_order, order, normal_buyer_idkey)?
    } else if order.is_sell_order().is_ok()
        && order.seller_pubkey.as_ref() == Some(&order.creator_pubkey)
    {
        handle_sell_child_order(&mut child_order, next_trade, normal_seller_idkey)?
    } else {
        return Err(MostroInternalErr(ServiceError::UnexpectedError(
            "Invalid order type or creator".to_string(),
        )));
    };

    // Prepare new pending child order
    let new_order = child_order.as_new_order();

    if let (Some(destination_pubkey), new_trade_index) = (notification_pubkey, new_trade_index) {
        // If we have next trade pubkey and index we can set them in child order
        enqueue_order_msg(
            request_id,
            new_order.id,
            Action::NewOrder,
            Some(Payload::Order(new_order)),
            PublicKey::from_str(&destination_pubkey).map_err(|_| {
                MostroInternalErr(ServiceError::NostrError("Invalid pubkey".to_string()))
            })?,
            new_trade_index,
        )
        .await;
    } else {
        return Err(MostroInternalErr(ServiceError::UnexpectedError(
            "Next trade index or pubkey is missing - user cannot be notified".to_string(),
        )));
    }

    // Create the child order in database
    child_order
        .create(pool)
        .await
        .map_err(|e| MostroInternalErr(ServiceError::DbAccessError(e.to_string())))?;

    Ok(())
}

pub async fn do_payment(
    ctx: &AppContext,
    mut order: Order,
    request_id: Option<u64>,
) -> Result<(), MostroError> {
    let payment_request = match order.buyer_invoice.as_ref() {
        Some(req) => req.to_string(),
        _ => return Err(MostroInternalErr(ServiceError::InvoiceInvalidError)),
    };

    let ln_addr = LightningAddress::from_str(&payment_request);
    // Calculate buyer's portion after subtracting only the Mostro fee
    // Dev fee is NOT charged to buyer - it's paid by mostrod from its earnings
    let amount = (order.amount as u64).saturating_sub(order.fee as u64);
    if amount == 0 {
        return Err(MostroInternalErr(ServiceError::InvoiceInvalidError));
    }
    let payment_request = if let Ok(addr) = ln_addr {
        resolv_ln_address(&addr.to_string(), amount)
            .await
            .map_err(|_| MostroInternalErr(ServiceError::LnAddressParseError))?
    } else {
        payment_request
    };
    let mut ln_client_payment = LndConnector::new().await?;
    let (tx, mut rx) = channel(100);

    let payment_task = ln_client_payment.send_payment(&payment_request, amount as i64, tx);
    if let Err(paymement_result) = payment_task.await {
        info!("Error during ln payment : {}", paymement_result);
        if let Ok(failed_payment) = check_failure_retries(ctx, &order, request_id).await {
            info!(
                "Order id {} has {} failed payments retries",
                failed_payment.id, failed_payment.payment_attempts
            );
        }
    }

    // Get Mostro keys from context
    let my_keys = ctx.keys().clone();

    // Get buyer and seller pubkeys
    let buyer_pubkey = order.get_buyer_pubkey().map_err(MostroInternalErr)?;

    // Clone ctx for the async closure
    let ctx = ctx.clone();

    let payment = {
        async move {
            // We redeclare vars to use inside this block
            // Receiving msgs from send_payment()
            while let Some(msg) = rx.recv().await {
                if let Ok(status) = PaymentStatus::try_from(msg.payment.status) {
                    match status {
                        PaymentStatus::Succeeded => {
                            info!(
                                "Order Id {}: Invoice with hash: {} paid!",
                                order.id, msg.payment.payment_hash
                            );
                            let _ = payment_success(
                                &ctx,
                                &mut order,
                                buyer_pubkey,
                                &my_keys,
                                request_id,
                            )
                            .await;
                        }
                        PaymentStatus::Failed => {
                            info!(
                                "Order Id {}: Invoice with hash: {} has failed!",
                                order.id, msg.payment.payment_hash
                            );

                            // Mark payment as failed
                            if let Ok(failed_payment) =
                                check_failure_retries(&ctx, &order, request_id).await
                            {
                                info!(
                                    "Order id {} has {} failed payments retries",
                                    failed_payment.id, failed_payment.payment_attempts
                                );
                            }
                        }
                        _ => {}
                    }
                }
            }
        }
    };
    tokio::spawn(payment);
    Ok(())
}

async fn payment_success(
    ctx: &AppContext,
    order: &mut Order,
    buyer_pubkey: PublicKey,
    my_keys: &Keys,
    request_id: Option<u64>,
) -> Result<()> {
    // Purchase completed message to buyer
    enqueue_order_msg(
        None,
        Some(order.id),
        Action::PurchaseCompleted,
        None,
        buyer_pubkey,
        None,
    )
    .await;

    let pool = ctx.pool();

    if let Ok(order_updated) = update_order_event(my_keys, Status::Success, order).await {
        // Only update status and event_id to avoid overwriting fields modified by
        // concurrent processes (dev_fee_paid, dev_fee_payment_hash, etc.)
        // The WHERE guard prevents double success transitions from concurrent tasks.
        let result =
            sqlx::query("UPDATE orders SET status = ?, event_id = ? WHERE id = ? AND status = ?")
                .bind(&order_updated.status)
                .bind(&order_updated.event_id)
                .bind(order_updated.id)
                .bind(Status::SettledHoldInvoice.to_string())
                .execute(pool)
                .await
                .map_err(|e| MostroInternalErr(ServiceError::DbAccessError(e.to_string())))?;

        if result.rows_affected() == 0 {
            tracing::warn!(
                "Order {} not transitioned to success: already processed by another task",
                order_updated.id
            );
            return Ok(());
        }

        // Send dm to buyer to rate counterpart
        enqueue_order_msg(
            request_id,
            Some(order_updated.id),
            Action::Rate,
            None,
            buyer_pubkey,
            None,
        )
        .await;
    }
    Ok(())
}

/// Check if order is range type
/// Add parent range id and update max amount
/// publish a new replaceable kind nostr event with the status updated
/// and update on local database the status and new event id
pub async fn get_child_order(
    ctx: &AppContext,
    order: Order,
    my_keys: &Keys,
) -> Result<(Option<Order>, Option<Event>), MostroError> {
    let (Some(max_amount), Some(min_amount)) = (order.max_amount, order.min_amount) else {
        return Ok((None, None));
    };

    if let Some(new_max) = max_amount.checked_sub(order.fiat_amount) {
        let mut new_order = create_base_order(&order)?;

        match new_max.cmp(&min_amount) {
            Ordering::Equal => {
                let (order, event) = order_for_equal(ctx, new_max, &mut new_order, my_keys).await?;
                return Ok((Some(order), Some(event)));
            }
            Ordering::Greater => {
                let (order, event) =
                    order_for_greater(ctx, new_max, &mut new_order, my_keys).await?;
                return Ok((Some(order), Some(event)));
            }
            Ordering::Less => {
                return Ok((None, None));
            }
        }
    }

    Ok((None, None))
}

fn create_base_order(order: &Order) -> Result<Order, MostroError> {
    let mut new_order = order.clone();
    new_order.id = uuid::Uuid::new_v4();
    new_order.status = Status::Pending.to_string();
    new_order.amount = 0;
    new_order.hash = None;
    new_order.preimage = None;
    new_order.buyer_invoice = None;
    new_order.taken_at = 0;
    new_order.invoice_held_at = 0;
    new_order.range_parent_id = Some(order.id);

    match new_order.get_order_kind().map_err(MostroInternalErr)? {
        mostro_core::order::Kind::Sell => {
            new_order.buyer_pubkey = None;
            new_order.master_buyer_pubkey = None;
            new_order.trade_index_buyer = None;
        }
        mostro_core::order::Kind::Buy => {
            new_order.seller_pubkey = None;
            new_order.master_seller_pubkey = None;
            new_order.trade_index_seller = None;
        }
    }

    Ok(new_order)
}

async fn create_order_event(
    ctx: &AppContext,
    new_order: &mut Order,
    my_keys: &Keys,
) -> Result<Event, MostroError> {
    let pool = ctx.pool();

    // Extract user for rating tag
    let identity_pubkey = match new_order.is_sell_order() {
        Ok(_) => new_order
            .get_master_seller_pubkey()
            .map_err(MostroInternalErr)?,
        Err(_) => new_order
            .get_master_buyer_pubkey()
            .map_err(MostroInternalErr)?,
    };

    // If user has sent the order with his identity key means that he wants to be rate so we can just
    // check if we have identity key in db - if present we have to send reputation tags otherwise no.
    let mostro_pubkey = my_keys.public_key().to_hex();
    let tags = match crate::db::is_user_present(pool, identity_pubkey.to_string()).await {
        Ok(user) => order_to_tags(
            new_order,
            Some((user.total_rating, user.total_reviews, user.created_at)),
            Some(&mostro_pubkey),
        )?,
        Err(_) => order_to_tags(new_order, Some((0.0, 0, 0)), Some(&mostro_pubkey))?,
    };

    // Prepare new child order event for sending (kind 38383 for orders)
    let event = if let Some(tags) = tags {
        new_order_event(my_keys, "", new_order.id.to_string(), tags)
            .map_err(|e| MostroInternalErr(ServiceError::NostrError(e.to_string())))?
    } else {
        return Err(MostroInternalErr(ServiceError::UnexpectedError(
            "Error creating order event".to_string(),
        )));
    };

    new_order.event_id = event.id.to_string();
    Ok(event)
}

async fn order_for_equal(
    ctx: &AppContext,
    new_max: i64,
    new_order: &mut Order,
    my_keys: &Keys,
) -> Result<(Order, Event), MostroError> {
    new_order.fiat_amount = new_max;
    new_order.max_amount = None;
    new_order.min_amount = None;
    let event = create_order_event(ctx, new_order, my_keys).await?;

    Ok((new_order.clone(), event))
}

async fn order_for_greater(
    ctx: &AppContext,
    new_max: i64,
    new_order: &mut Order,
    my_keys: &Keys,
) -> Result<(Order, Event), MostroError> {
    new_order.max_amount = Some(new_max);
    new_order.fiat_amount = 0;
    let event = create_order_event(ctx, new_order, my_keys).await?;

    Ok((new_order.clone(), event))
}