-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathdms.rs
More file actions
943 lines (893 loc) Β· 37.4 KB
/
dms.rs
File metadata and controls
943 lines (893 loc) Β· 37.4 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
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
use std::collections::HashSet;
use anyhow::Result;
use base64::engine::general_purpose;
use base64::Engine;
use chrono::DateTime;
use comfy_table::presets::UTF8_FULL;
use comfy_table::*;
use mostro_core::prelude::*;
use nip44::v2::{decrypt_to_bytes, ConversationKey};
use nostr_sdk::prelude::*;
use crate::{
cli::Context,
db::{Order, User},
parser::common::{
format_timestamp, print_amount_info, print_fiat_code, print_order_count,
print_payment_method, print_premium, print_required_amount, print_section_header,
print_success_message, print_trade_index,
},
util::save_order,
};
use serde_json;
/// Handle new order creation display
fn handle_new_order_display(order: &mostro_core::order::SmallOrder) {
print_section_header("π New Order Created");
if let Some(order_id) = order.id {
println!("π Order ID: {}", order_id);
}
print_amount_info(order.amount);
print_fiat_code(&order.fiat_code);
println!("π΅ Fiat Amount: {}", order.fiat_amount);
print_premium(order.premium);
print_payment_method(&order.payment_method);
println!(
"π Kind: {:?}",
order
.kind
.as_ref()
.unwrap_or(&mostro_core::order::Kind::Sell)
);
println!(
"π Status: {:?}",
order.status.as_ref().unwrap_or(&Status::Pending)
);
print_success_message("Order saved successfully!");
}
/// Handle add invoice display
fn handle_add_invoice_display(order: &mostro_core::order::SmallOrder) {
print_section_header("β‘ Add Lightning Invoice");
if let Some(order_id) = order.id {
println!("π Order ID: {}", order_id);
}
print_required_amount(order.amount);
println!("π‘ Please add a lightning invoice with the exact amount above");
println!();
}
/// Handle pay invoice display
fn handle_pay_invoice_display(order: &Option<mostro_core::order::SmallOrder>, invoice: &str) {
print_section_header("π³ Payment Invoice Received");
if let Some(order) = order {
if let Some(order_id) = order.id {
println!("π Order ID: {}", order_id);
}
print_amount_info(order.amount);
print_fiat_code(&order.fiat_code);
println!("π΅ Fiat Amount: {}", order.fiat_amount);
}
println!();
println!("β‘ LIGHTNING INVOICE TO PAY:");
println!("βββββββββββββββββββββββββββββββββββββ");
println!("{}", invoice);
println!("βββββββββββββββββββββββββββββββββββββ");
println!("π‘ Pay this invoice to continue the trade");
println!();
}
fn handle_pay_bond_invoice_display(order: &Option<mostro_core::order::SmallOrder>, invoice: &str) {
print_section_header("πͺ Anti-Abuse Bond Invoice");
if let Some(order) = order {
if let Some(order_id) = order.id {
println!("π Order ID: {}", order_id);
}
print_amount_info(order.amount);
print_fiat_code(&order.fiat_code);
println!("π΅ Fiat Amount: {}", order.fiat_amount);
}
println!();
println!("β‘ LIGHTNING BOND INVOICE TO PAY:");
println!("βββββββββββββββββββββββββββββββββββββ");
println!("{}", invoice);
println!("βββββββββββββββββββββββββββββββββββββ");
println!("π‘ Pay this hold invoice to lock your taker bond.");
println!("π‘ The trade hold invoice will arrive next.");
println!();
}
/// Format payload details for DM table display
fn format_payload_details(payload: &Payload, action: &Action) -> String {
match payload {
Payload::TextMessage(t) => format!("βοΈ {}", t),
Payload::PaymentRequest(_, inv, _) => {
// For invoices, show the full invoice without truncation
format!("β‘ Lightning Invoice:\n{}", inv)
}
Payload::Dispute(id, _) => format!("βοΈ Dispute ID: {}", id),
Payload::Order(o) if *action == Action::NewOrder => format!(
"π New Order: {} {} sats ({})",
o.id.as_ref()
.map(|x| x.to_string())
.unwrap_or_else(|| "N/A".to_string()),
o.amount,
o.fiat_code
),
Payload::Order(o) => {
// Pretty format order details
let status_emoji = match o.status.as_ref().unwrap_or(&Status::Pending) {
Status::Pending => "β³",
Status::Active => "β
",
Status::Dispute => "βοΈ",
Status::Canceled => "π«",
Status::CanceledByAdmin => "π«",
Status::CooperativelyCanceled => "π€",
Status::Success => "π",
Status::FiatSent => "πΈ",
Status::WaitingPayment => "β³",
Status::WaitingBuyerInvoice => "β‘",
Status::SettledByAdmin => "β
",
Status::CompletedByAdmin => "π",
Status::Expired => "β°",
Status::SettledHoldInvoice => "π°",
Status::InProgress => "π",
Status::WaitingTakerBond => "πͺ",
};
let kind_emoji = match o.kind.as_ref().unwrap_or(&mostro_core::order::Kind::Sell) {
mostro_core::order::Kind::Buy => "π",
mostro_core::order::Kind::Sell => "π",
};
format!(
"π Order: {} {} sats ({})\n{} Status: {:?}\n{} Kind: {:?}",
o.id.as_ref()
.map(|x| x.to_string())
.unwrap_or_else(|| "N/A".to_string()),
o.amount,
o.fiat_code,
status_emoji,
o.status.as_ref().unwrap_or(&Status::Pending),
kind_emoji,
o.kind.as_ref().unwrap_or(&mostro_core::order::Kind::Sell)
)
}
Payload::Peer(peer) => {
// Pretty format peer information
if let Some(reputation) = &peer.reputation {
let rating_emoji = if reputation.rating >= 4.0 {
"β"
} else if reputation.rating >= 3.0 {
"πΆ"
} else if reputation.rating >= 2.0 {
"πΈ"
} else {
"π»"
};
format!(
"π€ Peer: {}\n{} Rating: {:.1}/5.0\nπ Reviews: {}\nπ
Operating Days: {}",
if peer.pubkey.is_empty() {
"Anonymous"
} else {
&peer.pubkey
},
rating_emoji,
reputation.rating,
reputation.reviews,
reputation.operating_days
)
} else {
format!(
"π€ Peer: {}",
if peer.pubkey.is_empty() {
"Anonymous"
} else {
&peer.pubkey
}
)
}
}
_ => {
// For other payloads, try to pretty-print as JSON
match serde_json::to_string_pretty(payload) {
Ok(json) => format!("π Payload:\n{}", json),
Err(_) => format!("π Payload: {:?}", payload),
}
}
}
}
/// Handle orders list display
fn handle_orders_list_display(orders: &[mostro_core::order::SmallOrder]) {
if orders.is_empty() {
print_section_header("π Orders List");
println!("π No orders found or unauthorized access");
} else {
print_section_header("π Orders List");
print_order_count(orders.len());
println!();
for (i, order) in orders.iter().enumerate() {
println!("π Order {}:", i + 1);
println!("βββββββββββββββββββββββββββββββββββββ");
println!(
"π ID: {}",
order
.id
.as_ref()
.map(|id| id.to_string())
.unwrap_or_else(|| "N/A".to_string())
);
println!(
"π Kind: {:?}",
order
.kind
.as_ref()
.unwrap_or(&mostro_core::order::Kind::Sell)
);
println!(
"π Status: {:?}",
order.status.as_ref().unwrap_or(&Status::Pending)
);
print_amount_info(order.amount);
print_fiat_code(&order.fiat_code);
if let Some(min) = order.min_amount {
if let Some(max) = order.max_amount {
println!("π΅ Fiat Range: {}-{}", min, max);
} else {
println!("π΅ Fiat Amount: {}", order.fiat_amount);
}
} else {
println!("π΅ Fiat Amount: {}", order.fiat_amount);
}
print_payment_method(&order.payment_method);
print_premium(order.premium);
if let Some(created_at) = order.created_at {
if let Some(expires_at) = order.expires_at {
println!("π
Created: {}", format_timestamp(created_at));
println!("β° Expires: {}", format_timestamp(expires_at));
}
}
println!();
}
}
}
/// Display SolverDisputeInfo in a beautiful table format
fn display_solver_dispute_info(dispute_info: &mostro_core::dispute::SolverDisputeInfo) -> String {
let mut table = Table::new();
table
.load_preset(UTF8_FULL)
.set_content_arrangement(ContentArrangement::Dynamic)
.set_width(120)
.set_header(vec![
Cell::new("Field")
.add_attribute(Attribute::Bold)
.set_alignment(CellAlignment::Center),
Cell::new("Value")
.add_attribute(Attribute::Bold)
.set_alignment(CellAlignment::Center),
]);
let mut rows: Vec<Row> = Vec::new();
// Basic dispute information
rows.push(Row::from(vec![
Cell::new("π Order ID:"),
Cell::new(dispute_info.id.to_string()),
]));
rows.push(Row::from(vec![
Cell::new("π Kind"),
Cell::new(dispute_info.kind.clone()),
]));
rows.push(Row::from(vec![
Cell::new("π Status"),
Cell::new(dispute_info.status.clone()),
]));
// Financial information
rows.push(Row::from(vec![
Cell::new("π° Amount"),
Cell::new(format!("{} sats", dispute_info.amount)),
]));
rows.push(Row::from(vec![
Cell::new("π΅ Fiat Amount"),
Cell::new(dispute_info.fiat_amount.to_string()),
]));
rows.push(Row::from(vec![
Cell::new("π Premium"),
Cell::new(format!("{}%", dispute_info.premium)),
]));
rows.push(Row::from(vec![
Cell::new("π³ Payment Method"),
Cell::new(dispute_info.payment_method.clone()),
]));
rows.push(Row::from(vec![
Cell::new("πΈ Fee"),
Cell::new(format!("{} sats", dispute_info.fee)),
]));
rows.push(Row::from(vec![
Cell::new("π£οΈ Routing Fee"),
Cell::new(format!("{} sats", dispute_info.routing_fee)),
]));
// Participant information
rows.push(Row::from(vec![
Cell::new("π€ Initiator"),
Cell::new(dispute_info.initiator_pubkey.clone()),
]));
if let Some(buyer) = &dispute_info.buyer_pubkey {
rows.push(Row::from(vec![
Cell::new("π Buyer"),
Cell::new(buyer.clone()),
]));
}
if let Some(seller) = &dispute_info.seller_pubkey {
rows.push(Row::from(vec![
Cell::new("πͺ Seller"),
Cell::new(seller.clone()),
]));
}
// Privacy settings
rows.push(Row::from(vec![
Cell::new("π Initiator Privacy"),
Cell::new(if dispute_info.initiator_full_privacy {
"Full Privacy"
} else {
"Standard"
}),
]));
rows.push(Row::from(vec![
Cell::new("π Counterpart Privacy"),
Cell::new(if dispute_info.counterpart_full_privacy {
"Full Privacy"
} else {
"Standard"
}),
]));
// Optional fields
if let Some(hash) = &dispute_info.hash {
rows.push(Row::from(vec![
Cell::new("π Hash"),
Cell::new(hash.clone()),
]));
}
if let Some(preimage) = &dispute_info.preimage {
rows.push(Row::from(vec![
Cell::new("π Preimage"),
Cell::new(preimage.clone()),
]));
}
if let Some(buyer_invoice) = &dispute_info.buyer_invoice {
rows.push(Row::from(vec![
Cell::new("β‘ Buyer Invoice"),
Cell::new(buyer_invoice.clone()),
]));
}
// Status information
rows.push(Row::from(vec![
Cell::new("π Previous Status"),
Cell::new(dispute_info.order_previous_status.clone()),
]));
// Timestamps
rows.push(Row::from(vec![
Cell::new("π
Created"),
Cell::new(format_timestamp(dispute_info.created_at)),
]));
rows.push(Row::from(vec![
Cell::new("β° Taken At"),
Cell::new(format_timestamp(dispute_info.taken_at)),
]));
rows.push(Row::from(vec![
Cell::new("β‘ Invoice Held At"),
Cell::new(format_timestamp(dispute_info.invoice_held_at)),
]));
table.add_rows(rows);
table.to_string()
}
/// Execute logic of command answer
pub async fn print_commands_results(message: &MessageKind, ctx: &Context) -> Result<()> {
// Do the logic for the message response
match message.action {
Action::NewOrder => {
if let Some(Payload::Order(order)) = message.payload.as_ref() {
if let Some(req_id) = message.request_id {
if let Err(e) = save_order(
order.clone(),
&ctx.trade_keys,
req_id,
ctx.trade_index,
&ctx.pool,
)
.await
{
return Err(anyhow::anyhow!("Failed to save order: {}", e));
}
handle_new_order_display(order);
Ok(())
} else {
Err(anyhow::anyhow!("No request id found in message"))
}
} else {
Err(anyhow::anyhow!("No order found in message"))
}
}
// this is the case where the buyer adds an invoice to a takesell order
Action::WaitingSellerToPay => {
println!("β³ Waiting for Seller Payment");
println!("βββββββββββββββββββββββββββββββββββββββ");
if let Some(order_id) = &message.id {
println!("π Order ID: {}", order_id);
let mut order = Order::get_by_id(&ctx.pool, &order_id.to_string()).await?;
match order
.set_status(Status::WaitingPayment.to_string())
.save(&ctx.pool)
.await
{
Ok(_) => {
println!("π Status: Waiting for Payment");
println!("π‘ The seller needs to pay the invoice to continue");
println!("β
Order status updated successfully!");
}
Err(e) => println!("β Failed to update order status: {}", e),
}
Ok(())
} else {
Err(anyhow::anyhow!("No order found in message"))
}
}
// this is the case where the buyer adds an invoice to a takesell order
Action::AddInvoice => {
if let Some(Payload::Order(order)) = &message.payload {
handle_add_invoice_display(order);
if let Some(req_id) = message.request_id {
// Save the order
if let Err(e) = save_order(
order.clone(),
&ctx.trade_keys,
req_id,
ctx.trade_index,
&ctx.pool,
)
.await
{
return Err(anyhow::anyhow!("Failed to save order: {}", e));
}
print_success_message("Order saved successfully!");
} else {
return Err(anyhow::anyhow!("No request id found in message"));
}
Ok(())
} else {
Err(anyhow::anyhow!("No order found in message"))
}
}
// this is the case where the buyer pays the invoice coming from a takebuy
Action::PayInvoice => {
if let Some(Payload::PaymentRequest(order, invoice, _)) = &message.payload {
handle_pay_invoice_display(order, invoice);
if let Some(order) = order {
if let Some(req_id) = message.request_id {
let store_order = order.clone();
// Save the order
if let Err(e) = save_order(
store_order,
&ctx.trade_keys,
req_id,
ctx.trade_index,
&ctx.pool,
)
.await
{
println!("β Failed to save order: {}", e);
return Err(anyhow::anyhow!("Failed to save order: {}", e));
}
print_success_message("Order saved successfully!");
} else {
return Err(anyhow::anyhow!("No request id found in message"));
}
} else {
return Err(anyhow::anyhow!("No request id found in message"));
}
}
Ok(())
}
// mostro-core 0.11: anti-abuse bond invoice sent right after a takebuy/takesell.
Action::PayBondInvoice => {
if let Some(Payload::PaymentRequest(order, invoice, _)) = &message.payload {
handle_pay_bond_invoice_display(order, invoice);
if let Some(order) = order {
if let Some(req_id) = message.request_id {
if let Err(e) = save_order(
order.clone(),
&ctx.trade_keys,
req_id,
ctx.trade_index,
&ctx.pool,
)
.await
{
println!("β Failed to save order: {}", e);
return Err(anyhow::anyhow!("Failed to save order: {}", e));
}
print_success_message("Order saved successfully!");
} else {
return Err(anyhow::anyhow!("No request id found in message"));
}
}
}
Ok(())
}
Action::CantDo => {
println!("β Action Cannot Be Completed");
println!("βββββββββββββββββββββββββββββββββββββββ");
match message.payload {
Some(Payload::CantDo(Some(
CantDoReason::OutOfRangeFiatAmount | CantDoReason::OutOfRangeSatsAmount,
))) => {
println!("π° Amount Error");
println!("π‘ The amount is outside the allowed range");
println!("π Please check the order's min/max limits");
Err(anyhow::anyhow!(
"Amount is outside the allowed range. Please check the order's min/max limits."
))
}
Some(Payload::CantDo(Some(CantDoReason::PendingOrderExists))) => {
println!("β³ Pending Order Exists");
println!("π‘ A pending order already exists");
println!("π Please wait for it to be filled or canceled");
Err(anyhow::anyhow!(
"A pending order already exists. Please wait for it to be filled or canceled."
))
}
Some(Payload::CantDo(Some(CantDoReason::InvalidTradeIndex))) => {
println!("π’ Invalid Trade Index");
println!("π‘ The trade index is invalid");
println!("π Please synchronize the trade index with mostro");
Err(anyhow::anyhow!(
"Invalid trade index. Please synchronize the trade index with mostro"
))
}
Some(Payload::CantDo(Some(CantDoReason::InvalidFiatCurrency))) => {
println!("π± Invalid Currency");
println!("π‘ The fiat currency is not supported");
println!("π Please use a valid currency");
Err(anyhow::anyhow!("Invalid currency"))
}
_ => {
println!("β Unknown Error");
println!("π‘ An unknown error occurred");
Err(anyhow::anyhow!("Unknown reason: {:?}", message.payload))
}
}
}
// this is the case where the user cancels the order
Action::Canceled => {
if let Some(order_id) = &message.id {
println!("π« Order Canceled");
println!("βββββββββββββββββββββββββββββββββββββββ");
println!("π Order ID: {}", order_id);
// Acquire database connection
// Verify order exists before deletion
if Order::get_by_id(&ctx.pool, &order_id.to_string())
.await
.is_ok()
{
if let Err(e) = Order::delete_by_id(&ctx.pool, &order_id.to_string()).await {
println!("β Failed to delete order: {}", e);
return Err(anyhow::anyhow!("Failed to delete order: {}", e));
}
// Release database connection
println!("β
Order {} canceled successfully!", order_id);
Ok(())
} else {
println!("β Order not found: {}", order_id);
Err(anyhow::anyhow!("Order not found: {}", order_id))
}
} else {
Err(anyhow::anyhow!("No order id found in message"))
}
}
Action::RateReceived => {
print_section_header("β Rating Received");
println!("π Thank you for your rating!");
println!("π‘ Your feedback helps improve the trading experience");
print_success_message("Rating processed successfully!");
Ok(())
}
Action::FiatSentOk => {
if let Some(order_id) = &message.id {
print_section_header("πΈ Fiat Payment Confirmed");
println!("π Order ID: {}", order_id);
println!("β
Fiat payment confirmation received");
println!("β³ Waiting for sats release from seller");
println!("π‘ The seller will now release your Bitcoin");
Ok(())
} else {
Err(anyhow::anyhow!("No order id found in message"))
}
}
Action::LastTradeIndex => {
if let Some(last_trade_index) = message.trade_index {
print_section_header("π’ Last Trade Index Updated");
print_trade_index(last_trade_index as u64);
match User::get(&ctx.pool).await {
Ok(mut user) => {
user.set_last_trade_index(last_trade_index);
if let Err(e) = user.save(&ctx.pool).await {
println!("β Failed to update user: {}", e);
} else {
print_success_message("Trade index synchronized successfully!");
}
}
Err(_) => {
println!("β οΈ Warning: Last trade index but received unexpected payload structure: {:#?}", message.payload);
}
}
} else {
println!("β οΈ Warning: Last trade index but received unexpected payload structure: {:#?}", message.payload);
}
Ok(())
}
Action::DisputeInitiatedByYou => {
if let Some(Payload::Dispute(dispute_id, _)) = &message.payload {
println!("βοΈ Dispute Initiated");
println!("βββββββββββββββββββββββββββββββββββββββ");
println!("π Dispute ID: {}", dispute_id);
if let Some(order_id) = &message.id {
println!("π Order ID: {}", order_id);
let mut order = Order::get_by_id(&ctx.pool, &order_id.to_string()).await?;
// Update order status to disputed if we have the order
match order
.set_status(Status::Dispute.to_string())
.save(&ctx.pool)
.await
{
Ok(_) => {
println!("π Status: Dispute");
println!("β
Order status updated to Dispute");
}
Err(e) => println!("β Failed to update order status: {}", e),
}
}
println!("π‘ A dispute has been initiated for this order");
println!("β
Dispute created successfully!");
Ok(())
} else {
println!(
"β οΈ Warning: Dispute initiated but received unexpected payload structure"
);
Ok(())
}
}
Action::HoldInvoicePaymentAccepted => {
if let Some(order_id) = &message.id {
println!("π Hold Invoice Payment Accepted");
println!("βββββββββββββββββββββββββββββββββββββββ");
println!("π Order ID: {}", order_id);
println!("β
Hold invoice payment accepted successfully!");
Ok(())
} else {
println!(
"β οΈ Warning: Hold invoice payment accepted but received unexpected payload structure"
);
Ok(())
}
}
Action::HoldInvoicePaymentSettled | Action::Released => {
println!("π Payment Settled & Released");
println!("βββββββββββββββββββββββββββββββββββββββ");
println!("β
Hold invoice payment settled successfully!");
println!("π° Bitcoin has been released to the buyer");
println!("π Trade completed successfully!");
Ok(())
}
Action::Orders => {
if let Some(Payload::Orders(orders)) = &message.payload {
handle_orders_list_display(orders);
} else {
println!(
"β οΈ Warning: Orders list but received unexpected payload structure: {:#?}",
message.payload
);
}
Ok(())
}
Action::AdminTookDispute => {
if let Some(Payload::Dispute(_, Some(dispute_info))) = &message.payload {
println!("π Dispute Successfully Taken!");
println!("βββββββββββββββββββββββββββββββββββββββ");
println!();
// Display the dispute info using our dedicated function
let dispute_table = display_solver_dispute_info(dispute_info);
println!("{dispute_table}");
println!();
println!("β
Dispute taken successfully! You are now the solver for this dispute.");
Ok(())
} else {
// Fallback for debugging - show what we actually received
println!("π Dispute Successfully Taken!");
println!("βββββββββββββββββββββββββββββββββββββββ");
println!();
println!(
"β οΈ Warning: Expected Dispute payload with SolverDisputeInfo but received:"
);
println!("π Payload: {:#?}", message.payload);
println!();
println!("β
Dispute taken successfully! You are now the solver for this dispute.");
Ok(())
}
}
Action::RestoreSession => {
if let Some(Payload::RestoreData(restore_data)) = &message.payload {
println!("π Restore Session Response");
println!("βββββββββββββββββββββββββββββββββββββββ");
println!();
// Process orders
if !restore_data.restore_orders.is_empty() {
println!(
"π Found {} pending order(s):",
restore_data.restore_orders.len()
);
println!("βββββββββββββββββββββββββββββββββββββ");
for (i, order_info) in restore_data.restore_orders.iter().enumerate() {
println!(" {}. Order ID: {}", i + 1, order_info.order_id);
println!(" Trade Index: {}", order_info.trade_index);
println!(" Status: {:?}", order_info.status);
println!();
}
} else {
println!("π No pending orders found.");
println!();
}
// Process disputes
if !restore_data.restore_disputes.is_empty() {
println!(
"βοΈ Found {} active dispute(s):",
restore_data.restore_disputes.len()
);
println!("βββββββββββββββββββββββββββββββββββββ");
for (i, dispute_info) in restore_data.restore_disputes.iter().enumerate() {
println!(" {}. Dispute ID: {}", i + 1, dispute_info.dispute_id);
println!(" Order ID: {}", dispute_info.order_id);
println!(" Trade Index: {}", dispute_info.trade_index);
println!(" Status: {:?}", dispute_info.status);
println!();
}
} else {
println!("βοΈ No active disputes found.");
println!();
}
println!("β
Session restore completed successfully!");
Ok(())
} else {
Err(anyhow::anyhow!("No restore data payload found in message"))
}
}
_ => Err(anyhow::anyhow!("Unknown action: {:?}", message.action)),
}
}
pub async fn parse_dm_events(
events: Events,
pubkey: &Keys,
since: Option<&i64>,
) -> Vec<(Message, u64, PublicKey)> {
let mut id_set = HashSet::<EventId>::new();
let mut direct_messages: Vec<(Message, u64, PublicKey)> = Vec::new();
for dm in events.iter() {
// Skip if already processed
if !id_set.insert(dm.id) {
continue;
}
let (created_at, message, sender) = match dm.kind {
nostr_sdk::Kind::GiftWrap => match unwrap_message(dm, pubkey).await {
Ok(Some(u)) => (u.created_at, u.message, u.sender),
Ok(None) => continue, // outer NIP-44 failed β not addressed to us
Err(e) => {
eprintln!("Warning: could not unwrap gift wrap (event {}): {e}", dm.id);
continue;
}
},
nostr_sdk::Kind::PrivateDirectMessage => {
let ck = if let Ok(ck) = ConversationKey::derive(pubkey.secret_key(), &dm.pubkey) {
ck
} else {
continue;
};
let b64decoded_content =
match general_purpose::STANDARD.decode(dm.content.as_bytes()) {
Ok(b64decoded_content) => b64decoded_content,
Err(_) => {
continue;
}
};
let unencrypted_content = match decrypt_to_bytes(&ck, &b64decoded_content) {
Ok(bytes) => bytes,
Err(_) => {
continue;
}
};
let message_str = match String::from_utf8(unencrypted_content) {
Ok(s) => s,
Err(_) => {
continue;
}
};
let message = match Message::from_json(&message_str) {
Ok(m) => m,
Err(_) => {
continue;
}
};
(dm.created_at, message, dm.pubkey)
}
_ => continue,
};
// check if the message is older than the since time if it is, skip it
if let Some(since_time) = since {
// Calculate since time from now in minutes subtracting the since time
let since_time = chrono::Utc::now()
.checked_sub_signed(chrono::Duration::minutes(*since_time))
.unwrap()
.timestamp() as u64;
if created_at.as_secs() < since_time {
continue;
}
}
direct_messages.push((message, created_at.as_secs(), sender));
}
direct_messages.sort_by(|a, b| a.1.cmp(&b.1));
direct_messages
}
pub async fn print_direct_messages(
dm: &[(Message, u64, PublicKey)],
mostro_pubkey: Option<PublicKey>,
) -> Result<()> {
if dm.is_empty() {
println!();
println!("π No new messages");
println!();
return Ok(());
}
println!();
print_section_header("π¨ Direct Messages");
for (i, (message, created_at, sender_pubkey)) in dm.iter().enumerate() {
let date = match DateTime::from_timestamp(*created_at as i64, 0) {
Some(dt) => dt.format("%Y-%m-%d %H:%M:%S").to_string(),
None => "Invalid timestamp".to_string(),
};
let inner = message.get_inner_message_kind();
let action_str = inner.action.to_string();
// Select an icon for the action/payload
let action_icon = match inner.action {
Action::NewOrder => "π",
Action::AddInvoice | Action::PayInvoice => "β‘",
Action::PayBondInvoice => "πͺ",
Action::FiatSent | Action::FiatSentOk => "πΈ",
Action::Release | Action::Released => "π",
Action::Cancel | Action::Canceled => "π«",
Action::Dispute | Action::DisputeInitiatedByYou => "βοΈ",
Action::RateUser | Action::RateReceived => "β",
Action::Orders => "π",
Action::LastTradeIndex => "π’",
Action::SendDm => "π¬",
_ => "π―",
};
// From label: show π§ Mostro if matches provided pubkey
let from_label = if let Some(pk) = mostro_pubkey {
if *sender_pubkey == pk {
format!("π§ {}", sender_pubkey)
} else {
sender_pubkey.to_string()
}
} else {
sender_pubkey.to_string()
};
// Print message header
println!("π Message {}:", i + 1);
println!("βββββββββββββββββββββββββββββββββββββ");
println!("β° Time: {}", date);
println!("π¨ From: {}", from_label);
println!("π― Action: {} {}", action_icon, action_str);
// Print details with proper formatting
if let Some(payload) = &inner.payload {
let details = format_payload_details(payload, &inner.action);
println!("π Details:");
for line in details.lines() {
println!(" {}", line);
}
} else {
println!("π Details: -");
}
println!();
}
Ok(())
}
#[cfg(test)]
mod tests {}