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
pub mod add_invoice;
pub mod get_dm;
pub mod list_orders;
pub mod new_order;
pub mod rate_user;
pub mod send_msg;
pub mod take_buy;
pub mod take_dispute;
pub mod take_sell;

use crate::cli::add_invoice::execute_add_invoice;
use crate::cli::get_dm::execute_get_dm;
use crate::cli::list_orders::execute_list_orders;
use crate::cli::new_order::execute_new_order;
use crate::cli::rate_user::execute_rate_user;
use crate::cli::send_msg::execute_send_msg;
use crate::cli::take_buy::execute_take_buy;
use crate::cli::take_dispute::execute_take_dispute;
use crate::cli::take_sell::execute_take_sell;
use crate::util;

use anyhow::Result;
use clap::{Parser, Subcommand};
use nostr_sdk::prelude::FromBech32;
use nostr_sdk::secp256k1::XOnlyPublicKey;
use std::env::{set_var, var};
use uuid::Uuid;

#[derive(Parser)]
#[command(
    name = "mostro-cli",
    about = "A simple CLI to use Mostro P2P",
    author,
    help_template = "\
{before-help}{name} 🧌

{about-with-newline}
{author-with-newline}
{usage-heading} {usage}

{all-args}{after-help}
",
    version
)]
#[command(propagate_version = true)]
#[command(arg_required_else_help(true))]
pub struct Cli {
    #[command(subcommand)]
    pub command: Option<Commands>,
    #[arg(short, long)]
    pub verbose: bool,
}

#[derive(Subcommand, Clone)]
#[clap(rename_all = "lower")]
pub enum Commands {
    /// Requests open orders from Mostro pubkey
    ListOrders {
        /// Status of the order
        #[arg(short, long)]
        status: Option<String>,
        /// Currency selected
        #[arg(short, long)]
        currency: Option<String>,
        /// Choose an order kind
        #[arg(short, long)]
        kind: Option<String>,
    },
    /// Create a new buy/sell order on Mostro
    Neworder {
        /// Choose an order kind
        #[arg(short, long)]
        kind: String,
        /// Sats amount - leave empty for market price
        #[arg(short, long)]
        #[clap(default_value_t = 0)]
        amount: i64,
        /// Currency selected
        #[arg(short = 'c', long)]
        fiat_code: String,
        /// Fiat amount
        #[arg(short, long)]
        #[clap(value_parser=check_fiat_range)]
        fiat_amount: i64,
        /// Payment method
        #[arg(short = 'm', long)]
        payment_method: String,
        /// Premium on price
        #[arg(short, long)]
        #[clap(default_value_t = 0)]
        premium: i64,
        /// Invoice string
        #[arg(short, long)]
        invoice: Option<String>,
    },
    /// Take a sell order from a Mostro pubkey
    TakeSell {
        /// Order id
        #[arg(short, long)]
        order_id: Uuid,
        /// Invoice string
        #[arg(short, long)]
        invoice: Option<String>,
    },
    /// Take a buy order from a Mostro pubkey
    TakeBuy {
        /// Order id
        #[arg(short, long)]
        order_id: Uuid,
    },
    /// Take a buy order from a Mostro pubkey
    AddInvoice {
        /// Order id
        #[arg(short, long)]
        order_id: Uuid,
        /// Invoice string
        #[arg(short, long)]
        invoice: String,
    },
    /// Get the list of Mostro direct messages since the last hour, used to check order state
    GetDm {
        /// Since time of the messages in minutes
        #[arg(short, long)]
        #[clap(default_value_t = 30)]
        since: i64,
    },
    /// Send fiat sent message to confirm payment to other user
    FiatSent {
        /// Order id
        #[arg(short, long)]
        order_id: Uuid,
    },
    /// Settle the hold invoice and pay to buyer.
    Release {
        /// Order id
        #[arg(short, long)]
        order_id: Uuid,
    },
    /// Cancel a pending order
    Cancel {
        /// Order id
        #[arg(short, long)]
        order_id: Uuid,
    },
    /// Rate counterpart after a successful trade
    Rate {
        /// Order id
        #[arg(short, long)]
        order_id: Uuid,
        /// Rating from 1 to 5
        #[arg(short, long)]
        rating: u8,
    },
    /// Start a dispute
    Dispute {
        /// Order id
        #[arg(short, long)]
        order_id: Uuid,
    },
    /// Cancel an order (only admin)
    AdmCancel {
        /// Order id
        #[arg(short, long)]
        order_id: Uuid,
    },
    /// Settle a seller's hold invoice (only admin)
    AdmSettle {
        /// Order id
        #[arg(short, long)]
        order_id: Uuid,
    },
    /// Add a new dispute's solver (only admin)
    AdmAddSolver {
        /// npubkey
        #[arg(short, long)]
        npubkey: String,
    },
    /// Admin or solver take a Pending dispute (only admin)
    AdmTakeDispute {
        /// Dispute id
        #[arg(short, long)]
        dispute_id: Uuid,
    },
}

