-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathhelper.rs
More file actions
792 lines (724 loc) · 26.1 KB
/
Copy pathhelper.rs
File metadata and controls
792 lines (724 loc) · 26.1 KB
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
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
// Helper functions for order utilities
use anyhow::Result;
use mostro_core::prelude::*;
use nostr_sdk::prelude::*;
use std::collections::HashMap;
use std::str::FromStr;
use uuid::Uuid;
use crate::ui::state::{OperationResult, OrderChatStaticHeader, OrderSuccess, TakeOrderState};
use crate::util::db_utils::save_order;
use crate::util::dm_utils::FETCH_EVENTS_TIMEOUT;
use crate::util::filters::create_filter;
use crate::util::types::{get_cant_do_description, Event, ListKind};
use crate::util::OrderDmSubscriptionCmd;
use sqlx::SqlitePool;
use tokio::sync::mpsc::UnboundedSender;
/// Parse order from nostr tags
pub fn order_from_tags(tags: Tags) -> Result<SmallOrder> {
let mut order = SmallOrder::default();
for tag in tags {
let t = tag.to_vec(); // Vec<String>
if t.is_empty() {
continue;
}
let key = t[0].as_str();
let values = &t[1..];
let v = values.first().map(|s| s.as_str()).unwrap_or_default();
match key {
"d" => {
order.id = Uuid::parse_str(v).ok();
}
"k" => {
order.kind = mostro_core::order::Kind::from_str(v).ok();
}
"f" => {
order.fiat_code = v.to_string();
}
"s" => {
order.status = Status::from_str(v).ok().or(Some(Status::Pending));
}
"amt" => {
order.amount = v.parse::<i64>().unwrap_or(0);
}
"fa" => {
if v.contains('.') {
continue;
}
if let Some(max_str) = values.get(1) {
order.min_amount = v.parse::<i64>().ok();
order.max_amount = max_str.parse::<i64>().ok();
} else {
order.fiat_amount = v.parse::<i64>().unwrap_or(0);
}
}
"pm" => {
order.payment_method = values.join(",");
}
"premium" => {
order.premium = v.parse::<i64>().unwrap_or(0);
}
_ => {}
}
}
Ok(order)
}
/// Infer `Status` from the message `action` when there is no `SmallOrder` payload
/// (e.g. daemon sends `action: "canceled"` with `payload: null` but `id` on the kind).
pub fn inferred_status_from_trade_action(action: &Action) -> Option<Status> {
match action {
Action::Canceled => Some(Status::Canceled),
Action::CooperativeCancelAccepted => Some(Status::CooperativelyCanceled),
Action::WaitingBuyerInvoice | Action::AddInvoice => Some(Status::WaitingBuyerInvoice),
Action::WaitingSellerToPay | Action::PayInvoice => Some(Status::WaitingPayment),
Action::PayBondInvoice => Some(Status::WaitingTakerBond),
Action::AdminCanceled => Some(Status::CanceledByAdmin),
Action::FiatSentOk => Some(Status::FiatSent),
Action::Release | Action::Released => Some(Status::Success),
_ => None,
}
}
/// Map a Mostro `Action` plus the current `SmallOrder` into a new `Status`,
/// when the transition is clear from protocol semantics.
///
/// For intermediate states where Mostro already sets `order.status` on the
/// `SmallOrder`, callers can simply rely on that value instead of this helper.
pub fn map_action_to_status(action: &Action, order: &SmallOrder) -> Option<Status> {
// If the order already has an explicit status from Mostro, prefer that.
if let Some(status) = order.status {
return Some(status);
}
inferred_status_from_trade_action(action)
}
fn status_phase_rank_for_actor(
status: Status,
kind: Option<mostro_core::order::Kind>,
) -> Option<u8> {
match status {
Status::Pending | Status::WaitingTakerBond | Status::WaitingMakerBond => Some(0),
// Stage ordering follows listing kind progression (same for maker/taker):
// Buy listing: waiting-payment -> waiting-buyer-invoice
// Sell listing: waiting-buyer-invoice -> waiting-payment
Status::WaitingPayment => match kind {
Some(mostro_core::order::Kind::Buy) => Some(1),
Some(mostro_core::order::Kind::Sell) => Some(2),
None => None,
},
Status::WaitingBuyerInvoice | Status::SettledHoldInvoice => match kind {
Some(mostro_core::order::Kind::Buy) => Some(2),
Some(mostro_core::order::Kind::Sell) => Some(1),
None => None,
},
Status::InProgress | Status::Active => Some(3),
Status::FiatSent => Some(4),
Status::Success => Some(5),
_ => None,
}
}
pub(crate) fn is_terminal_trade_status(status: Status) -> bool {
matches!(
status,
Status::Canceled
| Status::CanceledByAdmin
| Status::SettledByAdmin
| Status::CompletedByAdmin
| Status::Expired
| Status::CooperativelyCanceled
| Status::Success
)
}
/// Guard status writes against backward transitions from stale/out-of-order DMs.
///
/// Returns `true` when `candidate` is equal/newer than `current` in the actor-aware phase graph.
/// Terminal states are sticky: once terminal, only the same terminal status is accepted.
pub fn should_apply_status_transition(
current: Option<Status>,
candidate: Status,
kind: Option<mostro_core::order::Kind>,
) -> bool {
let Some(current) = current else {
return true;
};
if current == candidate {
return true;
}
if is_terminal_trade_status(current) {
return false;
}
if is_terminal_trade_status(candidate) {
return true;
}
match (
status_phase_rank_for_actor(current, kind),
status_phase_rank_for_actor(candidate, kind),
) {
(Some(cur), Some(next)) => next >= cur,
// Unknown transition edge: keep existing status (safer than downgrade).
_ => false,
}
}
/// Like [`should_apply_status_transition`], but never treats **equal** status as an advance.
///
/// Use when an **older** Nostr `timestamp` must not replace the Messages row unless the payload
/// status is strictly newer than what the current row already shows.
pub fn should_strictly_advance_status(
current: Option<Status>,
candidate: Status,
kind: Option<mostro_core::order::Kind>,
) -> bool {
if let Some(cur) = current {
if cur == candidate {
return false;
}
}
should_apply_status_transition(current, candidate, kind)
}
/// Validates the range amount input against min/max limits.
pub fn validate_range_amount(take_state: &mut TakeOrderState) {
if take_state.amount_input.is_empty() {
take_state.validation_error = None;
return;
}
let amount = match take_state.amount_input.parse::<f64>() {
Ok(val) if val.is_finite() => val,
Ok(_) => {
take_state.validation_error = Some("Invalid number format".to_string());
return;
}
Err(_) => {
take_state.validation_error = Some("Invalid number format".to_string());
return;
}
};
let min_opt = take_state.order.min_amount.map(|m| m as f64);
let max_opt = take_state.order.max_amount.map(|m| m as f64);
let below_min = min_opt.is_some_and(|min| amount < min);
let above_max = max_opt.is_some_and(|max| amount > max);
if below_min || above_max {
let fiat = &take_state.order.fiat_code;
take_state.validation_error = Some(match (min_opt, max_opt) {
(Some(min), Some(max)) => {
format!("Amount must be between {} and {} {}", min, max, fiat)
}
(Some(min), None) => format!("Amount must be at least {} {}", min, fiat),
(None, Some(max)) => format!("Amount must be at most {} {}", max, fiat),
(None, None) => "Amount is outside allowed range".to_string(),
});
} else {
take_state.validation_error = None;
}
}
/// Parse dispute from nostr tags
pub fn dispute_from_tags(tags: Tags) -> Result<Dispute> {
let mut dispute = Dispute::default();
for tag in tags {
let t = tag.to_vec();
// Check if tag has at least 2 elements
if t.len() < 2 {
continue;
}
let key = t.first().map(|s| s.as_str()).unwrap_or("");
let value = t.get(1).map(|s| s.as_str()).unwrap_or("");
match key {
"d" => {
let id = value
.parse::<Uuid>()
.map_err(|_| anyhow::anyhow!("Invalid dispute id"))?;
dispute.id = id;
}
"s" => {
let status = DisputeStatus::from_str(value)
.map_err(|_| anyhow::anyhow!("Invalid dispute status"))?;
dispute.status = status.to_string();
}
_ => {}
}
}
Ok(dispute)
}
/// Parse disputes from events
///
/// Uses a HashMap keyed by dispute id to keep only the latest dispute per id,
/// mirroring the strategy used in `parse_orders_events` for orders.
pub fn parse_disputes_events(events: Events) -> Vec<Dispute> {
let mut latest_by_id: HashMap<Uuid, Dispute> = HashMap::new();
// Scan events to extract all disputes
for event in events.iter() {
let mut dispute = match dispute_from_tags(event.tags.clone()) {
Ok(d) => d,
Err(e) => {
log::warn!("Failed to parse dispute from tags: {:?}", e);
continue;
}
};
// Get created_at field from Nostr event
dispute.created_at = event.created_at.as_secs() as i64;
latest_by_id
.entry(dispute.id)
.and_modify(|existing| {
if dispute.created_at > existing.created_at {
*existing = dispute.clone();
}
})
.or_insert(dispute);
}
// Collect latest disputes and sort by creation time (newest first)
let mut disputes_list: Vec<Dispute> = latest_by_id.into_values().collect();
disputes_list.sort_by(|a, b| b.created_at.cmp(&a.created_at));
disputes_list
}
/// Latest [`SmallOrder`] per order id from Mostro nostr order events (newest event wins).
///
/// Does not apply currency, status, or kind filters — use [`parse_orders_events`] for that.
pub fn aggregate_latest_orders_by_id(events: &Events) -> HashMap<Uuid, SmallOrder> {
let mut latest_by_id: HashMap<Uuid, SmallOrder> = HashMap::new();
for event in events.iter() {
let mut order = match order_from_tags(event.tags.clone()) {
Ok(o) => o,
Err(e) => {
log::error!("{e:?}");
continue;
}
};
let order_id = match order.id {
Some(id) => id,
None => {
log::info!("Order ID is none");
continue;
}
};
if order.kind.is_none() {
log::info!("Order kind is none");
continue;
}
order.created_at = Some(event.created_at.as_secs() as i64);
latest_by_id
.entry(order_id)
.and_modify(|existing| {
let new_ts = order.created_at.unwrap_or(0);
let old_ts = existing.created_at.unwrap_or(0);
if new_ts > old_ts {
*existing = order.clone();
}
})
.or_insert(order);
}
latest_by_id
}
/// Parse orders from events
pub fn parse_orders_events(
events: Events,
currencies: Option<Vec<String>>,
status: Option<Status>,
kind: Option<mostro_core::order::Kind>,
) -> Vec<SmallOrder> {
let latest_by_id = aggregate_latest_orders_by_id(&events);
let mut requested: Vec<SmallOrder> = latest_by_id
.into_values()
.filter(|o| status.map(|s| o.status == Some(s)).unwrap_or(true))
.filter(|o| {
// If currencies filter is provided and not empty, filter by any currency in the list
// If currencies is None or empty, show all orders (no filter)
currencies
.as_ref()
.map(|currencies| currencies.is_empty() || currencies.contains(&o.fiat_code))
.unwrap_or(true)
})
.filter(|o| {
kind.as_ref()
.map(|k| o.kind.as_ref() == Some(k))
.unwrap_or(true)
})
.collect();
requested.sort_by(|a, b| b.created_at.cmp(&a.created_at));
requested
}
/// Fetch raw Mostro order-kind events from relays (same filter as [`fetch_events_list`] for orders).
///
/// Relay queries are capped (see [`crate::util::filters::MOSTRO_LIST_FETCH_EVENT_LIMIT`]); very old
/// order updates may not be included in the snapshot.
pub async fn fetch_mostro_order_events(
client: &Client,
mostro_pubkey: PublicKey,
) -> Result<Events> {
let filters = create_filter(ListKind::Orders, mostro_pubkey, None)?;
Ok(client.fetch_events(filters, FETCH_EVENTS_TIMEOUT).await?)
}
/// Pending listings for the public order book from an aggregated relay snapshot.
///
/// Applies the same currency rules as [`parse_orders_events`] when `status` is pending-only:
/// empty `currencies` list means no filter; `None` means no filter.
pub fn pending_orders_for_book(
latest: &HashMap<Uuid, SmallOrder>,
currencies: Option<Vec<String>>,
) -> Vec<SmallOrder> {
let mut requested: Vec<SmallOrder> = latest
.values()
.filter(|o| {
o.status == Some(Status::Pending)
&& currencies
.as_ref()
.map(|currencies| currencies.is_empty() || currencies.contains(&o.fiat_code))
.unwrap_or(true)
})
.cloned()
.collect();
requested.sort_by(|a, b| b.created_at.cmp(&a.created_at));
requested
}
/// Fetch events list using the same logic as mostro-cli (adapted for mostrix)
pub async fn fetch_events_list(
list_kind: ListKind,
status: Option<Status>,
currencies: Option<Vec<String>>,
kind: Option<mostro_core::order::Kind>,
client: &Client,
mostro_pubkey: PublicKey,
_since: Option<&i64>,
) -> Result<Vec<Event>> {
match list_kind {
ListKind::Orders => {
let fetched_events = fetch_mostro_order_events(client, mostro_pubkey).await?;
let orders = parse_orders_events(fetched_events, currencies, status, kind);
Ok(orders.into_iter().map(Event::SmallOrder).collect())
}
ListKind::Disputes => {
let filters = create_filter(list_kind, mostro_pubkey, None)?;
let fetched_events = client.fetch_events(filters, FETCH_EVENTS_TIMEOUT).await?;
let disputes = parse_disputes_events(fetched_events);
Ok(disputes.into_iter().map(Event::Dispute).collect())
}
_ => Err(anyhow::anyhow!("Unsupported ListKind for mostrix")),
}
}
/// Fetch orders from the Mostro network
/// Returns a vector of SmallOrder items filtered by the specified status and currencies
pub async fn get_orders(
client: &Client,
mostro_pubkey: PublicKey,
status: Option<Status>,
currencies: Option<Vec<String>>,
) -> Result<Vec<SmallOrder>> {
let fetched_events = fetch_mostro_order_events(client, mostro_pubkey).await?;
Ok(parse_orders_events(
fetched_events,
currencies,
status,
None,
))
}
/// Fetch disputes from the Mostro network
/// Returns a vector of Dispute items
pub async fn get_disputes(client: &Client, mostro_pubkey: PublicKey) -> Result<Vec<Dispute>> {
let fetched_events = fetch_events_list(
ListKind::Disputes,
None,
None,
None,
client,
mostro_pubkey,
None,
)
.await?;
let disputes: Vec<Dispute> = fetched_events
.into_iter()
.filter_map(|event| {
if let Event::Dispute(dispute) = event {
Some(dispute)
} else {
None
}
})
.collect();
Ok(disputes)
}
/// Fetch the latest [`SmallOrder`] for one order id from relays (author + custom order kind + `d` tag).
///
/// Uses `limit(10)` and picks the event with the greatest [`Event::created_at`] so relays that return
/// multiple revisions for the same identifier still resolve to the newest snapshot.
pub async fn fetch_small_order_by_id_from_relay(
client: &Client,
mostro_pubkey: PublicKey,
order_id: Uuid,
) -> Result<Option<SmallOrder>> {
let filter = Filter::new()
.author(mostro_pubkey)
.kind(nostr_sdk::Kind::Custom(NOSTR_ORDER_EVENT_KIND))
.identifier(order_id.to_string())
.limit(10);
let events = client
.fetch_events(filter, FETCH_EVENTS_TIMEOUT)
.await
.map_err(|e| anyhow::anyhow!("Failed to fetch order from relay by id: {}", e))?;
let Some(best) = events.iter().max_by_key(|e| e.created_at) else {
return Ok(None);
};
Ok(Some(order_from_tags(best.tags.clone())?))
}
/// Fetch a single order's fiat code from the relay by order id (identifier "d" tag).
/// Used when the order is not in the local DB (e.g. admin taking a dispute for an order they did not create).
pub async fn fetch_order_fiat_from_relay(
client: &Client,
mostro_pubkey: PublicKey,
order_id: Uuid,
) -> Result<Option<String>> {
let order = fetch_small_order_by_id_from_relay(client, mostro_pubkey, order_id).await?;
Ok(order.and_then(|o| {
let fiat = o.fiat_code;
if fiat.is_empty() {
None
} else {
Some(fiat)
}
}))
}
/// Build My Trades static header for one trade (maker or taker).
pub(super) fn build_order_chat_static_header(
order: &SmallOrder,
trade_index: i64,
trade_keys: &Keys,
is_mine: bool,
) -> Option<OrderChatStaticHeader> {
let order_id = order.id?;
Some(OrderChatStaticHeader {
order_id,
kind: order.kind,
created_at: order.created_at,
trade_index,
initiator_trade_pubkey: trade_keys.public_key().to_string(),
is_mine,
})
}
/// Persist order + track subscription, then build `PaymentRequestRequired` for invoice popups.
#[allow(clippy::too_many_arguments)]
pub(super) async fn payment_request_operation_result(
inner_action: Action,
opt_order: Option<SmallOrder>,
invoice_string: String,
opt_amount: Option<i64>,
fallback_order_id: Option<Uuid>,
request_id: u64,
next_idx: i64,
pool: &SqlitePool,
trade_keys: &Keys,
is_mine: bool,
dm_subscription_tx: Option<&UnboundedSender<OrderDmSubscriptionCmd>>,
log_prefix: &str,
) -> Result<OperationResult> {
let popup_action = match inner_action {
Action::PayBondInvoice => Action::PayBondInvoice,
_ => Action::PayInvoice,
};
let mut order_to_save =
opt_order.ok_or_else(|| anyhow::anyhow!("Order details are missing from payload"))?;
if order_to_save.id.is_none() {
if let Some(fallback) = fallback_order_id {
log::warn!(
"[{log_prefix}] Mostro PaymentRequest payload order missing id; falling back to order_id={fallback}"
);
order_to_save.id = Some(fallback);
} else {
return Err(anyhow::anyhow!(
"Order details are missing id in PaymentRequest payload"
));
}
}
let effective_order_id = order_to_save
.id
.or(fallback_order_id)
.ok_or_else(|| anyhow::anyhow!("Order id missing after PaymentRequest normalization"))?;
log::info!(
"[{log_prefix}] Action::{popup_action:?} response mapped to effective_order_id={effective_order_id}, trade_index={next_idx}"
);
if let Err(e) = save_order(
order_to_save.clone(),
trade_keys,
request_id,
next_idx,
pool,
is_mine,
)
.await
{
log::error!("Failed to save order to database: {e}");
}
if let Some(tx) = dm_subscription_tx {
log::info!(
"[{log_prefix}] Sending DM subscription command for order_id={effective_order_id}, trade_index={next_idx}"
);
let _ = tx.send(OrderDmSubscriptionCmd::TrackOrder {
order_id: effective_order_id,
trade_index: next_idx,
});
}
log::info!("Received {popup_action:?} for order {effective_order_id} with invoice");
let static_header =
build_order_chat_static_header(&order_to_save, next_idx, trade_keys, is_mine).ok_or_else(
|| {
anyhow::anyhow!(
"failed to build static header for order id {:?}",
order_to_save.id
)
},
)?;
let sat_amount = opt_amount.or(Some(order_to_save.amount));
Ok(OperationResult::PaymentRequestRequired {
order: order_to_save,
invoice: invoice_string,
sat_amount,
trade_index: next_idx,
static_header,
action: popup_action,
})
}
/// Helper function to create OperationResult::Success from an order
pub(super) fn create_order_result_success(
order: &SmallOrder,
trade_index: i64,
trade_keys: &Keys,
is_mine: bool,
) -> OperationResult {
OperationResult::Success(OrderSuccess {
order_id: order.id,
kind: order.kind,
amount: order.amount,
fiat_code: order.fiat_code.clone(),
fiat_amount: order.fiat_amount,
min_amount: order.min_amount,
max_amount: order.max_amount,
payment_method: order.payment_method.clone(),
premium: order.premium,
status: order.status,
trade_index: Some(trade_index),
static_header: build_order_chat_static_header(order, trade_index, trade_keys, is_mine),
})
}
/// Helper function to handle Mostro response and check for errors
pub(super) fn handle_mostro_response(
response_message: &Message,
expected_request_id: u64,
) -> Result<&mostro_core::message::MessageKind> {
let inner_message = response_message.get_inner_message_kind();
// Check for CantDo payload first (error response)
if let Some(Payload::CantDo(reason)) = &inner_message.payload {
let error_msg = match reason {
Some(r) => get_cant_do_description(r),
None => "Unknown error - Mostro couldn't process your request".to_string(),
};
log::error!("Received CantDo error: {}", error_msg);
return Err(anyhow::anyhow!(error_msg));
}
// Validate request_id if present
if let Some(id) = inner_message.request_id {
if id != expected_request_id {
log::warn!(
"Received response with mismatched request_id. Expected: {}, Got: {}",
expected_request_id,
id
);
return Err(anyhow::anyhow!("Mismatched request_id"));
}
} else if inner_message.action != Action::RateReceived
&& inner_message.action != Action::NewOrder
&& inner_message.action != Action::AddInvoice
&& inner_message.action != Action::AddBondInvoice
&& inner_message.action != Action::PayInvoice
&& inner_message.action != Action::PayBondInvoice
{
log::warn!(
"Received response with null request_id. Expected: {}",
expected_request_id
);
return Err(anyhow::anyhow!("Response with null request_id"));
}
Ok(inner_message)
}
#[cfg(test)]
mod tests {
use super::{
is_terminal_trade_status, should_apply_status_transition, should_strictly_advance_status,
};
use crate::models::TERMINAL_ORDER_HISTORY_STATUSES;
use mostro_core::prelude::Status;
use std::str::FromStr;
#[test]
fn terminal_order_history_statuses_match_is_terminal_trade_status() {
let terminal_variants = [
Status::Success,
Status::Canceled,
Status::CanceledByAdmin,
Status::SettledByAdmin,
Status::CompletedByAdmin,
Status::Expired,
Status::CooperativelyCanceled,
];
for s in terminal_variants {
assert!(
is_terminal_trade_status(s),
"test variant list must stay aligned with is_terminal_trade_status"
);
let display = s.to_string();
assert!(
TERMINAL_ORDER_HISTORY_STATUSES.contains(&display.as_str()),
"Status::to_string() for {s:?} must appear in TERMINAL_ORDER_HISTORY_STATUSES for targeted reconcile SQL"
);
}
for &kebab in TERMINAL_ORDER_HISTORY_STATUSES {
let parsed =
Status::from_str(kebab).expect("TERMINAL_ORDER_HISTORY_STATUSES must parse");
assert!(
is_terminal_trade_status(parsed),
"{kebab} in TERMINAL_ORDER_HISTORY_STATUSES must be terminal for relay reconcile"
);
}
}
#[test]
fn buy_maker_blocks_waiting_payment_downgrade() {
let allow = should_apply_status_transition(
Some(Status::WaitingBuyerInvoice),
Status::WaitingPayment,
Some(mostro_core::order::Kind::Buy),
);
assert!(!allow);
}
#[test]
fn sell_maker_allows_waiting_buyer_invoice_to_waiting_payment() {
let allow = should_apply_status_transition(
Some(Status::WaitingBuyerInvoice),
Status::WaitingPayment,
Some(mostro_core::order::Kind::Sell),
);
assert!(allow);
}
#[test]
fn terminal_status_is_sticky() {
let allow = should_apply_status_transition(
Some(Status::CooperativelyCanceled),
Status::WaitingPayment,
Some(mostro_core::order::Kind::Buy),
);
assert!(!allow);
}
#[test]
fn waiting_taker_bond_can_revert_to_pending() {
let kind = Some(mostro_core::order::Kind::Buy);
assert!(should_apply_status_transition(
Some(Status::WaitingTakerBond),
Status::Pending,
kind,
));
}
#[test]
fn apply_allows_equal_status_but_strict_does_not() {
let kind = Some(mostro_core::order::Kind::Buy);
assert!(should_apply_status_transition(
Some(Status::WaitingPayment),
Status::WaitingPayment,
kind,
));
assert!(!should_strictly_advance_status(
Some(Status::WaitingPayment),
Status::WaitingPayment,
kind,
));
}
}