/*
 * Binance NFT REST API
 *
 * OpenAPI Specification for the Binance NFT REST API
 *
 * The version of the OpenAPI document: 1.0.0
 *
 *
 * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
 * https://openapi-generator.tech
 * Do not edit the class manually.
 */

#![allow(unused_imports)]
use async_trait::async_trait;
use derive_builder::Builder;
use reqwest;
use rust_decimal::prelude::*;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use std::collections::BTreeMap;

use crate::common::{
    config::ConfigurationRestApi,
    models::{ParamBuildError, RestApiResponse},
    utils::send_request,
};
use crate::nft::rest_api::models;

const HAS_TIME_UNIT: bool = false;

#[async_trait]
pub trait NftApi: Send + Sync {
    async fn get_nft_asset(
        &self,
        params: GetNftAssetParams,
    ) -> anyhow::Result<RestApiResponse<models::GetNftAssetResponse>>;
    async fn get_nft_deposit_history(
        &self,
        params: GetNftDepositHistoryParams,
    ) -> anyhow::Result<RestApiResponse<models::GetNftDepositHistoryResponse>>;
    async fn get_nft_transaction_history(
        &self,
        params: GetNftTransactionHistoryParams,
    ) -> anyhow::Result<RestApiResponse<models::GetNftTransactionHistoryResponse>>;
    async fn get_nft_withdraw_history(
        &self,
        params: GetNftWithdrawHistoryParams,
    ) -> anyhow::Result<RestApiResponse<models::GetNftWithdrawHistoryResponse>>;
}

#[derive(Debug, Clone)]
pub struct NftApiClient {
    configuration: ConfigurationRestApi,
}

impl NftApiClient {
    pub fn new(configuration: ConfigurationRestApi) -> Self {
        Self { configuration }
    }
}

/// Request parameters for the [`get_nft_asset`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`get_nft_asset`](#method.get_nft_asset).
#[derive(Clone, Debug, Builder, Default)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct GetNftAssetParams {
    /// Default 50, Max 50
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub limit: Option<i64>,
    /// Default 1
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub page: Option<i64>,
    ///
    /// The `recv_window` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub recv_window: Option<i64>,
}

impl GetNftAssetParams {
    /// Create a builder for [`get_nft_asset`].
    ///
    #[must_use]
    pub fn builder() -> GetNftAssetParamsBuilder {
        GetNftAssetParamsBuilder::default()
    }
}
/// Request parameters for the [`get_nft_deposit_history`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`get_nft_deposit_history`](#method.get_nft_deposit_history).
#[derive(Clone, Debug, Builder, Default)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct GetNftDepositHistoryParams {
    ///
    /// The `start_time` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub start_time: Option<i64>,
    ///
    /// The `end_time` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub end_time: Option<i64>,
    /// Default 50, Max 50
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub limit: Option<i64>,
    /// Default 1
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub page: Option<i64>,
    ///
    /// The `recv_window` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub recv_window: Option<i64>,
}

impl GetNftDepositHistoryParams {
    /// Create a builder for [`get_nft_deposit_history`].
    ///
    #[must_use]
    pub fn builder() -> GetNftDepositHistoryParamsBuilder {
        GetNftDepositHistoryParamsBuilder::default()
    }
}
/// Request parameters for the [`get_nft_transaction_history`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`get_nft_transaction_history`](#method.get_nft_transaction_history).
#[derive(Clone, Debug, Builder)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct GetNftTransactionHistoryParams {
    /// 0: purchase order, 1: sell order, 2: royalty income, 3: primary market order, 4: mint fee
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub order_type: i64,
    ///
    /// The `start_time` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub start_time: Option<i64>,
    ///
    /// The `end_time` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub end_time: Option<i64>,
    /// Default 50, Max 50
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub limit: Option<i64>,
    /// Default 1
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub page: Option<i64>,
    ///
    /// The `recv_window` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub recv_window: Option<i64>,
}

