1use std::{collections::HashSet, marker::PhantomData, str::FromStr, time::SystemTime};
4
5use ahash::AHashSet;
6use eyre::eyre;
7use generics::{ConstructAuthError, UrlError};
8use hmac::{Hmac, KeyInit as _, Mac};
9use jiff::{SignedDuration, Timestamp};
10use secrecy::{ExposeSecret as _, SecretString};
11use serde::{Deserialize, Serialize, de::DeserializeOwned};
12use sha2::Sha256;
13use url::Url;
14use v_exchanges_api_generics::{http::*, ws::*};
15
16use crate::traits::*;
17
18#[derive(Debug, Default)]
20pub enum MexcOption {
21 #[default]
23 Default,
24 Pubkey(String),
26 Secret(SecretString),
28 Testnet(bool),
30 HttpUrl(MexcHttpUrl),
32 HttpAuth(MexcAuth),
34 RecvWindow(std::time::Duration),
36 WsUrl(MexcWsUrl),
38 WsConfig(WsConfig),
40 WsTopics(Vec<String>),
42}
43#[derive(Clone, derive_more::Debug, Default)]
45pub struct MexcOptions {
46 pub pubkey: Option<String>,
48 #[debug("[REDACTED]")]
50 pub secret: Option<SecretString>,
51 pub testnet: bool,
53 pub http_url: MexcHttpUrl,
55 pub http_auth: MexcAuth,
57 pub recv_window: Option<std::time::Duration>,
59 pub ws_url: MexcWsUrl,
61 pub ws_config: WsConfig,
63 pub ws_topics: AHashSet<String>,
65}
66#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
68#[non_exhaustive]
69pub enum MexcHttpUrl {
70 Spot,
71 Futures,
72 #[default]
73 None,
74}
75#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
76pub enum MexcAuth {
77 Sign,
78 Key,
79 #[default]
80 None,
81}
82#[derive(Debug, Deserialize, Serialize)]
83pub struct MexcError {
84 pub code: MexcErrorCode,
85 #[serde(alias = "message")]
86 pub msg: String,
87}
88#[non_exhaustive]
89#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
90#[serde(from = "i32", into = "i32")]
91pub enum MexcErrorCode {
92 Unauthorized(i32),
94 InvalidApiKey(i32),
95 InvalidSignature(i32),
96 ApiKeyExpired(i32),
97 SignatureNotValid(i32),
98
99 TooManyRequests(i32),
101
102 BadSymbol(i32),
104 PermissionDenied(i32),
105
106 Other(i32),
107}
108impl MexcErrorCode {
109 fn as_i32(self) -> i32 {
110 match self {
111 Self::Unauthorized(c)
112 | Self::InvalidApiKey(c)
113 | Self::InvalidSignature(c)
114 | Self::ApiKeyExpired(c)
115 | Self::SignatureNotValid(c)
116 | Self::TooManyRequests(c)
117 | Self::BadSymbol(c)
118 | Self::PermissionDenied(c)
119 | Self::Other(c) => c,
120 }
121 }
122}
123
124pub struct MexcRequestHandler<'a, R: DeserializeOwned> {
126 options: MexcOptions,
127 _phantom: PhantomData<&'a R>,
128}
129#[derive(Debug, derive_new::new)]
131pub struct MexcWsHandler {
132 options: MexcOptions,
133}
134#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
136#[non_exhaustive]
137pub enum MexcWsUrl {
138 Spot,
139 Futures,
140 #[default]
141 None,
142}
143static MAX_RECV_WINDOW: std::time::Duration = std::time::Duration::from_millis(60000); impl EndpointUrl for MexcHttpUrl {
146 fn url_mainnet(&self) -> Url {
147 match self {
148 Self::Spot => Url::parse("https://api.mexc.com").unwrap(),
149 Self::Futures => Url::parse("https://contract.mexc.com").unwrap(),
150 Self::None => Url::parse("").unwrap(),
151 }
152 }
153
154 fn url_testnet(&self) -> Option<Url> {
155 match self {
156 Self::Spot => Some(Url::parse("https://api-testnet.mexc.com").unwrap()),
157 Self::Futures => Some(Url::parse("https://contract-testnet.mexc.com").unwrap()),
158 Self::None => Some(Url::parse("").unwrap()),
159 }
160 }
161}
162
163#[derive(Deserialize)]
165struct MexcEnvelope {
166 success: bool,
167 code: i32,
168 #[serde(default)]
169 message: String,
170}
171
172impl From<MexcError> for ApiError {
173 fn from(e: MexcError) -> Self {
174 use v_exchanges_api_generics::http::AuthError;
175 match e.code {
176 MexcErrorCode::ApiKeyExpired(_) => AuthError::KeyExpired { msg: e.msg }.into(),
177 MexcErrorCode::Unauthorized(_) | MexcErrorCode::InvalidApiKey(_) | MexcErrorCode::InvalidSignature(_) | MexcErrorCode::SignatureNotValid(_) =>
178 AuthError::Unauthorized { msg: e.msg }.into(),
179 _ => ApiError::Other(eyre!("MEXC API error {}: {}", e.code.as_i32(), e.msg)),
180 }
181 }
182}
183
184impl From<i32> for MexcErrorCode {
185 fn from(code: i32) -> Self {
186 match code {
187 602 => Self::Unauthorized(code),
188 10001 => Self::InvalidApiKey(code),
189 140002 => Self::InvalidSignature(code),
190 402 | 700001 => Self::ApiKeyExpired(code),
191 700002 => Self::SignatureNotValid(code),
192 700007 | 700013 => Self::InvalidSignature(code),
193 70011 => Self::PermissionDenied(code),
194 10007 => Self::BadSymbol(code),
195 code => Self::Other(code),
196 }
197 }
198}
199
200impl From<MexcErrorCode> for i32 {
201 fn from(code: MexcErrorCode) -> Self {
202 code.as_i32()
203 }
204}
205
206impl<B, R> RequestHandler<B> for MexcRequestHandler<'_, R>
207where
208 B: Serialize,
209 R: DeserializeOwned,
210{
211 type Successful = R;
212
213 fn base_url(&self, is_test: bool) -> Result<Url, UrlError> {
214 match is_test {
215 true => self.options.http_url.url_testnet().ok_or_else(|| UrlError::MissingTestnet(self.options.http_url.url_mainnet())),
216 false => Ok(self.options.http_url.url_mainnet()),
217 }
218 }
219
220 #[tracing::instrument(skip_all, fields(?builder))]
221 fn build_request(&self, mut builder: RequestBuilder, request_body: &Option<B>, _: u8) -> Result<Request, BuildError> {
222 if let Some(body) = request_body {
223 let encoded = serde_urlencoded::to_string(body)?;
224 builder = builder.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded").body(encoded);
225 }
227
228 if self.options.http_auth != MexcAuth::None {
229 let pubkey = self.options.pubkey.as_deref().ok_or(ConstructAuthError::new_missing_pubkey())?;
230 builder = builder.header("ApiKey", pubkey);
231
232 let time = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap();
233 let timestamp = time.as_millis();
234 builder = builder.header("Request-Time", timestamp.to_string());
235
236 if let Some(recv_window) = self.options.recv_window {
237 builder = builder.header("Recv-Window", (recv_window.as_millis() as u64).to_string());
238 }
239
240 if self.options.http_auth == MexcAuth::Sign {
241 let secret = self.options.secret.as_ref().map(|s| s.expose_secret()).ok_or(ConstructAuthError::new_missing_secret())?;
242 let mut hmac = Hmac::<Sha256>::new_from_slice(secret.as_bytes()).unwrap();
243
244 let mut request = builder.build().expect("My understanding is that this doesn't fail on client, so fail fast for dev");
245 let param_string = if request.method() == Method::GET || request.method() == Method::DELETE {
246 if let Some(body) = request_body { serde_urlencoded::to_string(body)? } else { String::new() }
247 } else {
248 String::from_utf8(request.body().and_then(|body| body.as_bytes()).unwrap_or_default().to_vec()).unwrap_or_default()
250 };
251
252 let signature_base = format!("{pubkey}{timestamp}{param_string}");
253 hmac.update(signature_base.as_bytes());
254 let signature = hex::encode(hmac.finalize().into_bytes());
255 request.headers_mut().insert("Signature", signature.parse().unwrap());
256
257 return Ok(request);
258 }
259 }
260 Ok(builder.build().expect("Don't expect this to be reached by client. Same reasoning - fail fast for dev"))
261 }
262
263 fn handle_response(&self, status: StatusCode, headers: HeaderMap, response_body: Bytes) -> Result<Self::Successful, HandleError> {
264 if status.is_success() {
265 if let Ok(envelope) = serde_json::from_slice::<MexcEnvelope>(&response_body)
267 && !envelope.success
268 {
269 let api_error = MexcError {
270 code: envelope.code.into(),
271 msg: envelope.message,
272 };
273 return Err(ApiError::from(api_error).into());
274 }
275 serde_json::from_slice(&response_body).map_err(|error| {
276 let response_str = v_utils::utils::truncate_msg(String::from_utf8_lossy(&response_body));
277 HandleError::Parse(eyre!("Failed to parse response: {error}\nResponse body: {response_str}"))
278 })
279 } else {
280 if status == 401 {
281 use v_exchanges_api_generics::http::AuthError;
282 let msg = match std::str::from_utf8(&response_body) {
283 Ok(s) if !s.is_empty() => s.to_string(),
284 _ => "HTTP 401 Unauthorized".to_string(),
285 };
286 return Err(ApiError::Auth(AuthError::Unauthorized { msg }).into());
287 }
288 if status == 429 {
290 let retry_after_sec = if let Some(value) = headers.get("Retry-After") {
291 if let Ok(string) = value.to_str() {
292 if let Ok(retry_after) = u32::from_str(string) {
293 Some(retry_after)
294 } else {
295 tracing::debug!("Invalid number in Retry-After header");
296 None
297 }
298 } else {
299 tracing::debug!("Non-ASCII character in Retry-After header");
300 None
301 }
302 } else {
303 None
304 };
305 let e = match retry_after_sec {
306 Some(s) => {
307 let until = Some(Timestamp::now() + SignedDuration::from_secs(s as i64));
308 ApiError::from(IpError::Timeout { until }).into()
309 }
310 None => eyre!("Could't interpret Retry-After header").into(),
311 };
312 return Err(e);
313 }
314
315 let api_error: MexcError = match serde_json::from_slice(&response_body) {
316 Ok(parsed) => parsed,
317 Err(error) => {
318 let response_str = v_utils::utils::truncate_msg(String::from_utf8_lossy(&response_body));
319 return Err(HandleError::Parse(eyre!("Failed to parse error response: {error}\nResponse body: {response_str}")));
320 }
321 };
322 Err(ApiError::from(api_error).into())
323 }
324 }
325}
326
327impl WsHandler for MexcWsHandler {
329 fn config(&self) -> Result<WsConfig, UrlError> {
330 let mut config = self.options.ws_config.clone();
331 if self.options.ws_url != MexcWsUrl::None {
332 config.base_url = match self.options.testnet {
333 true => Some(self.options.ws_url.url_testnet().ok_or_else(|| UrlError::MissingTestnet(self.options.ws_url.url_mainnet()))?),
334 false => Some(self.options.ws_url.url_mainnet()),
335 }
336 }
337 config.topics = config.topics.union(&self.options.ws_topics).cloned().collect();
338 Ok(config)
339 }
340
341 fn handle_jrpc(&mut self, _jrpc: serde_json::Value) -> Result<ResponseOrContent, WsError> {
342 todo!();
343 }
344
345 fn handle_subscribe(&mut self, _topics: AHashSet<Topic>) -> Result<Vec<generics::tokio_tungstenite::tungstenite::Message>, WsError> {
346 todo!()
347 }
348}
349impl EndpointUrl for MexcWsUrl {
350 fn url_mainnet(&self) -> Url {
351 match self {
352 Self::Spot => Url::parse("wss://stream.mexc.com/ws").unwrap(),
353 Self::Futures => Url::parse("wss://contract.mexc.com/ws").unwrap(),
354 Self::None => Url::parse("").unwrap(),
355 }
356 }
357
358 fn url_testnet(&self) -> Option<Url> {
359 match self {
360 Self::Spot => Some(Url::parse("wss://stream-testnet.mexc.com/ws").unwrap()),
361 Self::Futures => Some(Url::parse("wss://contract-testnet.mexc.com/ws").unwrap()),
362 Self::None => None,
363 }
364 }
365}
366impl WsOption for MexcOption {
367 type WsHandler = MexcWsHandler;
368
369 fn ws_handler(options: Self::Options) -> Self::WsHandler {
370 MexcWsHandler::new(options)
371 }
372}
373impl HandlerOptions for MexcOptions {
376 type OptionItem = MexcOption;
377
378 fn update(&mut self, option: Self::OptionItem) {
379 match option {
380 MexcOption::Default => (),
381 MexcOption::Pubkey(v) => self.pubkey = Some(v),
382 MexcOption::Secret(v) => self.secret = Some(v),
383 MexcOption::Testnet(v) => self.testnet = v,
384 MexcOption::HttpUrl(v) => self.http_url = v,
385 MexcOption::HttpAuth(v) => self.http_auth = v,
386 MexcOption::RecvWindow(v) =>
387 if v > MAX_RECV_WINDOW {
388 tracing::warn!("recvWindow is too large, overwriting with maximum value of {MAX_RECV_WINDOW:?}");
389 self.recv_window = Some(MAX_RECV_WINDOW);
390 } else {
391 self.recv_window = Some(v);
392 },
393 MexcOption::WsUrl(v) => self.ws_url = v,
394 MexcOption::WsConfig(v) => self.ws_config = v,
395 MexcOption::WsTopics(v) => self.ws_topics = v.into_iter().collect(),
396 }
397 }
398
399 fn is_authenticated(&self) -> bool {
400 self.pubkey.is_some() }
402}
403
404impl<'a, R, B> HttpOption<'a, R, B> for MexcOption
405where
406 R: DeserializeOwned + 'a,
407 B: Serialize,
408{
409 type RequestHandler = MexcRequestHandler<'a, R>;
410
411 fn request_handler(options: Self::Options) -> Self::RequestHandler {
412 MexcRequestHandler::<'a, R> { options, _phantom: PhantomData }
413 }
414}
415
416impl HandlerOption for MexcOption {
417 type Options = MexcOptions;
418}