mostro_core/
order.rs

1use crate::prelude::*;
2use nostr_sdk::{PublicKey, Timestamp};
3use secrecy::SecretString;
4use serde::{Deserialize, Serialize};
5#[cfg(feature = "sqlx")]
6use sqlx::FromRow;
7#[cfg(feature = "sqlx")]
8use sqlx_crud::SqlxCrud;
9use std::{fmt::Display, str::FromStr};
10use uuid::Uuid;
11use wasm_bindgen::prelude::*;
12
13/// Orders can be only Buy or Sell
14#[wasm_bindgen]
15#[derive(Debug, Deserialize, Serialize, Clone, Copy, PartialEq, Eq)]
16#[serde(rename_all = "kebab-case")]
17pub enum Kind {
18    Buy,
19    Sell,
20}
21
22impl FromStr for Kind {
23    type Err = ();
24
25    fn from_str(kind: &str) -> std::result::Result<Self, Self::Err> {
26        match kind.to_lowercase().as_str() {
27            "buy" => std::result::Result::Ok(Self::Buy),
28            "sell" => std::result::Result::Ok(Self::Sell),
29            _ => Err(()),
30        }
31    }
32}
33
34impl Display for Kind {
35    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
36        match self {
37            Kind::Sell => write!(f, "sell"),
38            Kind::Buy => write!(f, "buy"),
39        }
40    }
41}
42
43/// Each status that an order can have
44#[wasm_bindgen]
45#[derive(Debug, Deserialize, Serialize, Clone, Copy, PartialEq, Eq)]
46#[serde(rename_all = "kebab-case")]
47pub enum Status {
48    Active,
49    Canceled,
50    CanceledByAdmin,
51    SettledByAdmin,
52    CompletedByAdmin,
53    Dispute,
54    Expired,
55    FiatSent,
56    SettledHoldInvoice,
57    Pending,
58    Success,
59    WaitingBuyerInvoice,
60    WaitingPayment,
61    CooperativelyCanceled,
62    InProgress,
63}
64
65impl Display for Status {
66    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
67        match self {
68            Status::Active => write!(f, "active"),
69            Status::Canceled => write!(f, "canceled"),
70            Status::CanceledByAdmin => write!(f, "canceled-by-admin"),
71            Status::SettledByAdmin => write!(f, "settled-by-admin"),
72            Status::CompletedByAdmin => write!(f, "completed-by-admin"),
73            Status::Dispute => write!(f, "dispute"),
74            Status::Expired => write!(f, "expired"),
75            Status::FiatSent => write!(f, "fiat-sent"),
76            Status::SettledHoldInvoice => write!(f, "settled-hold-invoice"),
77            Status::Pending => write!(f, "pending"),
78            Status::Success => write!(f, "success"),
79            Status::WaitingBuyerInvoice => write!(f, "waiting-buyer-invoice"),
80            Status::WaitingPayment => write!(f, "waiting-payment"),
81            Status::CooperativelyCanceled => write!(f, "cooperatively-canceled"),
82            Status::InProgress => write!(f, "in-progress"),
83        }
84    }
85}
86
87impl FromStr for Status {
88    type Err = ();
89    /// Convert a string to a status
90    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
91        match s.to_lowercase().as_str() {
92            "active" => std::result::Result::Ok(Self::Active),
93            "canceled" => std::result::Result::Ok(Self::Canceled),
94            "canceled-by-admin" => std::result::Result::Ok(Self::CanceledByAdmin),
95            "settled-by-admin" => std::result::Result::Ok(Self::SettledByAdmin),
96            "completed-by-admin" => std::result::Result::Ok(Self::CompletedByAdmin),
97            "dispute" => std::result::Result::Ok(Self::Dispute),
98            "expired" => std::result::Result::Ok(Self::Expired),
99            "fiat-sent" => std::result::Result::Ok(Self::FiatSent),
100            "settled-hold-invoice" => std::result::Result::Ok(Self::SettledHoldInvoice),
101            "pending" => std::result::Result::Ok(Self::Pending),
102            "success" => std::result::Result::Ok(Self::Success),
103            "waiting-buyer-invoice" => std::result::Result::Ok(Self::WaitingBuyerInvoice),
104            "waiting-payment" => std::result::Result::Ok(Self::WaitingPayment),
105            "cooperatively-canceled" => std::result::Result::Ok(Self::CooperativelyCanceled),
106            "in-progress" => std::result::Result::Ok(Self::InProgress),
107            _ => Err(()),
108        }
109    }
110}
111/// Database representation of an order
112#[cfg_attr(feature = "sqlx", derive(FromRow, SqlxCrud), external_id)]
113#[derive(Debug, Default, Deserialize, Serialize, Clone)]
114pub struct Order {
115    pub id: Uuid,
116    pub kind: String,
117    pub event_id: String,
118    pub hash: Option<String>,
119    pub preimage: Option<String>,
120    pub creator_pubkey: String,
121    pub cancel_initiator_pubkey: Option<String>,
122    pub buyer_pubkey: Option<String>,
123    pub master_buyer_pubkey: Option<String>,
124    pub seller_pubkey: Option<String>,
125    pub master_seller_pubkey: Option<String>,
126    pub status: String,
127    pub price_from_api: bool,
128    pub premium: i64,
129    pub payment_method: String,
130    pub amount: i64,
131    pub min_amount: Option<i64>,
132    pub max_amount: Option<i64>,
133    pub buyer_dispute: bool,
134    pub seller_dispute: bool,
135    pub buyer_cooperativecancel: bool,
136    pub seller_cooperativecancel: bool,
137    pub fee: i64,
138    pub routing_fee: i64,
139    pub fiat_code: String,
140    pub fiat_amount: i64,
141    pub buyer_invoice: Option<String>,
142    pub range_parent_id: Option<Uuid>,
143    pub invoice_held_at: i64,
144    pub taken_at: i64,
145    pub created_at: i64,
146    pub buyer_sent_rate: bool,
147    pub seller_sent_rate: bool,
148    pub failed_payment: bool,
149    pub payment_attempts: i64,
150    pub expires_at: i64,
151    pub trade_index_seller: Option<i64>,
152    pub trade_index_buyer: Option<i64>,
153    pub next_trade_pubkey: Option<String>,
154    pub next_trade_index: Option<i64>,
155}
156
157impl From<SmallOrder> for Order {
158    fn from(small_order: SmallOrder) -> Self {
159        Self {
160            id: Uuid::new_v4(),
161            // order will be overwritten with the real one before publishing
162            kind: small_order
163                .kind
164                .map_or_else(|| Kind::Buy.to_string(), |k| k.to_string()),
165            status: small_order
166                .status
167                .map_or_else(|| Status::Active.to_string(), |s| s.to_string()),
168            amount: small_order.amount,
169            fiat_code: small_order.fiat_code,
170            min_amount: small_order.min_amount,
171            max_amount: small_order.max_amount,
172            fiat_amount: small_order.fiat_amount,
173            payment_method: small_order.payment_method,
174            premium: small_order.premium,
175            event_id: String::new(),
176            creator_pubkey: String::new(),
177            price_from_api: false,
178            fee: 0,
179            routing_fee: 0,
180            invoice_held_at: 0,
181            taken_at: 0,
182            created_at: small_order.created_at.unwrap_or(0),
183            expires_at: small_order.expires_at.unwrap_or(0),
184            payment_attempts: 0,
185            ..Default::default()
186        }
187    }
188}
189
190impl Order {
191    /// Convert an order to a small order
192    pub fn as_new_order(&self) -> SmallOrder {
193        SmallOrder::new(
194            Some(self.id),
195            Some(Kind::from_str(&self.kind).unwrap()),
196            Some(Status::from_str(&self.status).unwrap()),
197            self.amount,
198            self.fiat_code.clone(),
199            self.min_amount,
200            self.max_amount,
201            self.fiat_amount,
202            self.payment_method.clone(),
203            self.premium,
204            None,
205            None,
206            self.buyer_invoice.clone(),
207            Some(self.created_at),
208            Some(self.expires_at),
209        )
210    }
211    /// Get the kind of the order
212    pub fn get_order_kind(&self) -> Result<Kind, ServiceError> {
213        if let Ok(kind) = Kind::from_str(&self.kind) {
214            Ok(kind)
215        } else {
216            Err(ServiceError::InvalidOrderKind)
217        }
218    }
219
220    /// Get the status of the order in case
221    pub fn get_order_status(&self) -> Result<Status, ServiceError> {
222        if let Ok(status) = Status::from_str(&self.status) {
223            Ok(status)
224        } else {
225            Err(ServiceError::InvalidOrderStatus)
226        }
227    }
228
229    /// Compare the status of the order
230    pub fn check_status(&self, status: Status) -> Result<(), CantDoReason> {
231        match Status::from_str(&self.status) {
232            Ok(s) => match s == status {
233                true => Ok(()),
234                false => Err(CantDoReason::InvalidOrderStatus),
235            },
236            Err(_) => Err(CantDoReason::InvalidOrderStatus),
237        }
238    }
239
240    /// Check if the order is a buy order
241    pub fn is_buy_order(&self) -> Result<(), CantDoReason> {
242        if self.kind != Kind::Buy.to_string() {
243            return Err(CantDoReason::InvalidOrderKind);
244        }
245        Ok(())
246    }
247    /// Check if the order is a sell order
248    pub fn is_sell_order(&self) -> Result<(), CantDoReason> {
249        if self.kind != Kind::Sell.to_string() {
250            return Err(CantDoReason::InvalidOrderKind);
251        }
252        Ok(())
253    }
254
255    /// Check if the sender is the creator of the order
256    pub fn sent_from_maker(&self, sender: PublicKey) -> Result<(), CantDoReason> {
257        let sender = sender.to_string();
258        if self.creator_pubkey != sender {
259            return Err(CantDoReason::InvalidPubkey);
260        }
261        Ok(())
262    }
263
264    /// Check if the sender is the creator of the order
265    pub fn not_sent_from_maker(&self, sender: PublicKey) -> Result<(), CantDoReason> {
266        let sender = sender.to_string();
267        if self.creator_pubkey == sender {
268            return Err(CantDoReason::InvalidPubkey);
269        }
270        Ok(())
271    }
272
273    /// Get the creator pubkey
274    pub fn get_creator_pubkey(&self) -> Result<PublicKey, ServiceError> {
275        match PublicKey::from_str(self.creator_pubkey.as_ref()) {
276            Ok(pk) => Ok(pk),
277            Err(_) => Err(ServiceError::InvalidPubkey),
278        }
279    }
280
281    /// Get the buyer pubkey
282    pub fn get_buyer_pubkey(&self) -> Result<PublicKey, ServiceError> {
283        if let Some(pk) = self.buyer_pubkey.as_ref() {
284            PublicKey::from_str(pk).map_err(|_| ServiceError::InvalidPubkey)
285        } else {
286            Err(ServiceError::InvalidPubkey)
287        }
288    }
289    /// Get the seller pubkey
290    pub fn get_seller_pubkey(&self) -> Result<PublicKey, ServiceError> {
291        if let Some(pk) = self.seller_pubkey.as_ref() {
292            PublicKey::from_str(pk).map_err(|_| ServiceError::InvalidPubkey)
293        } else {
294            Err(ServiceError::InvalidPubkey)
295        }
296    }
297    /// Get the master buyer pubkey
298    pub fn get_master_buyer_pubkey(
299        &self,
300        password: Option<&SecretString>,
301    ) -> Result<String, ServiceError> {
302        if let Some(pk) = self.master_buyer_pubkey.as_ref() {
303            CryptoUtils::decrypt_data(pk.clone(), password).map_err(|_| ServiceError::InvalidPubkey)
304        } else {
305            Err(ServiceError::InvalidPubkey)
306        }
307    }
308    /// Get the master seller pubkey
309    pub fn get_master_seller_pubkey(
310        &self,
311        password: Option<&SecretString>,
312    ) -> Result<String, ServiceError> {
313        if let Some(pk) = self.master_seller_pubkey.as_ref() {
314            CryptoUtils::decrypt_data(pk.clone(), password).map_err(|_| ServiceError::InvalidPubkey)
315        } else {
316            Err(ServiceError::InvalidPubkey)
317        }
318    }
319
320    /// Check if the order is a range order
321    pub fn is_range_order(&self) -> bool {
322        self.min_amount.is_some() && self.max_amount.is_some()
323    }
324
325    pub fn count_failed_payment(&mut self, retries_number: i64) {
326        if !self.failed_payment {
327            self.failed_payment = true;
328            self.payment_attempts = 1;
329        } else if self.payment_attempts < retries_number {
330            self.payment_attempts += 1;
331        }
332    }
333
334    /// Check if the order has no amount
335    pub fn has_no_amount(&self) -> bool {
336        self.amount == 0
337    }
338
339    /// Set the timestamp to now
340    pub fn set_timestamp_now(&mut self) {
341        self.taken_at = Timestamp::now().as_u64() as i64
342    }
343
344    /// Check if a user is creating a full privacy order so he doesn't to have reputation
345    /// compare master keys with the order keys if they are the same the user is in full privacy mode
346    /// otherwise the user is not in normal mode and has a reputation
347    pub fn is_full_privacy_order(
348        &self,
349        password: Option<&SecretString>,
350    ) -> Result<(Option<String>, Option<String>), ServiceError> {
351        let (mut normal_buyer_idkey, mut normal_seller_idkey) = (None, None);
352
353        // Get master pubkeys to get users data from db
354        let master_buyer_pubkey = self.get_master_buyer_pubkey(password).ok();
355        let master_seller_pubkey = self.get_master_seller_pubkey(password).ok();
356
357        // Check if the buyer is in full privacy mode
358        if self.buyer_pubkey.as_ref() != master_buyer_pubkey.as_ref() {
359            normal_buyer_idkey = master_buyer_pubkey;
360        }
361
362        // Check if the seller is in full privacy mode
363        if self.seller_pubkey.as_ref() != master_seller_pubkey.as_ref() {
364            normal_seller_idkey = master_seller_pubkey;
365        }
366
367        Ok((normal_buyer_idkey, normal_seller_idkey))
368    }
369    /// Setup the dispute status
370    ///
371    /// If the pubkey is the buyer, set the buyer dispute to true
372    /// If the pubkey is the seller, set the seller dispute to true
373    pub fn setup_dispute(&mut self, is_buyer_dispute: bool) -> Result<(), CantDoReason> {
374        // Get the opposite dispute status
375        let is_seller_dispute = !is_buyer_dispute;
376
377        // Update dispute flags based on who initiated
378        let mut update_seller_dispute = false;
379        let mut update_buyer_dispute = false;
380
381        if is_seller_dispute && !self.seller_dispute {
382            update_seller_dispute = true;
383            self.seller_dispute = update_seller_dispute;
384        } else if is_buyer_dispute && !self.buyer_dispute {
385            update_buyer_dispute = true;
386            self.buyer_dispute = update_buyer_dispute;
387        };
388        // Set the status to dispute
389        self.status = Status::Dispute.to_string();
390
391        // Update the database with dispute information
392        // Save the dispute to DB
393        if !update_buyer_dispute && !update_seller_dispute {
394            return Err(CantDoReason::DisputeCreationError);
395        }
396
397        Ok(())
398    }
399}
400
401/// We use this struct to create a new order
402#[derive(Debug, Default, Deserialize, Serialize, Clone)]
403pub struct SmallOrder {
404    #[serde(skip_serializing_if = "Option::is_none")]
405    pub id: Option<Uuid>,
406    pub kind: Option<Kind>,
407    pub status: Option<Status>,
408    pub amount: i64,
409    pub fiat_code: String,
410    pub min_amount: Option<i64>,
411    pub max_amount: Option<i64>,
412    pub fiat_amount: i64,
413    pub payment_method: String,
414    pub premium: i64,
415    #[serde(skip_serializing_if = "Option::is_none")]
416    pub buyer_trade_pubkey: Option<String>,
417    #[serde(skip_serializing_if = "Option::is_none")]
418    pub seller_trade_pubkey: Option<String>,
419    #[serde(skip_serializing_if = "Option::is_none")]
420    pub buyer_invoice: Option<String>,
421    pub created_at: Option<i64>,
422    pub expires_at: Option<i64>,
423}
424
425#[allow(dead_code)]
426impl SmallOrder {
427    #[allow(clippy::too_many_arguments)]
428    pub fn new(
429        id: Option<Uuid>,
430        kind: Option<Kind>,
431        status: Option<Status>,
432        amount: i64,
433        fiat_code: String,
434        min_amount: Option<i64>,
435        max_amount: Option<i64>,
436        fiat_amount: i64,
437        payment_method: String,
438        premium: i64,
439        buyer_trade_pubkey: Option<String>,
440        seller_trade_pubkey: Option<String>,
441        buyer_invoice: Option<String>,
442        created_at: Option<i64>,
443        expires_at: Option<i64>,
444    ) -> Self {
445        Self {
446            id,
447            kind,
448            status,
449            amount,
450            fiat_code,
451            min_amount,
452            max_amount,
453            fiat_amount,
454            payment_method,
455            premium,
456            buyer_trade_pubkey,
457            seller_trade_pubkey,
458            buyer_invoice,
459            created_at,
460            expires_at,
461        }
462    }
463    /// New order from json string
464    pub fn from_json(json: &str) -> Result<Self, ServiceError> {
465        serde_json::from_str(json).map_err(|_| ServiceError::MessageSerializationError)
466    }
467
468    /// Get order as json string
469    pub fn as_json(&self) -> Result<String, ServiceError> {
470        serde_json::to_string(&self).map_err(|_| ServiceError::MessageSerializationError)
471    }
472
473    /// Get the amount of sats or the string "Market price"
474    pub fn sats_amount(&self) -> String {
475        if self.amount == 0 {
476            "Market price".to_string()
477        } else {
478            self.amount.to_string()
479        }
480    }
481    /// Check if the order has a zero amount and a premium or fiat amount
482    pub fn check_zero_amount_with_premium(&self) -> Result<(), CantDoReason> {
483        let premium = (self.premium != 0).then_some(self.premium);
484        let sats_amount = (self.amount != 0).then_some(self.amount);
485
486        if premium.is_some() && sats_amount.is_some() {
487            return Err(CantDoReason::InvalidParameters);
488        }
489        Ok(())
490    }
491    /// Check if the order is a range order and if the amount is zero
492    pub fn check_range_order_limits(&self, amounts: &mut Vec<i64>) -> Result<(), CantDoReason> {
493        // Check if the min and max amount are valid and update the vector
494        if let (Some(min), Some(max)) = (self.min_amount, self.max_amount) {
495            if min < 0 || max < 0 {
496                return Err(CantDoReason::InvalidAmount);
497            }
498            if min >= max {
499                return Err(CantDoReason::InvalidAmount);
500            }
501            if self.amount != 0 {
502                return Err(CantDoReason::InvalidAmount);
503            }
504            amounts.clear();
505            amounts.push(min);
506            amounts.push(max);
507        }
508        Ok(())
509    }
510}
511
512impl From<Order> for SmallOrder {
513    fn from(order: Order) -> Self {
514        let id = Some(order.id);
515        let kind = Kind::from_str(&order.kind).unwrap();
516        let status = Status::from_str(&order.status).unwrap();
517        let amount = order.amount;
518        let fiat_code = order.fiat_code.clone();
519        let min_amount = order.min_amount;
520        let max_amount = order.max_amount;
521        let fiat_amount = order.fiat_amount;
522        let payment_method = order.payment_method.clone();
523        let premium = order.premium;
524        let buyer_trade_pubkey = order.buyer_pubkey.clone();
525        let seller_trade_pubkey = order.seller_pubkey.clone();
526        let buyer_invoice = order.buyer_invoice.clone();
527
528        Self {
529            id,
530            kind: Some(kind),
531            status: Some(status),
532            amount,
533            fiat_code,
534            min_amount,
535            max_amount,
536            fiat_amount,
537            payment_method,
538            premium,
539            buyer_trade_pubkey,
540            seller_trade_pubkey,
541            buyer_invoice,
542            created_at: None,
543            expires_at: None,
544        }
545    }
546}