/// Check range simple version for just a single value
pub fn check_fiat_range(s: &str) -> Result<i64, String> {
    match s.parse::<i64>() {
        Ok(val) => Ok(val),
        Err(_e) => Err(String::from("Error on parsing sats value")),
    }
}

pub async fn run() -> Result<()> {
    let cli = Cli::parse();

    // Init logger
    if cli.verbose {
        set_var("RUST_LOG", "info");
    }
    // Mostro pubkey
    let pubkey = var("MOSTRO_PUBKEY").expect("$MOSTRO_PUBKEY env var needs to be set");
    let mostro_key = XOnlyPublicKey::from_bech32(pubkey)?;

    // My key
    let my_key = util::get_keys()?;

    // Call function to connect to relays
    let client = util::connect_nostr().await?;

    if let Some(cmd) = cli.command {
        match &cmd {
            Commands::ListOrders {
                status,
                currency,
                kind,
            } => execute_list_orders(kind, currency, status, mostro_key, &client).await?,
            Commands::TakeSell { order_id, invoice } => {
                execute_take_sell(order_id, invoice, &my_key, mostro_key, &client).await?
            }
            Commands::TakeBuy { order_id } => {
                execute_take_buy(order_id, &my_key, mostro_key, &client).await?
            }
            Commands::AddInvoice { order_id, invoice } => {
                execute_add_invoice(order_id, invoice, &my_key, mostro_key, &client).await?
            }
            Commands::GetDm { since } => {
                execute_get_dm(since, &my_key, mostro_key, &client).await?
            }
            Commands::FiatSent { order_id }
            | Commands::Release { order_id }
            | Commands::Dispute { order_id }
            | Commands::AdmCancel { order_id }
            | Commands::AdmSettle { order_id }
            | Commands::Cancel { order_id } => {
                execute_send_msg(
                    cmd.clone(),
                    Some(*order_id),
                    &my_key,
                    mostro_key,
                    &client,
                    None,
                )
                .await?
            }
            Commands::AdmAddSolver { npubkey } => {
                execute_send_msg(
                    cmd.clone(),
                    None,
                    &my_key,
                    mostro_key,
                    &client,
                    Some(npubkey),
                )
                .await?
            }
            Commands::AdmAddSolver { npubkey } => {
                execute_send_msg(
                    cmd.clone(),
                    None,
                    &my_key,
                    mostro_key,
                    &client,
                    Some(npubkey),
                )
                .await?
            }
            Commands::Neworder {
                kind,
                fiat_code,
                amount,
                fiat_amount,
                payment_method,
                premium,
                invoice,
            } => {
                execute_new_order(
                    kind,
                    fiat_code,
                    fiat_amount,
                    amount,
                    payment_method,
                    premium,
                    invoice,
                    &my_key,
                    mostro_key,
                    &client,
                )
                .await?
            }
            Commands::Rate { order_id, rating } => {
                execute_rate_user(order_id, rating, &my_key, mostro_key, &client).await?;
            }
            Commands::AdmTakeDispute { dispute_id } => {
                execute_take_dispute(dispute_id, &my_key, mostro_key, &client).await?
            }
        };
    }

    println!("Bye Bye!");

    Ok(())
}