Skip to content
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ bothan-coinmarketcap = { path = "bothan-coinmarketcap", version = "0.0.1" }
bothan-htx = { path = "bothan-htx", version = "0.0.1" }
bothan-kraken = { path = "bothan-kraken", version = "0.0.1" }
bothan-okx = { path = "bothan-okx", version = "0.0.1" }
bothan-band = { path = "bothan-band", version = "0.0.1" }

anyhow = "1.0.86"
async-trait = "0.1.77"
Expand Down
2 changes: 1 addition & 1 deletion bothan-api/server-cli/src/commands/key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ fn export_key(config: &AppConfig) -> anyhow::Result<()> {
read(&config.monitoring.path).with_context(|| "Failed to read monitoring key file")?;
let pk = String::from_utf8(pkb).with_context(|| "Failed to parse monitoring key file")?;
println!("Private Key");
println!("{}", pk);
println!("{pk}");
Ok(())
}

Expand Down
6 changes: 3 additions & 3 deletions bothan-api/server-cli/src/commands/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ impl RequestCli {
let client = match GrpcClient::connect(&uri).await {
Ok(client) => client,
Err(e) => {
eprintln!("Failed to connect to server: {:#?}", e);
eprintln!("Failed to connect to server: {e:#?}");
std::process::exit(1);
}
};
Expand All @@ -71,7 +71,7 @@ impl RequestCli {
.get_info()
.await
.with_context(|| "Failed to get info")?;
println!("{:#?}", info);
println!("{info:#?}");
}
RequestSubCommand::UpdateRegistry { ipfs_hash, version } => {
client
Expand All @@ -98,7 +98,7 @@ impl RequestCli {
.get_prices(&ids)
.await
.with_context(|| "Failed to get prices")?;
println!("{:#?}", prices);
println!("{prices:#?}");
}
}
Ok(())
Expand Down
2 changes: 2 additions & 0 deletions bothan-api/server-cli/src/commands/start.rs
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,8 @@ async fn init_crypto_opts(
add_worker_opts(&mut worker_opts, &source.htx).await?;
add_worker_opts(&mut worker_opts, &source.kraken).await?;
add_worker_opts(&mut worker_opts, &source.okx).await?;
add_worker_opts(&mut worker_opts, &source.band1).await?;
add_worker_opts(&mut worker_opts, &source.band2).await?;

Ok(worker_opts)
}
Expand Down
2 changes: 1 addition & 1 deletion bothan-api/server-cli/src/helper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ impl<T> Exitable<T> for anyhow::Result<T> {
match self {
Ok(t) => t,
Err(e) => {
eprintln!("{:?}", e);
eprintln!("{e:?}");
std::process::exit(code);
}
}
Expand Down
7 changes: 5 additions & 2 deletions bothan-api/server-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ use std::str::FromStr;

use bothan_api::config::AppConfig;
use bothan_api::config::log::LogLevel;
use bothan_api::config::manager::crypto_info::sources::CryptoSourceConfigs;
use clap::{Parser, Subcommand};
use tracing_subscriber::EnvFilter;
use tracing_subscriber::filter::Directive;
Expand Down Expand Up @@ -86,7 +87,7 @@ async fn main() {
let cli = match Cli::try_parse() {
Ok(cli) => cli,
Err(e) => {
eprintln!("{}", e);
eprintln!("{e}");
std::process::exit(1);
}
};
Expand All @@ -98,7 +99,9 @@ async fn main() {
"Failed to load config. Try deleting the config file and running 'config init'.",
)
} else {
AppConfig::default()
let mut config = AppConfig::default();
config.manager.crypto.source = CryptoSourceConfigs::with_default_sources();
config
};

let log_lvl = &app_config.log.log_level;
Expand Down
1 change: 1 addition & 0 deletions bothan-api/server/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ bothan-coinmarketcap = { workspace = true }
bothan-htx = { workspace = true }
bothan-kraken = { workspace = true }
bothan-okx = { workspace = true }
bothan-band = { workspace = true }

async-trait = { workspace = true }
chrono = { workspace = true }
Expand Down
4 changes: 3 additions & 1 deletion bothan-api/server/src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,11 @@
//! ```rust,no_run
//! use bothan_api::api::BothanServer;
//! use bothan_api::config::AppConfig;
//! use bothan_api::config::manager::crypto_info::sources::CryptoSourceConfigs;
//!
//! fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let config = AppConfig::default();
//! let mut config = AppConfig::default();
//! config.manager.crypto.source = CryptoSourceConfigs::with_default_sources();
//! // Initialize server with config
//! Ok(())
//! }
Expand Down
2 changes: 1 addition & 1 deletion bothan-api/server/src/config/log.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ impl Display for LogLevel {
LogLevel::Warn => "warn".to_string(),
LogLevel::Error => "error".to_string(),
};
write!(f, "{}", str)
write!(f, "{str}")
}
}