impl GetNftTransactionHistoryParams {
    /// Create a builder for [`get_nft_transaction_history`].
    ///
    /// Required parameters:
    ///
    /// * `order_type` — 0: purchase order, 1: sell order, 2: royalty income, 3: primary market order, 4: mint fee
    ///
    #[must_use]
    pub fn builder(order_type: i64) -> GetNftTransactionHistoryParamsBuilder {
        GetNftTransactionHistoryParamsBuilder::default().order_type(order_type)
    }
}
/// Request parameters for the [`get_nft_withdraw_history`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`get_nft_withdraw_history`](#method.get_nft_withdraw_history).
#[derive(Clone, Debug, Builder, Default)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct GetNftWithdrawHistoryParams {
    ///
    /// The `start_time` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub start_time: Option<i64>,
    ///
    /// The `end_time` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub end_time: Option<i64>,
    /// Default 50, Max 50
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub limit: Option<i64>,
    /// Default 1
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub page: Option<i64>,
    ///
    /// The `recv_window` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub recv_window: Option<i64>,
}

impl GetNftWithdrawHistoryParams {
    /// Create a builder for [`get_nft_withdraw_history`].
    ///
    #[must_use]
    pub fn builder() -> GetNftWithdrawHistoryParamsBuilder {
        GetNftWithdrawHistoryParamsBuilder::default()
    }
}

