use std::collections::HashMap;
use crate::core::{Credentials, ExchangeResult};
#[derive(Clone)]
pub struct DydxAuth {
_credentials: Option<Credentials>,
}
impl DydxAuth {
pub fn new(credentials: Option<&Credentials>) -> ExchangeResult<Self> {
Ok(Self {
_credentials: credentials.cloned(),
})
}
pub fn public() -> Self {
Self {
_credentials: None,
}
}
pub fn sign_request(
&self,
_method: &str,
_endpoint: &str,
_body: &str,
) -> HashMap<String, String> {
let mut headers = HashMap::new();
headers.insert("Content-Type".to_string(), "application/json".to_string());
headers
}
pub fn has_credentials(&self) -> bool {
self._credentials.is_some()
}
pub fn address(&self) -> Option<&str> {
self._credentials.as_ref().map(|c| c.api_key.as_str())
.filter(|s| !s.is_empty())
}
#[cfg(feature = "onchain-cosmos")]
pub fn trading_credentials(&self) -> Option<(String, String)> {
let creds = self._credentials.as_ref()?;
let key_hex = creds.api_key.as_str();
let address = creds.api_secret.as_str();
if key_hex.is_empty() || address.is_empty() {
return None;
}
Some((key_hex.to_string(), address.to_string()))
}
}
impl Default for DydxAuth {
fn default() -> Self {
Self::public()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_public_auth() {
let auth = DydxAuth::public();
assert!(!auth.has_credentials());
let headers = auth.sign_request("GET", "/v4/perpetualMarkets", "");
assert!(headers.contains_key("Content-Type"));
assert_eq!(headers.get("Content-Type"), Some(&"application/json".to_string()));
}
#[test]
fn test_auth_with_credentials() {
let credentials = Credentials::new("dummy_key", "dummy_secret");
let auth = DydxAuth::new(Some(&credentials)).unwrap();
assert!(auth.has_credentials());
let headers = auth.sign_request("GET", "/v4/perpetualMarkets", "");
assert_eq!(headers.len(), 1); }
#[test]
fn test_auth_new_none() {
let auth = DydxAuth::new(None).unwrap();
assert!(!auth.has_credentials());
}
}