Expand Down
61 changes: 60 additions & 1 deletion bothan-api/server/src/config/manager/crypto_info/sources.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
use serde::{Deserialize, Serialize};

/// Configuration for the worker sources for crypto asset info.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[derive(Clone, Debug, Default, Serialize)]
pub struct CryptoSourceConfigs {
/// Binance worker options.
pub binance: Option<bothan_binance::WorkerOpts>,
Expand All @@ -32,6 +32,57 @@ pub struct CryptoSourceConfigs {
pub kraken: Option<bothan_kraken::WorkerOpts>,
/// OKX worker options.
pub okx: Option<bothan_okx::WorkerOpts>,
/// Band1 worker options.
pub band1: Option<bothan_band::WorkerOpts>,
/// Band2 worker options.
pub band2: Option<bothan_band::WorkerOpts>,
}

impl<'de> Deserialize<'de> for CryptoSourceConfigs {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
#[derive(Deserialize)]
struct Helper {
binance: Option<bothan_binance::WorkerOpts>,
bitfinex: Option<bothan_bitfinex::WorkerOpts>,
bybit: Option<bothan_bybit::WorkerOpts>,
coinbase: Option<bothan_coinbase::WorkerOpts>,
coingecko: Option<bothan_coingecko::WorkerOpts>,
coinmarketcap: Option<bothan_coinmarketcap::WorkerOpts>,
htx: Option<bothan_htx::WorkerOpts>,
kraken: Option<bothan_kraken::WorkerOpts>,
okx: Option<bothan_okx::WorkerOpts>,
band1: Option<bothan_band::WorkerOpts>,
band2: Option<bothan_band::WorkerOpts>,
}

let mut helper = Helper::deserialize(deserializer)?;

// Custom logic to modify `band1` during deserialization
if let Some(ref mut band1) = helper.band1 {
band1.name = Some("band1".to_string());
}
// Custom logic to modify `band2` during deserialization
if let Some(ref mut band2) = helper.band2 {
band2.name = Some("band2".to_string());
}

Ok(CryptoSourceConfigs {
binance: helper.binance,
bitfinex: helper.bitfinex,
bybit: helper.bybit,
coinbase: helper.coinbase,
coingecko: helper.coingecko,
coinmarketcap: helper.coinmarketcap,
htx: helper.htx,
kraken: helper.kraken,
okx: helper.okx,
band1: helper.band1,
band2: helper.band2,
})
}
}

impl CryptoSourceConfigs {
Expand All @@ -47,6 +98,14 @@ impl CryptoSourceConfigs {
htx: Some(bothan_htx::WorkerOpts::default()),
kraken: Some(bothan_kraken::WorkerOpts::default()),
okx: Some(bothan_okx::WorkerOpts::default()),
band1: Some(bothan_band::WorkerOpts::new(
"band1",
"https://bandsource1.bandchain.org",
)),
band2: Some(bothan_band::WorkerOpts::new(
"band2",
"https://bandsource1.bandchain.org",
)),
}
}
}
31 changes: 31 additions & 0 deletions bothan-band/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
[package]
name = "bothan-band"
version = "0.0.1"
description = "Rust client for the Band source with Bothan integration"
edition.workspace = true
license.workspace = true
repository.workspace = true

[dependencies]
bothan-lib = { workspace = true }