#[async_trait]
impl NftApi for NftApiClient {
    async fn get_nft_asset(
        &self,
        params: GetNftAssetParams,
    ) -> anyhow::Result<RestApiResponse<models::GetNftAssetResponse>> {
        let GetNftAssetParams {
            limit,
            page,
            recv_window,
        } = params;

        let mut query_params = BTreeMap::new();
        let body_params = BTreeMap::new();

        if let Some(rw) = limit {
            query_params.insert("limit".to_string(), json!(rw));
        }

        if let Some(rw) = page {
            query_params.insert("page".to_string(), json!(rw));
        }

        if let Some(rw) = recv_window {
            query_params.insert("recvWindow".to_string(), json!(rw));
        }

        send_request::<models::GetNftAssetResponse>(
            &self.configuration,
            "/sapi/v1/nft/user/getAsset",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }

    async fn get_nft_deposit_history(
        &self,
        params: GetNftDepositHistoryParams,
    ) -> anyhow::Result<RestApiResponse<models::GetNftDepositHistoryResponse>> {
        let GetNftDepositHistoryParams {
            start_time,
            end_time,
            limit,
            page,
            recv_window,
        } = params;

        let mut query_params = BTreeMap::new();
        let body_params = BTreeMap::new();

        if let Some(rw) = start_time {
            query_params.insert("startTime".to_string(), json!(rw));
        }

        if let Some(rw) = end_time {
            query_params.insert("endTime".to_string(), json!(rw));
        }

        if let Some(rw) = limit {
            query_params.insert("limit".to_string(), json!(rw));
        }

        if let Some(rw) = page {
            query_params.insert("page".to_string(), json!(rw));
        }

        if let Some(rw) = recv_window {
            query_params.insert("recvWindow".to_string(), json!(rw));
        }

        send_request::<models::GetNftDepositHistoryResponse>(
            &self.configuration,
            "/sapi/v1/nft/history/deposit",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }

    async fn get_nft_transaction_history(
        &self,
        params: GetNftTransactionHistoryParams,
    ) -> anyhow::Result<RestApiResponse<models::GetNftTransactionHistoryResponse>> {
        let GetNftTransactionHistoryParams {
            order_type,
            start_time,
            end_time,
            limit,
            page,
            recv_window,
        } = params;

        let mut query_params = BTreeMap::new();
        let body_params = BTreeMap::new();

        query_params.insert("orderType".to_string(), json!(order_type));

        if let Some(rw) = start_time {
            query_params.insert("startTime".to_string(), json!(rw));
        }

        if let Some(rw) = end_time {
            query_params.insert("endTime".to_string(), json!(rw));
        }

        if let Some(rw) = limit {
            query_params.insert("limit".to_string(), json!(rw));
        }

        if let Some(rw) = page {
            query_params.insert("page".to_string(), json!(rw));
        }

        if let Some(rw) = recv_window {
            query_params.insert("recvWindow".to_string(), json!(rw));
        }

        send_request::<models::GetNftTransactionHistoryResponse>(
            &self.configuration,
            "/sapi/v1/nft/history/transactions",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }

    async fn get_nft_withdraw_history(
        &self,
        params: GetNftWithdrawHistoryParams,
    ) -> anyhow::Result<RestApiResponse<models::GetNftWithdrawHistoryResponse>> {
        let GetNftWithdrawHistoryParams {
            start_time,
            end_time,
            limit,
            page,
            recv_window,
        } = params;

        let mut query_params = BTreeMap::new();
        let body_params = BTreeMap::new();

        if let Some(rw) = start_time {
            query_params.insert("startTime".to_string(), json!(rw));
        }

        if let Some(rw) = end_time {
            query_params.insert("endTime".to_string(), json!(rw));
        }

        if let Some(rw) = limit {
            query_params.insert("limit".to_string(), json!(rw));
        }

        if let Some(rw) = page {
            query_params.insert("page".to_string(), json!(rw));
        }

        if let Some(rw) = recv_window {
            query_params.insert("recvWindow".to_string(), json!(rw));
        }

        send_request::<models::GetNftWithdrawHistoryResponse>(
            &self.configuration,
            "/sapi/v1/nft/history/withdraw",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }
}

#[cfg(all(test, feature = "nft"))]
mod tests {
    use super::*;
    use crate::TOKIO_SHARED_RT;
    use crate::{errors::ConnectorError, models::DataFuture, models::RestApiRateLimit};
    use async_trait::async_trait;
    use std::collections::HashMap;

    struct DummyRestApiResponse<T> {
        inner: Box<dyn FnOnce() -> DataFuture<Result<T, ConnectorError>> + Send + Sync>,
        status: u16,
        headers: HashMap<String, String>,
        rate_limits: Option<Vec<RestApiRateLimit>>,
    }

    impl<T> From<DummyRestApiResponse<T>> for RestApiResponse<T> {
        fn from(dummy: DummyRestApiResponse<T>) -> Self {
            Self {
                data_fn: dummy.inner,
                status: dummy.status,
                headers: dummy.headers,
                rate_limits: dummy.rate_limits,
            }
        }
    }

    struct MockNftApiClient {
        force_error: bool,
    }

    #[async_trait]
    impl NftApi for MockNftApiClient {
        async fn get_nft_asset(
            &self,
            _params: GetNftAssetParams,
        ) -> anyhow::Result<RestApiResponse<models::GetNftAssetResponse>> {
            if self.force_error {
                return Err(ConnectorError::ConnectorClientError {
                    msg: "ResponseError".to_string(),
                    code: None,
                }
                .into());
            }

            let resp_json: Value = serde_json::from_str(r#"{"total":347,"list":[{"network":"BSC","contractAddress":"REGULAR11234567891779","tokenId":"100900000017"},{"network":"BSC","contractAddress":"SSMDQ8W59","tokenId":"200500000011"},{"network":"BSC","contractAddress":"SSMDQ8W59","tokenId":"200500000019"}]}"#).unwrap();
            let dummy_response: models::GetNftAssetResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::GetNftAssetResponse");

            let dummy = DummyRestApiResponse {
                inner: Box::new(move || Box::pin(async move { Ok(dummy_response) })),
                status: 200,
                headers: HashMap::new(),
                rate_limits: None,
            };

            Ok(dummy.into())
        }

        async fn get_nft_deposit_history(
            &self,
            _params: GetNftDepositHistoryParams,
        ) -> anyhow::Result<RestApiResponse<models::GetNftDepositHistoryResponse>> {
            if self.force_error {
                return Err(ConnectorError::ConnectorClientError {
                    msg: "ResponseError".to_string(),
                    code: None,
                }
                .into());
            }

            let resp_json: Value = serde_json::from_str(r#"{"total":2,"list":[{"network":"ETH","txID":null,"contractAdrress":"0xe507c961ee127d4439977a61af39c34eafee0dc6","tokenId":"10014","timestamp":1629986047000},{"network":"BSC","txID":null,"contractAdrress":"0x058451b463bab04f52c0799d55c4094f507acfa9","tokenId":"10016","timestamp":1630083581000}]}"#).unwrap();
            let dummy_response: models::GetNftDepositHistoryResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::GetNftDepositHistoryResponse");

            let dummy = DummyRestApiResponse {
                inner: Box::new(move || Box::pin(async move { Ok(dummy_response) })),
                status: 200,
                headers: HashMap::new(),
                rate_limits: None,
            };

            Ok(dummy.into())
        }

        async fn get_nft_transaction_history(
            &self,
            _params: GetNftTransactionHistoryParams,
        ) -> anyhow::Result<RestApiResponse<models::GetNftTransactionHistoryResponse>> {
            if self.force_error {
                return Err(ConnectorError::ConnectorClientError {
                    msg: "ResponseError".to_string(),
                    code: None,
                }
                .into());
            }

            let resp_json: Value = serde_json::from_str(r#"{"total":2,"list":[{"orderNo":"1_470502070600699904","tokens":[{"network":"BSC","tokenId":"216000000496","contractAddress":"MYSTERY_BOX0000087"}],"tradeTime":1626941236000,"tradeAmount":"19.60000000","tradeCurrency":"BNB"},{"orderNo":"1_488306442479116288","tokens":[{"network":"BSC","tokenId":"132900000007","contractAddress":"0xAf12111a592e408DAbC740849fcd5e68629D9fb6"}],"tradeTime":1631186130000,"tradeAmount":"192.00000000","tradeCurrency":"BNB"}]}"#).unwrap();
            let dummy_response: models::GetNftTransactionHistoryResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::GetNftTransactionHistoryResponse");

            let dummy = DummyRestApiResponse {
                inner: Box::new(move || Box::pin(async move { Ok(dummy_response) })),
                status: 200,
                headers: HashMap::new(),
                rate_limits: None,
            };

            Ok(dummy.into())
        }

        async fn get_nft_withdraw_history(
            &self,
            _params: GetNftWithdrawHistoryParams,
        ) -> anyhow::Result<RestApiResponse<models::GetNftWithdrawHistoryResponse>> {
            if self.force_error {
                return Err(ConnectorError::ConnectorClientError {
                    msg: "ResponseError".to_string(),
                    code: None,
                }
                .into());
            }

            let resp_json: Value = serde_json::from_str(r#"{"total":178,"list":[{"network":"ETH","txID":"0x2be5eed31d787fdb4880bc631c8e76bdfb6150e137f5cf1732e0416ea206f57f","contractAdrress":"0xe507c961ee127d4439977a61af39c34eafee0dc6","tokenId":"1000001247","timestamp":1633674433000,"fee":0.1,"feeAsset":"ETH"},{"network":"ETH","txID":"0x3b3aea5c0a4faccd6f306641e6deb9713ab229ac233be3be227f580311e4362a","contractAdrress":"0xe507c961ee127d4439977a61af39c34eafee0dc6","tokenId":"40000030","timestamp":1633677022000,"fee":0.1,"feeAsset":"ETH"}]}"#).unwrap();
            let dummy_response: models::GetNftWithdrawHistoryResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::GetNftWithdrawHistoryResponse");

            let dummy = DummyRestApiResponse {
                inner: Box::new(move || Box::pin(async move { Ok(dummy_response) })),
                status: 200,
                headers: HashMap::new(),
                rate_limits: None,
            };

            Ok(dummy.into())
        }
    }

    #[test]
    fn get_nft_asset_required_params_success() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockNftApiClient { force_error: false };

            let params = GetNftAssetParams::builder().build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"total":347,"list":[{"network":"BSC","contractAddress":"REGULAR11234567891779","tokenId":"100900000017"},{"network":"BSC","contractAddress":"SSMDQ8W59","tokenId":"200500000011"},{"network":"BSC","contractAddress":"SSMDQ8W59","tokenId":"200500000019"}]}"#).unwrap();
            let expected_response : models::GetNftAssetResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::GetNftAssetResponse");

            let resp = client.get_nft_asset(params).await.expect("Expected a response");
            let data_future = resp.data();
            let actual_response = data_future.await.unwrap();
            assert_eq!(actual_response, expected_response);
        });
    }

    #[test]
    fn get_nft_asset_optional_params_success() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockNftApiClient { force_error: false };

            let params = GetNftAssetParams::builder().limit(50).page(1).recv_window(5000).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"total":347,"list":[{"network":"BSC","contractAddress":"REGULAR11234567891779","tokenId":"100900000017"},{"network":"BSC","contractAddress":"SSMDQ8W59","tokenId":"200500000011"},{"network":"BSC","contractAddress":"SSMDQ8W59","tokenId":"200500000019"}]}"#).unwrap();
            let expected_response : models::GetNftAssetResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::GetNftAssetResponse");

            let resp = client.get_nft_asset(params).await.expect("Expected a response");
            let data_future = resp.data();
            let actual_response = data_future.await.unwrap();
            assert_eq!(actual_response, expected_response);
        });
    }

