/*
 * Binance Wallet REST API
 *
 * OpenAPI Specification for the Binance Wallet 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::wallet::rest_api::models;

const HAS_TIME_UNIT: bool = false;

#[async_trait]
pub trait CapitalApi: Send + Sync {
    async fn all_coins_information(
        &self,
        params: AllCoinsInformationParams,
    ) -> anyhow::Result<RestApiResponse<Vec<models::AllCoinsInformationResponseInner>>>;
    async fn deposit_address(
        &self,
        params: DepositAddressParams,
    ) -> anyhow::Result<RestApiResponse<models::DepositAddressResponse>>;
    async fn deposit_history(
        &self,
        params: DepositHistoryParams,
    ) -> anyhow::Result<RestApiResponse<Vec<models::DepositHistoryResponseInner>>>;
    async fn fetch_deposit_address_list_with_network(
        &self,
        params: FetchDepositAddressListWithNetworkParams,
    ) -> anyhow::Result<RestApiResponse<Vec<models::FetchDepositAddressListWithNetworkResponseInner>>>;
    async fn fetch_withdraw_address_list(
        &self,
    ) -> anyhow::Result<RestApiResponse<Vec<models::FetchWithdrawAddressListResponseInner>>>;
    async fn fetch_withdraw_quota(
        &self,
    ) -> anyhow::Result<RestApiResponse<models::FetchWithdrawQuotaResponse>>;
    async fn one_click_arrival_deposit_apply(
        &self,
        params: OneClickArrivalDepositApplyParams,
    ) -> anyhow::Result<RestApiResponse<models::OneClickArrivalDepositApplyResponse>>;
    async fn withdraw(
        &self,
        params: WithdrawParams,
    ) -> anyhow::Result<RestApiResponse<models::WithdrawResponse>>;
    async fn withdraw_history(
        &self,
        params: WithdrawHistoryParams,
    ) -> anyhow::Result<RestApiResponse<Vec<models::WithdrawHistoryResponseInner>>>;
}

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

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

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

impl AllCoinsInformationParams {
    /// Create a builder for [`all_coins_information`].
    ///
    #[must_use]
    pub fn builder() -> AllCoinsInformationParamsBuilder {
        AllCoinsInformationParamsBuilder::default()
    }
}
/// Request parameters for the [`deposit_address`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`deposit_address`](#method.deposit_address).
#[derive(Clone, Debug, Builder)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct DepositAddressParams {
    ///
    /// The `coin` parameter.
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub coin: String,
    ///
    /// The `network` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub network: Option<String>,
    ///
    /// The `amount` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub amount: Option<rust_decimal::Decimal>,
    ///
    /// The `recv_window` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub recv_window: Option<i64>,
}

impl DepositAddressParams {
    /// Create a builder for [`deposit_address`].
    ///
    /// Required parameters:
    ///
    /// * `coin` — String
    ///
    #[must_use]
    pub fn builder(coin: String) -> DepositAddressParamsBuilder {
        DepositAddressParamsBuilder::default().coin(coin)
    }
}
/// Request parameters for the [`deposit_history`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`deposit_history`](#method.deposit_history).
#[derive(Clone, Debug, Builder, Default)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct DepositHistoryParams {
    /// Default: `false`, return `sourceAddress`field when set to `true`
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub include_source: Option<bool>,
    ///
    /// The `coin` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub coin: Option<String>,
    /// 0(0:Email Sent, 2:Awaiting Approval 3:Rejected 4:Processing 6:Completed)
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub status: Option<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: 0
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub offset: Option<i64>,
    /// min 7, max 30, default 7
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub limit: Option<i64>,
    ///
    /// The `recv_window` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub recv_window: Option<i64>,
    ///
    /// The `tx_id` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub tx_id: Option<String>,
}

impl DepositHistoryParams {
    /// Create a builder for [`deposit_history`].
    ///
    #[must_use]
    pub fn builder() -> DepositHistoryParamsBuilder {
        DepositHistoryParamsBuilder::default()
    }
}
/// Request parameters for the [`fetch_deposit_address_list_with_network`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`fetch_deposit_address_list_with_network`](#method.fetch_deposit_address_list_with_network).
#[derive(Clone, Debug, Builder)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct FetchDepositAddressListWithNetworkParams {
    ///
    /// The `coin` parameter.
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub coin: String,
    ///
    /// The `network` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub network: Option<String>,
}

impl FetchDepositAddressListWithNetworkParams {
    /// Create a builder for [`fetch_deposit_address_list_with_network`].
    ///
    /// Required parameters:
    ///
    /// * `coin` — String
    ///
    #[must_use]
    pub fn builder(coin: String) -> FetchDepositAddressListWithNetworkParamsBuilder {
        FetchDepositAddressListWithNetworkParamsBuilder::default().coin(coin)
    }
}
/// Request parameters for the [`one_click_arrival_deposit_apply`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`one_click_arrival_deposit_apply`](#method.one_click_arrival_deposit_apply).
#[derive(Clone, Debug, Builder, Default)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct OneClickArrivalDepositApplyParams {
    /// Deposit record Id, priority use
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub deposit_id: Option<i64>,
    ///
    /// The `tx_id` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub tx_id: Option<String>,
    /// Sub-accountId of Cloud user
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub sub_account_id: Option<i64>,
    /// Sub-userId of parent user
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub sub_user_id: Option<i64>,
}

impl OneClickArrivalDepositApplyParams {
    /// Create a builder for [`one_click_arrival_deposit_apply`].
    ///
    #[must_use]
    pub fn builder() -> OneClickArrivalDepositApplyParamsBuilder {
        OneClickArrivalDepositApplyParamsBuilder::default()
    }
}
/// Request parameters for the [`withdraw`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`withdraw`](#method.withdraw).
#[derive(Clone, Debug, Builder)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct WithdrawParams {
    ///
    /// The `coin` parameter.
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub coin: String,
    ///
    /// The `address` parameter.
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub address: String,
    ///
    /// The `amount` parameter.
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub amount: rust_decimal::Decimal,
    /// client side id for withdrawal, if provided in POST `/sapi/v1/capital/withdraw/apply`, can be used here for query.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub withdraw_order_id: Option<String>,
    ///
    /// The `network` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub network: Option<String>,
    /// Secondary address identifier for coins like XRP,XMR etc.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub address_tag: Option<String>,
    /// When making internal transfer, `true` for returning the fee to the destination account; `false` for returning the fee back to the departure account. Default `false`.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub transaction_fee_flag: Option<bool>,
    /// Description of the address. Address book cap is 200, space in name should be encoded into `%20`
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub name: Option<String>,
    /// The wallet type for withdraw，0-spot wallet ，1-funding wallet. Default walletType is the current "selected wallet" under wallet->Fiat and Spot/Funding->Deposit
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub wallet_type: Option<i64>,
    ///
    /// The `recv_window` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub recv_window: Option<i64>,
}

impl WithdrawParams {
    /// Create a builder for [`withdraw`].
    ///
    /// Required parameters:
    ///
    /// * `coin` — String
    /// * `address` — String
    /// * `amount` — `rust_decimal::Decimal`
    ///
    #[must_use]
    pub fn builder(
        coin: String,
        address: String,
        amount: rust_decimal::Decimal,
    ) -> WithdrawParamsBuilder {
        WithdrawParamsBuilder::default()
            .coin(coin)
            .address(address)
            .amount(amount)
    }
}
/// Request parameters for the [`withdraw_history`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`withdraw_history`](#method.withdraw_history).
#[derive(Clone, Debug, Builder, Default)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct WithdrawHistoryParams {
    ///
    /// The `coin` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub coin: Option<String>,
    /// client side id for withdrawal, if provided in POST `/sapi/v1/capital/withdraw/apply`, can be used here for query.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub withdraw_order_id: Option<String>,
    /// 0(0:Email Sent, 2:Awaiting Approval 3:Rejected 4:Processing 6:Completed)
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub status: Option<i64>,
    /// Default: 0
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub offset: Option<i64>,
    /// min 7, max 30, default 7
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub limit: Option<i64>,
    /// id list returned in the response of POST `/sapi/v1/capital/withdraw/apply`, separated by `,`
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub id_list: Option<String>,
    ///
    /// 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>,
    ///
    /// The `recv_window` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub recv_window: Option<i64>,
}

impl WithdrawHistoryParams {
    /// Create a builder for [`withdraw_history`].
    ///
    #[must_use]
    pub fn builder() -> WithdrawHistoryParamsBuilder {
        WithdrawHistoryParamsBuilder::default()
    }
}

#[async_trait]
impl CapitalApi for CapitalApiClient {
    async fn all_coins_information(
        &self,
        params: AllCoinsInformationParams,
    ) -> anyhow::Result<RestApiResponse<Vec<models::AllCoinsInformationResponseInner>>> {
        let AllCoinsInformationParams { recv_window } = params;

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

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

        send_request::<Vec<models::AllCoinsInformationResponseInner>>(
            &self.configuration,
            "/sapi/v1/capital/config/getall",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }

    async fn deposit_address(
        &self,
        params: DepositAddressParams,
    ) -> anyhow::Result<RestApiResponse<models::DepositAddressResponse>> {
        let DepositAddressParams {
            coin,
            network,
            amount,
            recv_window,
        } = params;

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

        query_params.insert("coin".to_string(), json!(coin));

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

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

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

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

    async fn deposit_history(
        &self,
        params: DepositHistoryParams,
    ) -> anyhow::Result<RestApiResponse<Vec<models::DepositHistoryResponseInner>>> {
        let DepositHistoryParams {
            include_source,
            coin,
            status,
            start_time,
            end_time,
            offset,
            limit,
            recv_window,
            tx_id,
        } = params;

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

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

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

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

        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) = offset {
            query_params.insert("offset".to_string(), json!(rw));
        }

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

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

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

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

    async fn fetch_deposit_address_list_with_network(
        &self,
        params: FetchDepositAddressListWithNetworkParams,
    ) -> anyhow::Result<RestApiResponse<Vec<models::FetchDepositAddressListWithNetworkResponseInner>>>
    {
        let FetchDepositAddressListWithNetworkParams { coin, network } = params;

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

        query_params.insert("coin".to_string(), json!(coin));

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

        send_request::<Vec<models::FetchDepositAddressListWithNetworkResponseInner>>(
            &self.configuration,
            "/sapi/v1/capital/deposit/address/list",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }

    async fn fetch_withdraw_address_list(
        &self,
    ) -> anyhow::Result<RestApiResponse<Vec<models::FetchWithdrawAddressListResponseInner>>> {
        let query_params = BTreeMap::new();
        let body_params = BTreeMap::new();

        send_request::<Vec<models::FetchWithdrawAddressListResponseInner>>(
            &self.configuration,
            "/sapi/v1/capital/withdraw/address/list",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }

    async fn fetch_withdraw_quota(
        &self,
    ) -> anyhow::Result<RestApiResponse<models::FetchWithdrawQuotaResponse>> {
        let query_params = BTreeMap::new();
        let body_params = BTreeMap::new();

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

    async fn one_click_arrival_deposit_apply(
        &self,
        params: OneClickArrivalDepositApplyParams,
    ) -> anyhow::Result<RestApiResponse<models::OneClickArrivalDepositApplyResponse>> {
        let OneClickArrivalDepositApplyParams {
            deposit_id,
            tx_id,
            sub_account_id,
            sub_user_id,
        } = params;

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

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

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

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

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

        send_request::<models::OneClickArrivalDepositApplyResponse>(
            &self.configuration,
            "/sapi/v1/capital/deposit/credit-apply",
            reqwest::Method::POST,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }

    async fn withdraw(
        &self,
        params: WithdrawParams,
    ) -> anyhow::Result<RestApiResponse<models::WithdrawResponse>> {
        let WithdrawParams {
            coin,
            address,
            amount,
            withdraw_order_id,
            network,
            address_tag,
            transaction_fee_flag,
            name,
            wallet_type,
            recv_window,
        } = params;

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

        query_params.insert("coin".to_string(), json!(coin));

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

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

        query_params.insert("address".to_string(), json!(address));

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

        query_params.insert("amount".to_string(), json!(amount));

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

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

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

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

        send_request::<models::WithdrawResponse>(
            &self.configuration,
            "/sapi/v1/capital/withdraw/apply",
            reqwest::Method::POST,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }

    async fn withdraw_history(
        &self,
        params: WithdrawHistoryParams,
    ) -> anyhow::Result<RestApiResponse<Vec<models::WithdrawHistoryResponseInner>>> {
        let WithdrawHistoryParams {
            coin,
            withdraw_order_id,
            status,
            offset,
            limit,
            id_list,
            start_time,
            end_time,
            recv_window,
        } = params;

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

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

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

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

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

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

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

        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) = recv_window {
            query_params.insert("recvWindow".to_string(), json!(rw));
        }

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

#[cfg(all(test, feature = "wallet"))]
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 MockCapitalApiClient {
        force_error: bool,
    }

    #[async_trait]
    impl CapitalApi for MockCapitalApiClient {
        async fn all_coins_information(
            &self,
            _params: AllCoinsInformationParams,
        ) -> anyhow::Result<RestApiResponse<Vec<models::AllCoinsInformationResponseInner>>>
        {
            if self.force_error {
                return Err(ConnectorError::ConnectorClientError {
                    msg: "ResponseError".to_string(),
                    code: None,
                }
                .into());
            }

            let resp_json: Value = serde_json::from_str(r#"[{"coin":"1MBABYDOGE","depositAllEnable":true,"withdrawAllEnable":true,"name":"1M x BABYDOGE","free":"34941.1","locked":"0","freeze":"0","withdrawing":"0","ipoing":"0","ipoable":"0","storage":"0","isLegalMoney":false,"trading":true,"networkList":[{"network":"BSC","coin":"1MBABYDOGE","withdrawIntegerMultiple":"0.01","isDefault":false,"depositEnable":true,"withdrawEnable":true,"depositDesc":"","withdrawDesc":"","specialTips":"","specialWithdrawTips":"","name":"BNB Smart Chain (BEP20)","resetAddressStatus":false,"addressRegex":"^(0x)[0-9A-Fa-f]{40}$","memoRegex":"","withdrawFee":"10","withdrawMin":"20","withdrawMax":"9999999999","withdrawInternalMin":"0.01","depositDust":"0.01","minConfirm":5,"unLockConfirm":0,"sameAddress":false,"withdrawTag":false,"estimatedArrivalTime":1,"busy":false,"contractAddressUrl":"https://bscscan.com/token/","contractAddress":"0xc748673057861a797275cd8a068abb95a902e8de","denomination":1000000},{"network":"ETH","coin":"1MBABYDOGE","withdrawIntegerMultiple":"0.01","isDefault":true,"depositEnable":true,"withdrawEnable":true,"depositDesc":"","withdrawDesc":"","specialTips":"","specialWithdrawTips":"","name":"Ethereum (ERC20)","resetAddressStatus":false,"addressRegex":"^(0x)[0-9A-Fa-f]{40}$","memoRegex":"","withdrawFee":"1511","withdrawMin":"3022","withdrawMax":"9999999999","withdrawInternalMin":"0.01","depositDust":"0.01","minConfirm":6,"unLockConfirm":64,"sameAddress":false,"withdrawTag":false,"estimatedArrivalTime":2,"busy":false,"contractAddressUrl":"https://etherscan.io/address/","contractAddress":"0xac57de9c1a09fec648e93eb98875b212db0d460b","denomination":1000000}]}]"#).unwrap();
            let dummy_response: Vec<models::AllCoinsInformationResponseInner> =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into Vec<models::AllCoinsInformationResponseInner>");

            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 deposit_address(
            &self,
            _params: DepositAddressParams,
        ) -> anyhow::Result<RestApiResponse<models::DepositAddressResponse>> {
            if self.force_error {
                return Err(ConnectorError::ConnectorClientError {
                    msg: "ResponseError".to_string(),
                    code: None,
                }
                .into());
            }

            let resp_json: Value = serde_json::from_str(r#"{"address":"1HPn8Rx2y6nNSfagQBKy27GB99Vbzg89wv","coin":"BTC","tag":"","url":"https://btc.com/1HPn8Rx2y6nNSfagQBKy27GB99Vbzg89wv"}"#).unwrap();
            let dummy_response: models::DepositAddressResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::DepositAddressResponse");

            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 deposit_history(
            &self,
            _params: DepositHistoryParams,
        ) -> anyhow::Result<RestApiResponse<Vec<models::DepositHistoryResponseInner>>> {
            if self.force_error {
                return Err(ConnectorError::ConnectorClientError {
                    msg: "ResponseError".to_string(),
                    code: None,
                }
                .into());
            }

            let resp_json: Value = serde_json::from_str(r#"[{"id":"769800519366885376","amount":"0.001","coin":"BNB","network":"BNB","status":1,"address":"bnb136ns6lfw4zs5hg4n85vdthaad7hq5m4gtkgf23","addressTag":"101764890","txId":"98A3EA560C6B3336D348B6C83F0F95ECE4F1F5919E94BD006E5BF3BF264FACFC","insertTime":1661493146000,"completeTime":1661493146000,"transferType":0,"confirmTimes":"1/1","unlockConfirm":0,"walletType":0,"travelRuleStatus":0},{"id":"769754833590042625","amount":"0.50000000","coin":"IOTA","network":"IOTA","status":1,"address":"SIZ9VLMHWATXKV99LH99CIGFJFUMLEHGWVZVNNZXRJJVWBPHYWPPBOSDORZ9EQSHCZAMPVAPGFYQAUUV9DROOXJLNW","addressTag":"","txId":"ESBFVQUTPIWQNJSPXFNHNYHSQNTGKRVKPRABQWTAXCDWOAKDKYWPTVG9BGXNVNKTLEJGESAVXIKIZ9999","insertTime":1599620082000,"completeTime":1661493146000,"transferType":0,"confirmTimes":"1/1","unlockConfirm":0,"walletType":0,"travelRuleStatus":1}]"#).unwrap();
            let dummy_response: Vec<models::DepositHistoryResponseInner> =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into Vec<models::DepositHistoryResponseInner>");

            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 fetch_deposit_address_list_with_network(
            &self,
            _params: FetchDepositAddressListWithNetworkParams,
        ) -> anyhow::Result<
            RestApiResponse<Vec<models::FetchDepositAddressListWithNetworkResponseInner>>,
        > {
            if self.force_error {
                return Err(ConnectorError::ConnectorClientError {
                    msg: "ResponseError".to_string(),
                    code: None,
                }
                .into());
            }

            let resp_json: Value = serde_json::from_str(r#"[{"coin":"ETH","address":"0xD316E95Fd9E8E237Cb11f8200Babbc5D8D177BA4","tag":"","isDefault":0},{"coin":"ETH","address":"0xD316E95Fd9E8E237Cb11f8200Babbc5D8D177BA4","tag":"","isDefault":0},{"coin":"ETH","address":"0x00003ada75e7da97ba0db2fcde72131f712455e2","tag":"","isDefault":1}]"#).unwrap();
            let dummy_response : Vec<models::FetchDepositAddressListWithNetworkResponseInner> = serde_json::from_value(resp_json.clone()).expect("should parse into Vec<models::FetchDepositAddressListWithNetworkResponseInner>");

            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 fetch_withdraw_address_list(
            &self,
        ) -> anyhow::Result<RestApiResponse<Vec<models::FetchWithdrawAddressListResponseInner>>>
        {
            if self.force_error {
                return Err(ConnectorError::ConnectorClientError {
                    msg: "ResponseError".to_string(),
                    code: None,
                }
                .into());
            }

            let resp_json: Value = serde_json::from_str(r#"[{"address":"1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa","addressTag":"","coin":"BTC","name":"Satoshi","network":"BTC","origin":"bla","originType":"others","whiteStatus":true}]"#).unwrap();
            let dummy_response: Vec<models::FetchWithdrawAddressListResponseInner> =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into Vec<models::FetchWithdrawAddressListResponseInner>");

            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 fetch_withdraw_quota(
            &self,
        ) -> anyhow::Result<RestApiResponse<models::FetchWithdrawQuotaResponse>> {
            if self.force_error {
                return Err(ConnectorError::ConnectorClientError {
                    msg: "ResponseError".to_string(),
                    code: None,
                }
                .into());
            }

            let resp_json: Value =
                serde_json::from_str(r#"{"wdQuota":"10000","usedWdQuota":"1000"}"#).unwrap();
            let dummy_response: models::FetchWithdrawQuotaResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::FetchWithdrawQuotaResponse");

            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 one_click_arrival_deposit_apply(
            &self,
            _params: OneClickArrivalDepositApplyParams,
        ) -> anyhow::Result<RestApiResponse<models::OneClickArrivalDepositApplyResponse>> {
            if self.force_error {
                return Err(ConnectorError::ConnectorClientError {
                    msg: "ResponseError".to_string(),
                    code: None,
                }
                .into());
            }

            let resp_json: Value = serde_json::from_str(
                r#"{"code":"000000","message":"success","data":true,"success":true}"#,
            )
            .unwrap();
            let dummy_response: models::OneClickArrivalDepositApplyResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::OneClickArrivalDepositApplyResponse");

            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 withdraw(
            &self,
            _params: WithdrawParams,
        ) -> anyhow::Result<RestApiResponse<models::WithdrawResponse>> {
            if self.force_error {
                return Err(ConnectorError::ConnectorClientError {
                    msg: "ResponseError".to_string(),
                    code: None,
                }
                .into());
            }

            let resp_json: Value =
                serde_json::from_str(r#"{"id":"7213fea8e94b4a5593d507237e5a555b"}"#).unwrap();
            let dummy_response: models::WithdrawResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::WithdrawResponse");

            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 withdraw_history(
            &self,
            _params: WithdrawHistoryParams,
        ) -> anyhow::Result<RestApiResponse<Vec<models::WithdrawHistoryResponseInner>>> {
            if self.force_error {
                return Err(ConnectorError::ConnectorClientError {
                    msg: "ResponseError".to_string(),
                    code: None,
                }
                .into());
            }

            let resp_json: Value = serde_json::from_str(r#"[{"id":"b6ae22b3aa844210a7041aee7589627c","amount":"8.91000000","transactionFee":"0.004","coin":"USDT","status":6,"address":"0x94df8b352de7f46f64b01d3666bf6e936e44ce60","txId":"0xb5ef8c13b968a406cc62a93a8bd80f9e9a906ef1b3fcf20a2e48573c17659268","applyTime":"2019-10-12 11:12:02","network":"ETH","transferType":0,"withdrawOrderId":"WITHDRAWtest123","info":"The address is not valid. Please confirm with the recipient","confirmNo":3,"walletType":1,"txKey":"","completeTime":"2023-03-23 16:52:41"},{"id":"156ec387f49b41df8724fa744fa82719","amount":"0.00150000","transactionFee":"0.004","coin":"BTC","status":6,"address":"1FZdVHtiBqMrWdjPyRPULCUceZPJ2WLCsB","txId":"60fd9007ebfddc753455f95fafa808c4302c836e4d1eebc5a132c36c1d8ac354","applyTime":"2019-09-24 12:43:45","network":"BTC","transferType":0,"info":"","confirmNo":2,"walletType":1,"txKey":"","completeTime":"2023-03-23 16:52:41"}]"#).unwrap();
            let dummy_response: Vec<models::WithdrawHistoryResponseInner> =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into Vec<models::WithdrawHistoryResponseInner>");

            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 all_coins_information_required_params_success() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockCapitalApiClient { force_error: false };

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

            let resp_json: Value = serde_json::from_str(r#"[{"coin":"1MBABYDOGE","depositAllEnable":true,"withdrawAllEnable":true,"name":"1M x BABYDOGE","free":"34941.1","locked":"0","freeze":"0","withdrawing":"0","ipoing":"0","ipoable":"0","storage":"0","isLegalMoney":false,"trading":true,"networkList":[{"network":"BSC","coin":"1MBABYDOGE","withdrawIntegerMultiple":"0.01","isDefault":false,"depositEnable":true,"withdrawEnable":true,"depositDesc":"","withdrawDesc":"","specialTips":"","specialWithdrawTips":"","name":"BNB Smart Chain (BEP20)","resetAddressStatus":false,"addressRegex":"^(0x)[0-9A-Fa-f]{40}$","memoRegex":"","withdrawFee":"10","withdrawMin":"20","withdrawMax":"9999999999","withdrawInternalMin":"0.01","depositDust":"0.01","minConfirm":5,"unLockConfirm":0,"sameAddress":false,"withdrawTag":false,"estimatedArrivalTime":1,"busy":false,"contractAddressUrl":"https://bscscan.com/token/","contractAddress":"0xc748673057861a797275cd8a068abb95a902e8de","denomination":1000000},{"network":"ETH","coin":"1MBABYDOGE","withdrawIntegerMultiple":"0.01","isDefault":true,"depositEnable":true,"withdrawEnable":true,"depositDesc":"","withdrawDesc":"","specialTips":"","specialWithdrawTips":"","name":"Ethereum (ERC20)","resetAddressStatus":false,"addressRegex":"^(0x)[0-9A-Fa-f]{40}$","memoRegex":"","withdrawFee":"1511","withdrawMin":"3022","withdrawMax":"9999999999","withdrawInternalMin":"0.01","depositDust":"0.01","minConfirm":6,"unLockConfirm":64,"sameAddress":false,"withdrawTag":false,"estimatedArrivalTime":2,"busy":false,"contractAddressUrl":"https://etherscan.io/address/","contractAddress":"0xac57de9c1a09fec648e93eb98875b212db0d460b","denomination":1000000}]}]"#).unwrap();
            let expected_response : Vec<models::AllCoinsInformationResponseInner> = serde_json::from_value(resp_json.clone()).expect("should parse into Vec<models::AllCoinsInformationResponseInner>");

            let resp = client.all_coins_information(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 all_coins_information_optional_params_success() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockCapitalApiClient { force_error: false };

            let params = AllCoinsInformationParams::builder().recv_window(5000).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"[{"coin":"1MBABYDOGE","depositAllEnable":true,"withdrawAllEnable":true,"name":"1M x BABYDOGE","free":"34941.1","locked":"0","freeze":"0","withdrawing":"0","ipoing":"0","ipoable":"0","storage":"0","isLegalMoney":false,"trading":true,"networkList":[{"network":"BSC","coin":"1MBABYDOGE","withdrawIntegerMultiple":"0.01","isDefault":false,"depositEnable":true,"withdrawEnable":true,"depositDesc":"","withdrawDesc":"","specialTips":"","specialWithdrawTips":"","name":"BNB Smart Chain (BEP20)","resetAddressStatus":false,"addressRegex":"^(0x)[0-9A-Fa-f]{40}$","memoRegex":"","withdrawFee":"10","withdrawMin":"20","withdrawMax":"9999999999","withdrawInternalMin":"0.01","depositDust":"0.01","minConfirm":5,"unLockConfirm":0,"sameAddress":false,"withdrawTag":false,"estimatedArrivalTime":1,"busy":false,"contractAddressUrl":"https://bscscan.com/token/","contractAddress":"0xc748673057861a797275cd8a068abb95a902e8de","denomination":1000000},{"network":"ETH","coin":"1MBABYDOGE","withdrawIntegerMultiple":"0.01","isDefault":true,"depositEnable":true,"withdrawEnable":true,"depositDesc":"","withdrawDesc":"","specialTips":"","specialWithdrawTips":"","name":"Ethereum (ERC20)","resetAddressStatus":false,"addressRegex":"^(0x)[0-9A-Fa-f]{40}$","memoRegex":"","withdrawFee":"1511","withdrawMin":"3022","withdrawMax":"9999999999","withdrawInternalMin":"0.01","depositDust":"0.01","minConfirm":6,"unLockConfirm":64,"sameAddress":false,"withdrawTag":false,"estimatedArrivalTime":2,"busy":false,"contractAddressUrl":"https://etherscan.io/address/","contractAddress":"0xac57de9c1a09fec648e93eb98875b212db0d460b","denomination":1000000}]}]"#).unwrap();
            let expected_response : Vec<models::AllCoinsInformationResponseInner> = serde_json::from_value(resp_json.clone()).expect("should parse into Vec<models::AllCoinsInformationResponseInner>");

            let resp = client.all_coins_information(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 all_coins_information_response_error() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockCapitalApiClient { force_error: true };

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

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

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

            let params = DepositAddressParams::builder("coin_example".to_string(),).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"address":"1HPn8Rx2y6nNSfagQBKy27GB99Vbzg89wv","coin":"BTC","tag":"","url":"https://btc.com/1HPn8Rx2y6nNSfagQBKy27GB99Vbzg89wv"}"#).unwrap();
            let expected_response : models::DepositAddressResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::DepositAddressResponse");

            let resp = client.deposit_address(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 deposit_address_optional_params_success() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockCapitalApiClient { force_error: false };

            let params = DepositAddressParams::builder("coin_example".to_string(),).network("network_example".to_string()).amount(dec!(1.0)).recv_window(5000).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"address":"1HPn8Rx2y6nNSfagQBKy27GB99Vbzg89wv","coin":"BTC","tag":"","url":"https://btc.com/1HPn8Rx2y6nNSfagQBKy27GB99Vbzg89wv"}"#).unwrap();
            let expected_response : models::DepositAddressResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::DepositAddressResponse");

            let resp = client.deposit_address(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 deposit_address_response_error() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockCapitalApiClient { force_error: true };

            let params = DepositAddressParams::builder("coin_example".to_string())
                .build()
                .unwrap();

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

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

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

            let resp_json: Value = serde_json::from_str(r#"[{"id":"769800519366885376","amount":"0.001","coin":"BNB","network":"BNB","status":1,"address":"bnb136ns6lfw4zs5hg4n85vdthaad7hq5m4gtkgf23","addressTag":"101764890","txId":"98A3EA560C6B3336D348B6C83F0F95ECE4F1F5919E94BD006E5BF3BF264FACFC","insertTime":1661493146000,"completeTime":1661493146000,"transferType":0,"confirmTimes":"1/1","unlockConfirm":0,"walletType":0,"travelRuleStatus":0},{"id":"769754833590042625","amount":"0.50000000","coin":"IOTA","network":"IOTA","status":1,"address":"SIZ9VLMHWATXKV99LH99CIGFJFUMLEHGWVZVNNZXRJJVWBPHYWPPBOSDORZ9EQSHCZAMPVAPGFYQAUUV9DROOXJLNW","addressTag":"","txId":"ESBFVQUTPIWQNJSPXFNHNYHSQNTGKRVKPRABQWTAXCDWOAKDKYWPTVG9BGXNVNKTLEJGESAVXIKIZ9999","insertTime":1599620082000,"completeTime":1661493146000,"transferType":0,"confirmTimes":"1/1","unlockConfirm":0,"walletType":0,"travelRuleStatus":1}]"#).unwrap();
            let expected_response : Vec<models::DepositHistoryResponseInner> = serde_json::from_value(resp_json.clone()).expect("should parse into Vec<models::DepositHistoryResponseInner>");

            let resp = client.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 deposit_history_optional_params_success() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockCapitalApiClient { force_error: false };

            let params = DepositHistoryParams::builder().include_source(false).coin("coin_example".to_string()).status(789).start_time(1623319461670).end_time(1641782889000).offset(0).limit(7).recv_window(5000).tx_id("1".to_string()).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"[{"id":"769800519366885376","amount":"0.001","coin":"BNB","network":"BNB","status":1,"address":"bnb136ns6lfw4zs5hg4n85vdthaad7hq5m4gtkgf23","addressTag":"101764890","txId":"98A3EA560C6B3336D348B6C83F0F95ECE4F1F5919E94BD006E5BF3BF264FACFC","insertTime":1661493146000,"completeTime":1661493146000,"transferType":0,"confirmTimes":"1/1","unlockConfirm":0,"walletType":0,"travelRuleStatus":0},{"id":"769754833590042625","amount":"0.50000000","coin":"IOTA","network":"IOTA","status":1,"address":"SIZ9VLMHWATXKV99LH99CIGFJFUMLEHGWVZVNNZXRJJVWBPHYWPPBOSDORZ9EQSHCZAMPVAPGFYQAUUV9DROOXJLNW","addressTag":"","txId":"ESBFVQUTPIWQNJSPXFNHNYHSQNTGKRVKPRABQWTAXCDWOAKDKYWPTVG9BGXNVNKTLEJGESAVXIKIZ9999","insertTime":1599620082000,"completeTime":1661493146000,"transferType":0,"confirmTimes":"1/1","unlockConfirm":0,"walletType":0,"travelRuleStatus":1}]"#).unwrap();
            let expected_response : Vec<models::DepositHistoryResponseInner> = serde_json::from_value(resp_json.clone()).expect("should parse into Vec<models::DepositHistoryResponseInner>");

            let resp = client.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 deposit_history_response_error() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockCapitalApiClient { force_error: true };

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

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

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

            let params = FetchDepositAddressListWithNetworkParams::builder("coin_example".to_string(),).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"[{"coin":"ETH","address":"0xD316E95Fd9E8E237Cb11f8200Babbc5D8D177BA4","tag":"","isDefault":0},{"coin":"ETH","address":"0xD316E95Fd9E8E237Cb11f8200Babbc5D8D177BA4","tag":"","isDefault":0},{"coin":"ETH","address":"0x00003ada75e7da97ba0db2fcde72131f712455e2","tag":"","isDefault":1}]"#).unwrap();
            let expected_response : Vec<models::FetchDepositAddressListWithNetworkResponseInner> = serde_json::from_value(resp_json.clone()).expect("should parse into Vec<models::FetchDepositAddressListWithNetworkResponseInner>");

            let resp = client.fetch_deposit_address_list_with_network(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 fetch_deposit_address_list_with_network_optional_params_success() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockCapitalApiClient { force_error: false };

            let params = FetchDepositAddressListWithNetworkParams::builder("coin_example".to_string(),).network("network_example".to_string()).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"[{"coin":"ETH","address":"0xD316E95Fd9E8E237Cb11f8200Babbc5D8D177BA4","tag":"","isDefault":0},{"coin":"ETH","address":"0xD316E95Fd9E8E237Cb11f8200Babbc5D8D177BA4","tag":"","isDefault":0},{"coin":"ETH","address":"0x00003ada75e7da97ba0db2fcde72131f712455e2","tag":"","isDefault":1}]"#).unwrap();
            let expected_response : Vec<models::FetchDepositAddressListWithNetworkResponseInner> = serde_json::from_value(resp_json.clone()).expect("should parse into Vec<models::FetchDepositAddressListWithNetworkResponseInner>");

            let resp = client.fetch_deposit_address_list_with_network(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 fetch_deposit_address_list_with_network_response_error() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockCapitalApiClient { force_error: true };

            let params =
                FetchDepositAddressListWithNetworkParams::builder("coin_example".to_string())
                    .build()
                    .unwrap();

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

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


            let resp_json: Value = serde_json::from_str(r#"[{"address":"1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa","addressTag":"","coin":"BTC","name":"Satoshi","network":"BTC","origin":"bla","originType":"others","whiteStatus":true}]"#).unwrap();
            let expected_response : Vec<models::FetchWithdrawAddressListResponseInner> = serde_json::from_value(resp_json.clone()).expect("should parse into Vec<models::FetchWithdrawAddressListResponseInner>");

            let resp = client.fetch_withdraw_address_list().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 fetch_withdraw_address_list_optional_params_success() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockCapitalApiClient { force_error: false };


            let resp_json: Value = serde_json::from_str(r#"[{"address":"1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa","addressTag":"","coin":"BTC","name":"Satoshi","network":"BTC","origin":"bla","originType":"others","whiteStatus":true}]"#).unwrap();
            let expected_response : Vec<models::FetchWithdrawAddressListResponseInner> = serde_json::from_value(resp_json.clone()).expect("should parse into Vec<models::FetchWithdrawAddressListResponseInner>");

            let resp = client.fetch_withdraw_address_list().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 fetch_withdraw_address_list_response_error() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockCapitalApiClient { force_error: true };

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

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

            let resp_json: Value =
                serde_json::from_str(r#"{"wdQuota":"10000","usedWdQuota":"1000"}"#).unwrap();
            let expected_response: models::FetchWithdrawQuotaResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::FetchWithdrawQuotaResponse");

            let resp = client
                .fetch_withdraw_quota()
                .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 fetch_withdraw_quota_optional_params_success() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockCapitalApiClient { force_error: false };

            let resp_json: Value =
                serde_json::from_str(r#"{"wdQuota":"10000","usedWdQuota":"1000"}"#).unwrap();
            let expected_response: models::FetchWithdrawQuotaResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::FetchWithdrawQuotaResponse");

            let resp = client
                .fetch_withdraw_quota()
                .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 fetch_withdraw_quota_response_error() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockCapitalApiClient { force_error: true };

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

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

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

            let resp_json: Value = serde_json::from_str(
                r#"{"code":"000000","message":"success","data":true,"success":true}"#,
            )
            .unwrap();
            let expected_response: models::OneClickArrivalDepositApplyResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::OneClickArrivalDepositApplyResponse");

            let resp = client
                .one_click_arrival_deposit_apply(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 one_click_arrival_deposit_apply_optional_params_success() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockCapitalApiClient { force_error: false };

            let params = OneClickArrivalDepositApplyParams::builder()
                .deposit_id(1)
                .tx_id("1".to_string())
                .sub_account_id(1)
                .sub_user_id(1)
                .build()
                .unwrap();

            let resp_json: Value = serde_json::from_str(
                r#"{"code":"000000","message":"success","data":true,"success":true}"#,
            )
            .unwrap();
            let expected_response: models::OneClickArrivalDepositApplyResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::OneClickArrivalDepositApplyResponse");

            let resp = client
                .one_click_arrival_deposit_apply(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 one_click_arrival_deposit_apply_response_error() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockCapitalApiClient { force_error: true };

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

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

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

            let params = WithdrawParams::builder(
                "coin_example".to_string(),
                "address_example".to_string(),
                dec!(1.0),
            )
            .build()
            .unwrap();

            let resp_json: Value =
                serde_json::from_str(r#"{"id":"7213fea8e94b4a5593d507237e5a555b"}"#).unwrap();
            let expected_response: models::WithdrawResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::WithdrawResponse");

            let resp = client.withdraw(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 withdraw_optional_params_success() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockCapitalApiClient { force_error: false };

            let params = WithdrawParams::builder(
                "coin_example".to_string(),
                "address_example".to_string(),
                dec!(1.0),
            )
            .withdraw_order_id("1".to_string())
            .network("network_example".to_string())
            .address_tag("address_tag_example".to_string())
            .transaction_fee_flag(false)
            .name("name_example".to_string())
            .wallet_type(0)
            .recv_window(5000)
            .build()
            .unwrap();

            let resp_json: Value =
                serde_json::from_str(r#"{"id":"7213fea8e94b4a5593d507237e5a555b"}"#).unwrap();
            let expected_response: models::WithdrawResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::WithdrawResponse");

            let resp = client.withdraw(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 withdraw_response_error() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockCapitalApiClient { force_error: true };

            let params = WithdrawParams::builder(
                "coin_example".to_string(),
                "address_example".to_string(),
                dec!(1.0),
            )
            .build()
            .unwrap();

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

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

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

            let resp_json: Value = serde_json::from_str(r#"[{"id":"b6ae22b3aa844210a7041aee7589627c","amount":"8.91000000","transactionFee":"0.004","coin":"USDT","status":6,"address":"0x94df8b352de7f46f64b01d3666bf6e936e44ce60","txId":"0xb5ef8c13b968a406cc62a93a8bd80f9e9a906ef1b3fcf20a2e48573c17659268","applyTime":"2019-10-12 11:12:02","network":"ETH","transferType":0,"withdrawOrderId":"WITHDRAWtest123","info":"The address is not valid. Please confirm with the recipient","confirmNo":3,"walletType":1,"txKey":"","completeTime":"2023-03-23 16:52:41"},{"id":"156ec387f49b41df8724fa744fa82719","amount":"0.00150000","transactionFee":"0.004","coin":"BTC","status":6,"address":"1FZdVHtiBqMrWdjPyRPULCUceZPJ2WLCsB","txId":"60fd9007ebfddc753455f95fafa808c4302c836e4d1eebc5a132c36c1d8ac354","applyTime":"2019-09-24 12:43:45","network":"BTC","transferType":0,"info":"","confirmNo":2,"walletType":1,"txKey":"","completeTime":"2023-03-23 16:52:41"}]"#).unwrap();
            let expected_response : Vec<models::WithdrawHistoryResponseInner> = serde_json::from_value(resp_json.clone()).expect("should parse into Vec<models::WithdrawHistoryResponseInner>");

            let resp = client.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 withdraw_history_optional_params_success() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockCapitalApiClient { force_error: false };

            let params = WithdrawHistoryParams::builder().coin("coin_example".to_string()).withdraw_order_id("1".to_string()).status(789).offset(0).limit(7).id_list("id_list_example".to_string()).start_time(1623319461670).end_time(1641782889000).recv_window(5000).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"[{"id":"b6ae22b3aa844210a7041aee7589627c","amount":"8.91000000","transactionFee":"0.004","coin":"USDT","status":6,"address":"0x94df8b352de7f46f64b01d3666bf6e936e44ce60","txId":"0xb5ef8c13b968a406cc62a93a8bd80f9e9a906ef1b3fcf20a2e48573c17659268","applyTime":"2019-10-12 11:12:02","network":"ETH","transferType":0,"withdrawOrderId":"WITHDRAWtest123","info":"The address is not valid. Please confirm with the recipient","confirmNo":3,"walletType":1,"txKey":"","completeTime":"2023-03-23 16:52:41"},{"id":"156ec387f49b41df8724fa744fa82719","amount":"0.00150000","transactionFee":"0.004","coin":"BTC","status":6,"address":"1FZdVHtiBqMrWdjPyRPULCUceZPJ2WLCsB","txId":"60fd9007ebfddc753455f95fafa808c4302c836e4d1eebc5a132c36c1d8ac354","applyTime":"2019-09-24 12:43:45","network":"BTC","transferType":0,"info":"","confirmNo":2,"walletType":1,"txKey":"","completeTime":"2023-03-23 16:52:41"}]"#).unwrap();
            let expected_response : Vec<models::WithdrawHistoryResponseInner> = serde_json::from_value(resp_json.clone()).expect("should parse into Vec<models::WithdrawHistoryResponseInner>");

            let resp = client.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 withdraw_history_response_error() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockCapitalApiClient { force_error: true };

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

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