binance_async_api/rest/
mod.rs

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
pub mod coinm;
pub mod spot;
pub mod usdm;

use crate::{
    client::{BinanceClient, Product},
    errors::{BinanceError, BinanceResponse, BinanceResponseContent},
};
use chrono::Utc;
use hex::encode as hexify;
use hmac::{Hmac, Mac};
use reqwest::{
    header::{HeaderMap, HeaderName, HeaderValue, CONTENT_TYPE, USER_AGENT},
    Method, Response,
};
use serde::{de::DeserializeOwned, Serialize};
use serde_json::from_str;
use sha2::Sha256;

pub trait Request: Serialize {
    const PRODUCT: Product;
    const ENDPOINT: &'static str;
    const METHOD: Method;
    const KEYED: bool = false; // SIGNED imples KEYED no matter KEYED is true or false
    const SIGNED: bool = false;
    type Response: DeserializeOwned;
}

impl BinanceClient {
    pub async fn request<R>(
        &self,
        req: R,
        api_key: Option<&str>,
        api_secret: Option<&str>,
    ) -> Result<BinanceResponse<R::Response>, BinanceError>
    where
        R: Request,
    {
        let mut params = if matches!(R::METHOD, Method::GET) {
            serde_qs::to_string(&req).unwrap()
        } else {
            String::new()
        };

        let body = if !matches!(R::METHOD, Method::GET) {
            serde_qs::to_string(&req).unwrap()
        } else {
            String::new()
        };

        if R::SIGNED {
            let secret = match api_secret {
                Some(s) => s,
                None => return Err(BinanceError::MissingApiSecret),
            };
            if !params.is_empty() {
                params.push('&');
            }
            params.push_str(&format!("timestamp={}", Utc::now().timestamp_millis()));

            let signature = signature(&params, &body, secret);
            params.push_str(&format!("&signature={}", signature));
        }

        let path = R::ENDPOINT;

        let base = match R::PRODUCT {
            Product::Spot => self.config.rest_api_endpoint,
            Product::UsdMFutures => self.config.usdm_futures_rest_api_endpoint,
            Product::CoinMFutures => self.config.coinm_futures_rest_api_endpoint,
        };
        let url = format!("{base}{path}?{params}");

        let mut custom_headers = HeaderMap::new();
        custom_headers.insert(USER_AGENT, HeaderValue::from_static("binance-async-api"));
        if !body.is_empty() {
            custom_headers.insert(
                CONTENT_TYPE,
                HeaderValue::from_static("application/x-www-form-urlencoded"),
            );
        }
        if R::SIGNED || R::KEYED {
            let key = match api_key {
                Some(key) => key,
                None => return Err(BinanceError::MissingApiKey),
            };
            custom_headers.insert(
                HeaderName::from_static("x-mbx-apikey"),
                HeaderValue::from_str(key).map_err(|_| BinanceError::InvalidApiKey)?,
            );
        }

        let resp = self
            .client
            .request(R::METHOD, url.as_str())
            .headers(custom_headers)
            .body(body)
            .send()
            .await?;

        handle_response(resp).await
    }
}

fn signature(params: &str, body: &str, secret: &str) -> String {
    // Signature: hex(HMAC_SHA256(queries + data))
    let mut mac = Hmac::<Sha256>::new_from_slice(secret.as_bytes()).unwrap();
    let sign_message = format!("{}{}", params, body);
    mac.update(sign_message.as_bytes());
    hexify(mac.finalize().into_bytes())
}

async fn handle_response<O: DeserializeOwned>(resp: Response) -> Result<BinanceResponse<O>, BinanceError> {
    let status_code = resp.status();
    let headers = resp.headers().clone();
    let resp_text = resp.text().await?;
    dbg!(&resp_text);
    let resp_content: BinanceResponseContent<O> = from_str(&resp_text).unwrap();
    // let resp_content: BinanceResponseContent<O> = resp.json().await?;
    match resp_content {
        BinanceResponseContent::Success(content) => Ok(BinanceResponse {
            status_code,
            headers,
            content,
        }),
        BinanceResponseContent::Error(content) => Err(BinanceError::BinanceResponse {
            status_code,
            headers,
            content,
        }),
    }
}