exchange_interactions_adapters 0.19.2

Implementations of HTTP/HTTPS/WebSocket API methods for some crypto exchanges, using [crypto-botters](<https://github.com/negi-grass/crypto-botters>) framework
Documentation
use std::fmt::Debug;

use exchange_interactions_api_generics::{http, ws};

/// A `trait` that shows the implementing type is an enpoint url. Meant to be implemented on enums with all currently accessible urls for exchange defined.
pub trait EndpointUrl {
	fn url_mainnet(&self) -> url::Url;
	/// Returns the testnet url for the exchange. Not that not all exchanges have testnets for all endpoints.
	fn url_testnet(&self) -> Option<url::Url>;
}

/// shows that the implementing type is able to create [websocket::WebSocketHandler]s
pub trait WsOption: HandlerOption {
	type WsHandler: ws::WsHandler;

	fn ws_handler(options: Self::Options) -> Self::WsHandler;
}

/// A `trait` that shows the implementing type is able to create [http::RequestHandler]s
pub trait HttpOption<'a, R, B>: HandlerOption {
	type RequestHandler: http::RequestHandler<B>;

	fn request_handler(options: Self::Options) -> Self::RequestHandler;
}

/// Set of [HandlerOption] s
pub trait HandlerOptions: Default + Clone + Debug {
	/// The element of this set
	type OptionItem: HandlerOption<Options = Self>;

	//Q: searched through impls, only differing options are HttpAuth and RecvWindow, (on unimportant exchanges at that), rest seem to have exact same types and uses. So maybe I could describe OptionItem procedurally + have part of the implementation for free? Really only problem would be the differing types and the websocket_url/http_url, which are effectively enums of `&'static str`
	fn update(&mut self, option: Self::OptionItem);
	fn is_authenticated(&self) -> bool;
}

/// A `trait` that represents an option which can be set when creating handlers
pub trait HandlerOption: Default {
	type Options: HandlerOptions<OptionItem = Self>;
}
/// Response path for venues that ship no typed error envelope: parse on success, otherwise report
/// whatever came back. `venue` only names the exchange in the message.
#[cfg(any(feature = "bitflyer", feature = "coincheck"))]
pub(crate) fn handle_untyped_response<T: serde::de::DeserializeOwned>(venue: &str, status: http::StatusCode, body: &http::Bytes) -> Result<T, http::HandleError> {
	let truncated = || v_utils::utils::truncate_msg(String::from_utf8_lossy(body));
	if status.is_success() {
		return serde_json::from_slice(body).map_err(|error| http::HandleError::Parse(eyre::eyre!("Failed to parse response: {error}\nResponse body: {}", truncated())));
	}
	Err(match serde_json::from_slice::<serde_json::Value>(body) {
		Ok(parsed) => http::HandleError::Api(http::ApiError::Other(eyre::eyre!("{venue} API error (status {status}): {parsed}"))),
		Err(error) => http::HandleError::Parse(eyre::eyre!("Failed to parse error response: {error}\nResponse body: {}", truncated())),
	})
}

/// Writes an [EndpointUrl] impl from a flat variant→literal table. Omitting `testnet:` means the
/// venue exposes no testnet for that variant, so the two `match`es cannot drift out of sync.
///
/// Exported rather than `pub(crate) use`d only because the formatter hoists every `use` above the
/// `macro_rules!` it would name; call it as `crate::endpoint_urls!`.
#[doc(hidden)]
#[macro_export]
macro_rules! endpoint_urls {
	($ty:ty { $($variant:ident => $mainnet:literal $(, testnet: $testnet:literal)? ;)+ }) => {
		impl $crate::traits::EndpointUrl for $ty {
			fn url_mainnet(&self) -> url::Url {
				match self {
					$(Self::$variant => url::Url::parse($mainnet).expect("literal"),)+
				}
			}

			fn url_testnet(&self) -> Option<url::Url> {
				match self {
					$(Self::$variant => $crate::endpoint_urls!(@testnet $($testnet)?),)+
				}
			}
		}
	};
	(@testnet $testnet:literal) => { Some(url::Url::parse($testnet).expect("literal")) };
	(@testnet) => { None };
}