async-trait = { workspace = true }
chrono = { workspace = true }
humantime-serde = { workspace = true }
itertools = { workspace = true }
reqwest = { workspace = true }
rust_decimal = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
tokio = { workspace = true }
tokio-util = { workspace = true }
tracing = { workspace = true }
url = { workspace = true }

[dev-dependencies]
mockito = { workspace = true }


[package.metadata.cargo-machete]
ignored = ["humantime-serde"]
26 changes: 26 additions & 0 deletions bothan-band/src/api.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
//! Band REST API client implementation.
//!
//! This module provides types and utilities for interacting with the Band REST API,
//! including configuration, request execution, error handling, and response deserialization.
//!
//! The module provides:
//!
//! - [`builder`] — A builder pattern for creating [`RestApi`] clients with optional parameters like base URL and API key.
//! - [`rest`] — Core API client implementation, including HTTP request logic and integration with Bothan's `AssetInfoProvider` trait.
//! - [`types`] — Data types that represent Band REST API responses such as [`Price`](types::Price)
//! - [`error`] — Custom error types used during API client configuration and request processing.
//!
//! # Integration with Workers
//!
//! This module is intended to be used by worker implementations (such as [`Worker`](`crate::worker::Worker`))
//! that periodically query Band for asset data. The [`RestApi`] implements the
//! [`AssetInfoProvider`](bothan_lib::worker::rest::AssetInfoProvider) trait, which allows
//! Band responses to be translated into Bothan-compatible asset updates.

pub use builder::RestApiBuilder;
pub use rest::RestApi;

pub mod builder;
pub mod error;
pub mod rest;
pub mod types;
88 changes: 88 additions & 0 deletions bothan-band/src/api/builder.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
//! Builder for configuring and constructing `BandAPI`.
//!
//! This module provides a builder for constructing [`RestApi`] clients used
//! to interact with the Band REST API. The builder supports optional configuration
//! of base URL.
//!
//! The module provides:
//!
//! - The [`RestApiBuilder`] for REST API building
//! - Supports setting the API base URL
//! - Automatically uses the default Band URL when parameters are omitted during the [`build`](`RestApiBuilder::build`) call

use reqwest::ClientBuilder;
use reqwest::header::HeaderMap;
use url::Url;

use crate::api::RestApi;
use crate::api::error::BuildError;

/// Builder for creating instances of [`RestApi`].
///
/// The `RestApiBuilder` provides a builder pattern for setting up a [`RestApi`] instance
/// by allowing users to specify optional configuration parameters such as the base URL.
///
/// # Example
/// ```
/// use bothan_band::api::RestApiBuilder;
///
/// #[tokio::main]
/// async fn main() {
/// let api = RestApiBuilder::new("https://bandsource-url.com")
/// .build()
/// .unwrap();
/// }
/// ```
pub struct RestApiBuilder {
/// Base URL of the Band REST API.
url: String,
}

impl RestApiBuilder {
/// Creates a new `RestApiBuilder` with the specified configuration.
///
/// This method allows manual initialization of the builder using
/// a required URL string.
///
/// # Examples
///
/// ```
/// use bothan_band::api::RestApiBuilder;
///
/// let builder = RestApiBuilder::new(
/// "https://bandsource-url.com",
/// );
/// ```
pub fn new<T>(url: T) -> Self
where
T: Into<String>,
{
RestApiBuilder { url: url.into() }
}

/// Sets the URL for the Band API.
/// The default URL is `DEFAULT_URL`.
pub fn with_url(mut self, url: &str) -> Self {
self.url = url.into();
self
}

/// Builds the [`RestApi`] instance.
///
/// This method consumes the builder and attempts to create a fully configured client.
///
/// # Errors
///
/// Returns a [`BuildError`] if:
/// - The URL is invalid
/// - The HTTP client fails to build
pub fn build(self) -> Result<RestApi, BuildError> {
let headers = HeaderMap::new();

let parsed_url = Url::parse(&self.url)?;

let client = ClientBuilder::new().default_headers(headers).build()?;

Ok(RestApi::new(parsed_url, client))
}
}
Loading