    #[test]
    fn get_nft_asset_response_error() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockNftApiClient { force_error: true };

            let params = GetNftAssetParams::builder().build().unwrap();

            match client.get_nft_asset(params).await {
                Ok(_) => panic!("Expected an error"),
                Err(err) => {
                    assert_eq!(err.to_string(), "Connector client error: ResponseError");
                }
            }
        });
    }

    #[test]
    fn get_nft_deposit_history_required_params_success() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockNftApiClient { force_error: false };

            let params = GetNftDepositHistoryParams::builder().build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"total":2,"list":[{"network":"ETH","txID":null,"contractAdrress":"0xe507c961ee127d4439977a61af39c34eafee0dc6","tokenId":"10014","timestamp":1629986047000},{"network":"BSC","txID":null,"contractAdrress":"0x058451b463bab04f52c0799d55c4094f507acfa9","tokenId":"10016","timestamp":1630083581000}]}"#).unwrap();
            let expected_response : models::GetNftDepositHistoryResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::GetNftDepositHistoryResponse");

            let resp = client.get_nft_deposit_history(params).await.expect("Expected a response");
            let data_future = resp.data();
            let actual_response = data_future.await.unwrap();
            assert_eq!(actual_response, expected_response);
        });
    }

    #[test]
    fn get_nft_deposit_history_optional_params_success() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockNftApiClient { force_error: false };

            let params = GetNftDepositHistoryParams::builder().start_time(1623319461670).end_time(1641782889000).limit(50).page(1).recv_window(5000).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"total":2,"list":[{"network":"ETH","txID":null,"contractAdrress":"0xe507c961ee127d4439977a61af39c34eafee0dc6","tokenId":"10014","timestamp":1629986047000},{"network":"BSC","txID":null,"contractAdrress":"0x058451b463bab04f52c0799d55c4094f507acfa9","tokenId":"10016","timestamp":1630083581000}]}"#).unwrap();
            let expected_response : models::GetNftDepositHistoryResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::GetNftDepositHistoryResponse");

            let resp = client.get_nft_deposit_history(params).await.expect("Expected a response");
            let data_future = resp.data();
            let actual_response = data_future.await.unwrap();
            assert_eq!(actual_response, expected_response);
        });
    }

    #[test]
    fn get_nft_deposit_history_response_error() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockNftApiClient { force_error: true };

            let params = GetNftDepositHistoryParams::builder().build().unwrap();

            match client.get_nft_deposit_history(params).await {
                Ok(_) => panic!("Expected an error"),
                Err(err) => {
                    assert_eq!(err.to_string(), "Connector client error: ResponseError");
                }
            }
        });
    }

    #[test]
    fn get_nft_transaction_history_required_params_success() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockNftApiClient { force_error: false };

            let params = GetNftTransactionHistoryParams::builder(789,).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"total":2,"list":[{"orderNo":"1_470502070600699904","tokens":[{"network":"BSC","tokenId":"216000000496","contractAddress":"MYSTERY_BOX0000087"}],"tradeTime":1626941236000,"tradeAmount":"19.60000000","tradeCurrency":"BNB"},{"orderNo":"1_488306442479116288","tokens":[{"network":"BSC","tokenId":"132900000007","contractAddress":"0xAf12111a592e408DAbC740849fcd5e68629D9fb6"}],"tradeTime":1631186130000,"tradeAmount":"192.00000000","tradeCurrency":"BNB"}]}"#).unwrap();
            let expected_response : models::GetNftTransactionHistoryResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::GetNftTransactionHistoryResponse");

            let resp = client.get_nft_transaction_history(params).await.expect("Expected a response");
            let data_future = resp.data();
            let actual_response = data_future.await.unwrap();
            assert_eq!(actual_response, expected_response);
        });
    }

    #[test]
    fn get_nft_transaction_history_optional_params_success() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockNftApiClient { force_error: false };

            let params = GetNftTransactionHistoryParams::builder(789,).start_time(1623319461670).end_time(1641782889000).limit(50).page(1).recv_window(5000).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"total":2,"list":[{"orderNo":"1_470502070600699904","tokens":[{"network":"BSC","tokenId":"216000000496","contractAddress":"MYSTERY_BOX0000087"}],"tradeTime":1626941236000,"tradeAmount":"19.60000000","tradeCurrency":"BNB"},{"orderNo":"1_488306442479116288","tokens":[{"network":"BSC","tokenId":"132900000007","contractAddress":"0xAf12111a592e408DAbC740849fcd5e68629D9fb6"}],"tradeTime":1631186130000,"tradeAmount":"192.00000000","tradeCurrency":"BNB"}]}"#).unwrap();
            let expected_response : models::GetNftTransactionHistoryResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::GetNftTransactionHistoryResponse");

            let resp = client.get_nft_transaction_history(params).await.expect("Expected a response");
            let data_future = resp.data();
            let actual_response = data_future.await.unwrap();
            assert_eq!(actual_response, expected_response);
        });
    }

    #[test]
    fn get_nft_transaction_history_response_error() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockNftApiClient { force_error: true };

            let params = GetNftTransactionHistoryParams::builder(789)
                .build()
                .unwrap();

            match client.get_nft_transaction_history(params).await {
                Ok(_) => panic!("Expected an error"),
                Err(err) => {
                    assert_eq!(err.to_string(), "Connector client error: ResponseError");
                }
            }
        });
    }

    #[test]
    fn get_nft_withdraw_history_required_params_success() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockNftApiClient { force_error: false };

            let params = GetNftWithdrawHistoryParams::builder().build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"total":178,"list":[{"network":"ETH","txID":"0x2be5eed31d787fdb4880bc631c8e76bdfb6150e137f5cf1732e0416ea206f57f","contractAdrress":"0xe507c961ee127d4439977a61af39c34eafee0dc6","tokenId":"1000001247","timestamp":1633674433000,"fee":0.1,"feeAsset":"ETH"},{"network":"ETH","txID":"0x3b3aea5c0a4faccd6f306641e6deb9713ab229ac233be3be227f580311e4362a","contractAdrress":"0xe507c961ee127d4439977a61af39c34eafee0dc6","tokenId":"40000030","timestamp":1633677022000,"fee":0.1,"feeAsset":"ETH"}]}"#).unwrap();
            let expected_response : models::GetNftWithdrawHistoryResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::GetNftWithdrawHistoryResponse");

            let resp = client.get_nft_withdraw_history(params).await.expect("Expected a response");
            let data_future = resp.data();
            let actual_response = data_future.await.unwrap();
            assert_eq!(actual_response, expected_response);
        });
    }

    #[test]
    fn get_nft_withdraw_history_optional_params_success() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockNftApiClient { force_error: false };

            let params = GetNftWithdrawHistoryParams::builder().start_time(1623319461670).end_time(1641782889000).limit(50).page(1).recv_window(5000).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"total":178,"list":[{"network":"ETH","txID":"0x2be5eed31d787fdb4880bc631c8e76bdfb6150e137f5cf1732e0416ea206f57f","contractAdrress":"0xe507c961ee127d4439977a61af39c34eafee0dc6","tokenId":"1000001247","timestamp":1633674433000,"fee":0.1,"feeAsset":"ETH"},{"network":"ETH","txID":"0x3b3aea5c0a4faccd6f306641e6deb9713ab229ac233be3be227f580311e4362a","contractAdrress":"0xe507c961ee127d4439977a61af39c34eafee0dc6","tokenId":"40000030","timestamp":1633677022000,"fee":0.1,"feeAsset":"ETH"}]}"#).unwrap();
            let expected_response : models::GetNftWithdrawHistoryResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::GetNftWithdrawHistoryResponse");

            let resp = client.get_nft_withdraw_history(params).await.expect("Expected a response");
            let data_future = resp.data();
            let actual_response = data_future.await.unwrap();
            assert_eq!(actual_response, expected_response);
        });
    }

    #[test]
    fn get_nft_withdraw_history_response_error() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockNftApiClient { force_error: true };

            let params = GetNftWithdrawHistoryParams::builder().build().unwrap();

            match client.get_nft_withdraw_history(params).await {
                Ok(_) => panic!("Expected an error"),
                Err(err) => {
                    assert_eq!(err.to_string(), "Connector client error: ResponseError");
                }
            }
        });
    }
}
