Skip to main content

binance_sdk/c2c/rest_api/apis/
api.rs

1/*
2 * C2C REST API
3 *
4 * Query fiat transaction history via the C2C REST API.
5 *
6 * The version of the OpenAPI document: 1.0.0
7 *
8 *
9 * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
10 * https://openapi-generator.tech
11 * Do not edit the class manually.
12 */
13
14#![allow(unused_imports)]
15use async_trait::async_trait;
16use derive_builder::Builder;
17use reqwest;
18use rust_decimal::prelude::*;
19use serde::{Deserialize, Serialize};
20use serde_json::{Value, json};
21use std::collections::BTreeMap;
22
23use crate::c2c::rest_api::models;
24use crate::common::{
25    config::ConfigurationRestApi,
26    models::{ParamBuildError, RestApiResponse},
27    utils::send_request,
28};
29
30const HAS_TIME_UNIT: bool = false;
31
32#[async_trait]
33pub trait Api: Send + Sync {
34    async fn get_c2_c_trade_history(
35        &self,
36        params: GetC2CTradeHistoryParams,
37    ) -> anyhow::Result<RestApiResponse<models::GetC2CTradeHistoryResponse>>;
38}
39
40#[derive(Debug, Clone)]
41pub struct ApiClient {
42    configuration: ConfigurationRestApi,
43}
44
45impl ApiClient {
46    pub fn new(configuration: ConfigurationRestApi) -> Self {
47        Self { configuration }
48    }
49}
50
51#[allow(non_camel_case_types)]
52#[derive(Debug, Clone, Serialize, Deserialize)]
53pub enum GetC2CTradeHistoryTradeTypeEnum {
54    #[serde(rename = "BUY")]
55    Buy,
56    #[serde(rename = "SELL")]
57    Sell,
58}
59
60impl GetC2CTradeHistoryTradeTypeEnum {
61    #[must_use]
62    pub fn as_str(&self) -> &'static str {
63        match self {
64            Self::Buy => "BUY",
65            Self::Sell => "SELL",
66        }
67    }
68}
69
70impl std::str::FromStr for GetC2CTradeHistoryTradeTypeEnum {
71    type Err = Box<dyn std::error::Error + Send + Sync>;
72
73    fn from_str(s: &str) -> Result<Self, Self::Err> {
74        match s {
75            "BUY" => Ok(Self::Buy),
76            "SELL" => Ok(Self::Sell),
77            other => Err(format!("invalid GetC2CTradeHistoryTradeTypeEnum: {}", other).into()),
78        }
79    }
80}
81
82/// Request parameters for the [`get_c2_c_trade_history`] operation.
83///
84/// This struct holds all of the inputs you can pass when calling
85/// [`get_c2_c_trade_history`](#method.get_c2_c_trade_history).
86#[derive(Clone, Debug, Builder, Deserialize, Default)]
87#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
88pub struct GetC2CTradeHistoryParams {
89    /// Trade side filter
90    ///
91    /// This field is **optional.
92    #[builder(setter(into), default)]
93    #[serde(rename = "tradeType", default)]
94    pub trade_type: Option<GetC2CTradeHistoryTradeTypeEnum>,
95    ///
96    /// The `start_timestamp` parameter.
97    ///
98    /// This field is **optional.
99    #[builder(setter(into), default)]
100    #[serde(rename = "startTimestamp", default)]
101    pub start_timestamp: Option<i64>,
102    ///
103    /// The `end_timestamp` parameter.
104    ///
105    /// This field is **optional.
106    #[builder(setter(into), default)]
107    #[serde(rename = "endTimestamp", default)]
108    pub end_timestamp: Option<i64>,
109    /// Page number
110    ///
111    /// This field is **optional.
112    #[builder(setter(into), default)]
113    #[serde(rename = "page", default)]
114    pub page: Option<i64>,
115    /// Number of records per page
116    ///
117    /// This field is **optional.
118    #[builder(setter(into), default)]
119    #[serde(rename = "rows", default)]
120    pub rows: Option<i64>,
121}
122
123impl GetC2CTradeHistoryParams {
124    /// Create a builder for [`get_c2_c_trade_history`].
125    ///
126    #[must_use]
127    pub fn builder() -> GetC2CTradeHistoryParamsBuilder {
128        GetC2CTradeHistoryParamsBuilder::default()
129    }
130}
131
132#[async_trait]
133impl Api for ApiClient {
134    async fn get_c2_c_trade_history(
135        &self,
136        params: GetC2CTradeHistoryParams,
137    ) -> anyhow::Result<RestApiResponse<models::GetC2CTradeHistoryResponse>> {
138        let GetC2CTradeHistoryParams {
139            trade_type,
140            start_timestamp,
141            end_timestamp,
142            page,
143            rows,
144        } = params;
145
146        let mut query_params = BTreeMap::new();
147        let body_params = BTreeMap::new();
148
149        if let Some(rw) = trade_type {
150            query_params.insert("tradeType".to_string(), json!(rw));
151        }
152
153        if let Some(rw) = start_timestamp {
154            query_params.insert("startTimestamp".to_string(), json!(rw));
155        }
156
157        if let Some(rw) = end_timestamp {
158            query_params.insert("endTimestamp".to_string(), json!(rw));
159        }
160
161        if let Some(rw) = page {
162            query_params.insert("page".to_string(), json!(rw));
163        }
164
165        if let Some(rw) = rows {
166            query_params.insert("rows".to_string(), json!(rw));
167        }
168
169        send_request::<models::GetC2CTradeHistoryResponse>(
170            &self.configuration,
171            "/sapi/v1/c2c/orderMatch/listUserOrderHistory",
172            reqwest::Method::GET,
173            query_params,
174            body_params,
175            if HAS_TIME_UNIT {
176                self.configuration.time_unit
177            } else {
178                None
179            },
180            false,
181        )
182        .await
183    }
184}
185
186#[cfg(all(test, feature = "c2c"))]
187mod tests {
188    use super::*;
189    use crate::TOKIO_SHARED_RT;
190    use crate::{errors::ConnectorError, models::DataFuture, models::RestApiRateLimit};
191    use async_trait::async_trait;
192    use std::collections::HashMap;
193
194    struct DummyRestApiResponse<T> {
195        inner: Box<dyn FnOnce() -> DataFuture<Result<T, ConnectorError>> + Send + Sync>,
196        status: u16,
197        headers: HashMap<String, String>,
198        rate_limits: Option<Vec<RestApiRateLimit>>,
199    }
200
201    impl<T> From<DummyRestApiResponse<T>> for RestApiResponse<T> {
202        fn from(dummy: DummyRestApiResponse<T>) -> Self {
203            Self {
204                data_fn: dummy.inner,
205                status: dummy.status,
206                headers: dummy.headers,
207                rate_limits: dummy.rate_limits,
208            }
209        }
210    }
211
212    struct MockApiClient {
213        force_error: bool,
214    }
215
216    #[async_trait]
217    impl Api for MockApiClient {
218        async fn get_c2_c_trade_history(
219            &self,
220            _params: GetC2CTradeHistoryParams,
221        ) -> anyhow::Result<RestApiResponse<models::GetC2CTradeHistoryResponse>> {
222            if self.force_error {
223                return Err(ConnectorError::ConnectorClientError {
224                    msg: "ResponseError".to_string(),
225                    code: None,
226                }
227                .into());
228            }
229
230            let resp_json: Value = serde_json::from_str(r#"{"code":"000000","message":"success","data":[{"orderNumber":"20219644646554779648","advNo":"11218246497340923904","tradeType":"SELL","asset":"BUSD","fiat":"CNY","fiatSymbol":"¥","amount":"5000.00000000","totalPrice":"33400.00000000","unitPrice":"6.68","orderStatus":"COMPLETED","createTime":1619361369000,"commission":"0","counterPartNickName":"阿涛❤***","payMethodName":"BANK","additionalKycVerify":0,"takerCommissionRate":"0","takerCommission":"0","takerAmount":"343.4","advertisementRole":"TAKER"}],"total":1,"success":true}"#).unwrap_or_else(|_| serde_json::json!({}));
231            let dummy_response: models::GetC2CTradeHistoryResponse =
232                serde_json::from_value(resp_json.clone())
233                    .expect("should parse into models::GetC2CTradeHistoryResponse");
234
235            let dummy = DummyRestApiResponse {
236                inner: Box::new(move || Box::pin(async move { Ok(dummy_response) })),
237                status: 200,
238                headers: HashMap::new(),
239                rate_limits: None,
240            };
241
242            Ok(dummy.into())
243        }
244    }
245
246    #[test]
247    fn get_c2_c_trade_history_required_params_success() {
248        TOKIO_SHARED_RT.block_on(async {
249            let client = MockApiClient { force_error: false };
250
251            let params = GetC2CTradeHistoryParams::builder().build().unwrap();
252
253            let resp_json: Value = serde_json::from_str(r#"{"code":"000000","message":"success","data":[{"orderNumber":"20219644646554779648","advNo":"11218246497340923904","tradeType":"SELL","asset":"BUSD","fiat":"CNY","fiatSymbol":"¥","amount":"5000.00000000","totalPrice":"33400.00000000","unitPrice":"6.68","orderStatus":"COMPLETED","createTime":1619361369000,"commission":"0","counterPartNickName":"阿涛❤***","payMethodName":"BANK","additionalKycVerify":0,"takerCommissionRate":"0","takerCommission":"0","takerAmount":"343.4","advertisementRole":"TAKER"}],"total":1,"success":true}"#).unwrap_or_else(|_| serde_json::json!({}));
254            let expected_response : models::GetC2CTradeHistoryResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::GetC2CTradeHistoryResponse");
255
256            let resp = client.get_c2_c_trade_history(params).await.expect("Expected a response");
257            let data_future = resp.data();
258            let actual_response = data_future.await.unwrap();
259            assert_eq!(actual_response, expected_response);
260        });
261    }
262
263    #[test]
264    fn get_c2_c_trade_history_optional_params_success() {
265        TOKIO_SHARED_RT.block_on(async {
266            let client = MockApiClient { force_error: false };
267
268            let params = GetC2CTradeHistoryParams::builder().trade_type(GetC2CTradeHistoryTradeTypeEnum::Buy).start_timestamp(1770736694138).end_timestamp(1770736694138).page(1).rows(100).build().unwrap();
269
270            let resp_json: Value = serde_json::from_str(r#"{"code":"000000","message":"success","data":[{"orderNumber":"20219644646554779648","advNo":"11218246497340923904","tradeType":"SELL","asset":"BUSD","fiat":"CNY","fiatSymbol":"¥","amount":"5000.00000000","totalPrice":"33400.00000000","unitPrice":"6.68","orderStatus":"COMPLETED","createTime":1619361369000,"commission":"0","counterPartNickName":"阿涛❤***","payMethodName":"BANK","additionalKycVerify":0,"takerCommissionRate":"0","takerCommission":"0","takerAmount":"343.4","advertisementRole":"TAKER"}],"total":1,"success":true}"#).unwrap_or_else(|_| serde_json::json!({}));
271            let expected_response : models::GetC2CTradeHistoryResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::GetC2CTradeHistoryResponse");
272
273            let resp = client.get_c2_c_trade_history(params).await.expect("Expected a response");
274            let data_future = resp.data();
275            let actual_response = data_future.await.unwrap();
276            assert_eq!(actual_response, expected_response);
277        });
278    }
279
280    #[test]
281    fn get_c2_c_trade_history_response_error() {
282        TOKIO_SHARED_RT.block_on(async {
283            let client = MockApiClient { force_error: true };
284
285            let params = GetC2CTradeHistoryParams::builder().build().unwrap();
286
287            match client.get_c2_c_trade_history(params).await {
288                Ok(_) => panic!("Expected an error"),
289                Err(err) => {
290                    assert_eq!(err.to_string(), "Connector client error: ResponseError");
291                }
292            }
293        });
294    }
295}