-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathnew_order.rs
More file actions
168 lines (154 loc) · 4.99 KB
/
new_order.rs
File metadata and controls
168 lines (154 loc) · 4.99 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
use crate::cli::Context;
use crate::parser::dms::print_commands_results;
use crate::parser::orders::print_order_preview;
use crate::parser::parse_dm_events;
use crate::util::{send_dm, uppercase_first, wait_for_dm};
use anyhow::Result;
use mostro_core::prelude::*;
use std::collections::HashMap;
use std::io::{stdin, stdout, BufRead, Write};
use std::process;
use std::str::FromStr;
use uuid::Uuid;
pub type FiatNames = HashMap<String, String>;
#[allow(clippy::too_many_arguments)]
pub async fn execute_new_order(
kind: &str,
fiat_code: &str,
fiat_amount: &(i64, Option<i64>),
amount: &i64,
payment_method: &str,
premium: &i64,
invoice: &Option<String>,
ctx: &Context,
expiration_days: &i64,
) -> Result<()> {
// Uppercase currency
let fiat_code = fiat_code.to_uppercase();
// Check if fiat currency selected is available on Yadio and eventually force user to set amount
// this is in the case of crypto <--> crypto offer for example
if *amount == 0 {
// Get Fiat list
let api_req_string = "https://api.yadio.io/currencies".to_string();
let fiat_list_check = reqwest::get(api_req_string)
.await?
.json::<FiatNames>()
.await?
.contains_key(&fiat_code);
if !fiat_list_check {
println!("{} is not present in the fiat market, please specify an amount with -a flag to fix the rate", fiat_code);
process::exit(0);
}
}
let kind = uppercase_first(kind);
// New check against strings
let kind_checked = mostro_core::order::Kind::from_str(&kind)
.map_err(|_| anyhow::anyhow!("Invalid order kind"))?;
let expires_at = match *expiration_days {
0 => None,
_ => {
let now = chrono::Utc::now();
let expires_at = now + chrono::Duration::days(*expiration_days);
Some(expires_at.timestamp())
}
};
// Get the type of neworder
// if both tuple field are valid than it's a range order
// otherwise use just fiat amount value as before
let amt = if fiat_amount.1.is_some() {
(0, Some(fiat_amount.0), fiat_amount.1)
} else {
(fiat_amount.0, None, None)
};
let small_order = SmallOrder::new(
None,
Some(kind_checked),
Some(Status::Pending),
*amount,
fiat_code.clone(),
amt.1,
amt.2,
amt.0,
payment_method.to_owned(),
*premium,
None,
None,
invoice.as_ref().to_owned().cloned(),
Some(0),
expires_at,
);
// Create new order for mostro
let order_content = Payload::Order(small_order.clone());
// Print order preview
let ord_preview = print_order_preview(order_content.clone())
.map_err(|e| anyhow::anyhow!("Failed to generate order preview: {}", e))?;
println!("{ord_preview}");
let mut user_input = String::new();
let _input = stdin();
print!("Check your order! Is it correct? (Y/n) > ");
stdout().flush()?;
let mut answer = stdin().lock();
answer.read_line(&mut user_input)?;
match user_input.to_lowercase().as_str().trim_end() {
"y" | "" => {}
"n" => {
println!("Ok you have cancelled the order, create another one please");
process::exit(0);
}
&_ => {
println!("Can't get what you're sayin!");
process::exit(0);
}
};
let request_id = Uuid::new_v4().as_u128() as u64;
// Create NewOrder message
let message = Message::new_order(
None,
Some(request_id),
Some(ctx.trade_index),
Action::NewOrder,
Some(order_content),
);
// Send dm to receiver pubkey
println!(
"SENDING DM with trade index: {} and trade keys: {:?}",
ctx.trade_index,
ctx.trade_keys.public_key().to_hex()
);
// Serialize the message
let message_json = message
.as_json()
.map_err(|_| anyhow::anyhow!("Failed to serialize message"))?;
// Send the DM
send_dm(
&ctx.client,
Some(&ctx.identity_keys),
&ctx.trade_keys,
&ctx.mostro_pubkey,
message_json,
None,
false,
)
.await?;
// Wait for the DM to be sent from mostro
let recv_event = wait_for_dm(ctx, None).await?;
// Parse the incoming DM
let messages = parse_dm_events(recv_event, &ctx.trade_keys, None).await;
if let Some((message, _, _)) = messages.first() {
let message = message.0.get_inner_message_kind();
if message.request_id == Some(request_id) {
print_commands_results(message, None, ctx).await?;
} else {
return Err(anyhow::anyhow!(
"Received response with mismatched request_id. Expected: {}, Got: {:?}",
request_id,
message.request_id
));
}
} else {
return Err(anyhow::anyhow!(
"No valid response received from Mostro after sending new order"
));
}
Ok(())
}