From deb0c8edd336b50eb3b2cd5e25ae1081f3651bcb Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Tue, 14 Nov 2023 11:21:37 +0700 Subject: [PATCH 01/46] add folder --- Cargo.lock | 4 ++++ Cargo.toml | 2 +- price-adapter/Cargo.toml | 4 ++++ price-adapter/src/lib.rs | 1 + 4 files changed, 10 insertions(+), 1 deletion(-) create mode 100644 price-adapter/Cargo.toml create mode 100644 price-adapter/src/lib.rs diff --git a/Cargo.lock b/Cargo.lock index 6cae992b..9ef7e8a9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -725,6 +725,10 @@ version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de" +[[package]] +name = "price-adapter" +version = "0.1.0" + [[package]] name = "price-adapter-raw" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index d7102caa..e5b98cd9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,2 +1,2 @@ [workspace] -members = ["price-adapter-raw"] +members = ["price-adapter-raw", "price-adapter"] diff --git a/price-adapter/Cargo.toml b/price-adapter/Cargo.toml new file mode 100644 index 00000000..f1f79c60 --- /dev/null +++ b/price-adapter/Cargo.toml @@ -0,0 +1,4 @@ +[package] +name = "price-adapter" +version = "0.1.0" +edition = "2021" diff --git a/price-adapter/src/lib.rs b/price-adapter/src/lib.rs new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/price-adapter/src/lib.rs @@ -0,0 +1 @@ + From 09213c8cfeec3ffbcf19b9a6cba792e0f59790d0 Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Sat, 18 Nov 2023 19:31:57 +0700 Subject: [PATCH 02/46] first draft version --- Cargo.lock | 7 +++ price-adapter/Cargo.toml | 7 +++ price-adapter/README.md | 3 ++ price-adapter/examples/coingecko-basic.rs | 11 +++++ price-adapter/src/coingecko.rs | 45 +++++++++++++++++++ price-adapter/src/error.rs | 13 ++++++ price-adapter/src/lib.rs | 4 +- .../src/mapper/band_static_mapper.rs | 29 ++++++++++++ price-adapter/src/mapper/mapper.rs | 6 +++ price-adapter/src/mapper/mod.rs | 5 +++ resources/coingecko.json | 4 ++ 11 files changed, 133 insertions(+), 1 deletion(-) create mode 100644 price-adapter/README.md create mode 100644 price-adapter/examples/coingecko-basic.rs create mode 100644 price-adapter/src/coingecko.rs create mode 100644 price-adapter/src/error.rs create mode 100644 price-adapter/src/mapper/band_static_mapper.rs create mode 100644 price-adapter/src/mapper/mapper.rs create mode 100644 price-adapter/src/mapper/mod.rs create mode 100644 resources/coingecko.json diff --git a/Cargo.lock b/Cargo.lock index 9ef7e8a9..decae958 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -728,6 +728,13 @@ checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de" [[package]] name = "price-adapter" version = "0.1.0" +dependencies = [ + "price-adapter-raw", + "serde", + "serde_json", + "thiserror", + "tokio", +] [[package]] name = "price-adapter-raw" diff --git a/price-adapter/Cargo.toml b/price-adapter/Cargo.toml index f1f79c60..5f272461 100644 --- a/price-adapter/Cargo.toml +++ b/price-adapter/Cargo.toml @@ -2,3 +2,10 @@ name = "price-adapter" version = "0.1.0" edition = "2021" + +[dependencies] +price-adapter-raw = { version = "0.1.0", path = "../price-adapter-raw" } +thiserror = "1.0.50" +tokio = { version = "1.0", features = ["full"] } +serde = { version = "1.0.192", features = ["serde_derive"] } +serde_json = "1.0.108" diff --git a/price-adapter/README.md b/price-adapter/README.md new file mode 100644 index 00000000..0e4e00d0 --- /dev/null +++ b/price-adapter/README.md @@ -0,0 +1,3 @@ +# Price adapter + +The primary purpose of the price adapter library is to provide a versatile tool for retrieving the current price of a wide range of supported financial symbols from various data sources, all standardized in terms of the United States Dollar (USD) unit. This library offers a comprehensive and efficient solution for seamlessly accessing and integrating real-time or historical pricing information for a multitude of financial instruments, ensuring that users can effortlessly obtain accurate pricing data in USD for their respective symbols, regardless of the specific data source they choose to utilize. diff --git a/price-adapter/examples/coingecko-basic.rs b/price-adapter/examples/coingecko-basic.rs new file mode 100644 index 00000000..af847e26 --- /dev/null +++ b/price-adapter/examples/coingecko-basic.rs @@ -0,0 +1,11 @@ +use price_adapter::coingecko::CoinGecko; +use price_adapter::mapper::BandStaticMapper; + +#[tokio::main] +async fn main() { + let band_static_mapper = Box::new(BandStaticMapper::new("coingecko".to_string())); + let coingecko = CoinGecko::new(band_static_mapper, None); + let queries = vec!["ETH"]; + let prices = coingecko.get_prices(&queries).await; + println!("prices: {:?}", prices); +} diff --git a/price-adapter/src/coingecko.rs b/price-adapter/src/coingecko.rs new file mode 100644 index 00000000..80b67df5 --- /dev/null +++ b/price-adapter/src/coingecko.rs @@ -0,0 +1,45 @@ +use super::mapper::Mapper; +use crate::error::Error; +use price_adapter_raw::types::PriceInfo; +use price_adapter_raw::CoinGecko as CoinGeckoRaw; + +/// An object to query Coingecko public api. +pub struct CoinGecko { + raw: CoinGeckoRaw, + mapper: Box, +} + +impl CoinGecko { + pub fn new(mapper: Box, api_key: Option) -> Self { + let raw: CoinGeckoRaw; + if let Some(key) = api_key { + raw = CoinGeckoRaw::new_with_api_key(key); + } else { + raw = CoinGeckoRaw::new(); + } + + Self { raw, mapper } + } + + /// get pair prices from the given queries (list of a tuple of (base, quote)). + pub async fn get_prices(&self, symbols: &[&str]) -> Vec> { + let mapping = self.mapper.get_mapping(); + + let ids = symbols + .iter() + .filter_map(|&symbol| { + if let Some(id) = mapping.get(symbol) { + Some(id.as_str().unwrap()) + } else { + None + } + }) + .collect::>(); + + let res = self.raw.get_prices(ids.as_slice()).await; + + res.into_iter() + .map(|result| result.map_err(|e| Error::RawError(e))) + .collect() + } +} diff --git a/price-adapter/src/error.rs b/price-adapter/src/error.rs new file mode 100644 index 00000000..2db8fac0 --- /dev/null +++ b/price-adapter/src/error.rs @@ -0,0 +1,13 @@ +use thiserror::Error; + +#[derive(Debug, Error)] +pub enum Error { + #[error("unknown error")] + Unknown, + + #[error("raw error: {0}")] + RawError(#[from] price_adapter_raw::error::Error), + + #[error("file error: {0}")] + FileError(#[from] std::io::Error), +} diff --git a/price-adapter/src/lib.rs b/price-adapter/src/lib.rs index 8b137891..e6962dfa 100644 --- a/price-adapter/src/lib.rs +++ b/price-adapter/src/lib.rs @@ -1 +1,3 @@ - +pub mod coingecko; +pub mod error; +pub mod mapper; diff --git a/price-adapter/src/mapper/band_static_mapper.rs b/price-adapter/src/mapper/band_static_mapper.rs new file mode 100644 index 00000000..f1bfb266 --- /dev/null +++ b/price-adapter/src/mapper/band_static_mapper.rs @@ -0,0 +1,29 @@ +use super::Mapper; +use serde_json::Value; +use std::collections::HashMap; +use std::fs::File; +use std::io::Read; + +pub struct BandStaticMapper { + mapping: HashMap, +} + +impl BandStaticMapper { + pub fn new(source: String) -> Self { + // Read the JSON file content + let mut file = File::open(format!("resources/{}.json", source)).unwrap(); + let mut content = String::new(); + file.read_to_string(&mut content).unwrap(); + + // Deserialize the JSON content into a Vec + let mapping = serde_json::from_str(&content).unwrap(); + + Self { mapping } + } +} + +impl Mapper for BandStaticMapper { + fn get_mapping(&self) -> &HashMap { + &self.mapping + } +} diff --git a/price-adapter/src/mapper/mapper.rs b/price-adapter/src/mapper/mapper.rs new file mode 100644 index 00000000..a348b5e3 --- /dev/null +++ b/price-adapter/src/mapper/mapper.rs @@ -0,0 +1,6 @@ +use serde_json::Value; +use std::collections::HashMap; + +pub trait Mapper { + fn get_mapping(&self) -> &HashMap; +} diff --git a/price-adapter/src/mapper/mod.rs b/price-adapter/src/mapper/mod.rs new file mode 100644 index 00000000..410e408f --- /dev/null +++ b/price-adapter/src/mapper/mod.rs @@ -0,0 +1,5 @@ +mod band_static_mapper; +mod mapper; + +pub use band_static_mapper::*; +pub use mapper::*; diff --git a/resources/coingecko.json b/resources/coingecko.json new file mode 100644 index 00000000..e556df28 --- /dev/null +++ b/resources/coingecko.json @@ -0,0 +1,4 @@ +{ + "BTC": "bitcoin", + "ETH": "ethereum" +} From a508626818b83e6980105c054de01ef198d27807 Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Sat, 18 Nov 2023 20:00:12 +0700 Subject: [PATCH 03/46] fix clippy --- price-adapter/src/coingecko.rs | 12 +++--------- price-adapter/src/mapper/band_static_mapper.rs | 2 +- price-adapter/src/mapper/mod.rs | 3 +-- price-adapter/src/mapper/{mapper.rs => types.rs} | 0 4 files changed, 5 insertions(+), 12 deletions(-) rename price-adapter/src/mapper/{mapper.rs => types.rs} (100%) diff --git a/price-adapter/src/coingecko.rs b/price-adapter/src/coingecko.rs index 80b67df5..678cf70d 100644 --- a/price-adapter/src/coingecko.rs +++ b/price-adapter/src/coingecko.rs @@ -1,4 +1,4 @@ -use super::mapper::Mapper; +use super::mapper::types::Mapper; use crate::error::Error; use price_adapter_raw::types::PriceInfo; use price_adapter_raw::CoinGecko as CoinGeckoRaw; @@ -27,19 +27,13 @@ impl CoinGecko { let ids = symbols .iter() - .filter_map(|&symbol| { - if let Some(id) = mapping.get(symbol) { - Some(id.as_str().unwrap()) - } else { - None - } - }) + .filter_map(|&symbol| mapping.get(symbol).map(|id| id.as_str().unwrap())) .collect::>(); let res = self.raw.get_prices(ids.as_slice()).await; res.into_iter() - .map(|result| result.map_err(|e| Error::RawError(e))) + .map(|result| result.map_err(Error::RawError)) .collect() } } diff --git a/price-adapter/src/mapper/band_static_mapper.rs b/price-adapter/src/mapper/band_static_mapper.rs index f1bfb266..d11b2ddf 100644 --- a/price-adapter/src/mapper/band_static_mapper.rs +++ b/price-adapter/src/mapper/band_static_mapper.rs @@ -1,4 +1,4 @@ -use super::Mapper; +use super::types::Mapper; use serde_json::Value; use std::collections::HashMap; use std::fs::File; diff --git a/price-adapter/src/mapper/mod.rs b/price-adapter/src/mapper/mod.rs index 410e408f..714317d1 100644 --- a/price-adapter/src/mapper/mod.rs +++ b/price-adapter/src/mapper/mod.rs @@ -1,5 +1,4 @@ mod band_static_mapper; -mod mapper; +pub mod types; pub use band_static_mapper::*; -pub use mapper::*; diff --git a/price-adapter/src/mapper/mapper.rs b/price-adapter/src/mapper/types.rs similarity index 100% rename from price-adapter/src/mapper/mapper.rs rename to price-adapter/src/mapper/types.rs From 896e1f7b76fae5ea0495ee0446ca29b3a0eb692c Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Mon, 20 Nov 2023 13:16:31 +0700 Subject: [PATCH 04/46] fix from comment --- price-adapter/examples/coingecko-basic.rs | 4 ++-- price-adapter/src/coingecko.rs | 10 +++++----- price-adapter/src/error.rs | 4 ++-- price-adapter/src/lib.rs | 4 +++- price-adapter/src/{mapper/mod.rs => mapper.rs} | 0 5 files changed, 12 insertions(+), 10 deletions(-) rename price-adapter/src/{mapper/mod.rs => mapper.rs} (100%) diff --git a/price-adapter/examples/coingecko-basic.rs b/price-adapter/examples/coingecko-basic.rs index af847e26..85768dbd 100644 --- a/price-adapter/examples/coingecko-basic.rs +++ b/price-adapter/examples/coingecko-basic.rs @@ -1,9 +1,9 @@ -use price_adapter::coingecko::CoinGecko; use price_adapter::mapper::BandStaticMapper; +use price_adapter::CoinGecko; #[tokio::main] async fn main() { - let band_static_mapper = Box::new(BandStaticMapper::new("coingecko".to_string())); + let band_static_mapper = BandStaticMapper::new("coingecko".to_string()); let coingecko = CoinGecko::new(band_static_mapper, None); let queries = vec!["ETH"]; let prices = coingecko.get_prices(&queries).await; diff --git a/price-adapter/src/coingecko.rs b/price-adapter/src/coingecko.rs index 678cf70d..2bea339b 100644 --- a/price-adapter/src/coingecko.rs +++ b/price-adapter/src/coingecko.rs @@ -4,13 +4,13 @@ use price_adapter_raw::types::PriceInfo; use price_adapter_raw::CoinGecko as CoinGeckoRaw; /// An object to query Coingecko public api. -pub struct CoinGecko { +pub struct CoinGecko { raw: CoinGeckoRaw, - mapper: Box, + mapper: M, } -impl CoinGecko { - pub fn new(mapper: Box, api_key: Option) -> Self { +impl CoinGecko { + pub fn new(mapper: M, api_key: Option) -> Self { let raw: CoinGeckoRaw; if let Some(key) = api_key { raw = CoinGeckoRaw::new_with_api_key(key); @@ -33,7 +33,7 @@ impl CoinGecko { let res = self.raw.get_prices(ids.as_slice()).await; res.into_iter() - .map(|result| result.map_err(Error::RawError)) + .map(|result| result.map_err(Error::PriceAdapterRawError)) .collect() } } diff --git a/price-adapter/src/error.rs b/price-adapter/src/error.rs index 2db8fac0..d5ffd273 100644 --- a/price-adapter/src/error.rs +++ b/price-adapter/src/error.rs @@ -5,8 +5,8 @@ pub enum Error { #[error("unknown error")] Unknown, - #[error("raw error: {0}")] - RawError(#[from] price_adapter_raw::error::Error), + #[error("price-adapter-raw error: {0}")] + PriceAdapterRawError(#[from] price_adapter_raw::error::Error), #[error("file error: {0}")] FileError(#[from] std::io::Error), diff --git a/price-adapter/src/lib.rs b/price-adapter/src/lib.rs index e6962dfa..3186caf1 100644 --- a/price-adapter/src/lib.rs +++ b/price-adapter/src/lib.rs @@ -1,3 +1,5 @@ -pub mod coingecko; +mod coingecko; pub mod error; pub mod mapper; + +pub use coingecko::CoinGecko; diff --git a/price-adapter/src/mapper/mod.rs b/price-adapter/src/mapper.rs similarity index 100% rename from price-adapter/src/mapper/mod.rs rename to price-adapter/src/mapper.rs From 46a1476a4961dfe7afcb62c6fe591b80a34a60a1 Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Mon, 20 Nov 2023 17:04:15 +0700 Subject: [PATCH 05/46] update logic --- price-adapter/examples/coingecko-basic.rs | 2 +- price-adapter/src/coingecko.rs | 35 +++++++++++++++++------ price-adapter/src/error.rs | 3 ++ price-adapter/src/lib.rs | 1 + price-adapter/src/types.rs | 18 ++++++++++++ 5 files changed, 50 insertions(+), 9 deletions(-) create mode 100644 price-adapter/src/types.rs diff --git a/price-adapter/examples/coingecko-basic.rs b/price-adapter/examples/coingecko-basic.rs index 85768dbd..fda520d6 100644 --- a/price-adapter/examples/coingecko-basic.rs +++ b/price-adapter/examples/coingecko-basic.rs @@ -5,7 +5,7 @@ use price_adapter::CoinGecko; async fn main() { let band_static_mapper = BandStaticMapper::new("coingecko".to_string()); let coingecko = CoinGecko::new(band_static_mapper, None); - let queries = vec!["ETH"]; + let queries = vec!["ETH", "BAND"]; let prices = coingecko.get_prices(&queries).await; println!("prices: {:?}", prices); } diff --git a/price-adapter/src/coingecko.rs b/price-adapter/src/coingecko.rs index 2bea339b..1bc68f52 100644 --- a/price-adapter/src/coingecko.rs +++ b/price-adapter/src/coingecko.rs @@ -1,6 +1,6 @@ use super::mapper::types::Mapper; use crate::error::Error; -use price_adapter_raw::types::PriceInfo; +use crate::types::PriceInfo; use price_adapter_raw::CoinGecko as CoinGeckoRaw; /// An object to query Coingecko public api. @@ -25,15 +25,34 @@ impl CoinGecko { pub async fn get_prices(&self, symbols: &[&str]) -> Vec> { let mapping = self.mapper.get_mapping(); - let ids = symbols + let ids_with_index: Vec<(&str, &str, usize)> = symbols .iter() - .filter_map(|&symbol| mapping.get(symbol).map(|id| id.as_str().unwrap())) - .collect::>(); + .enumerate() + .filter_map(|(index, &symbol)| { + mapping + .get(symbol) + .and_then(|id| id.as_str().and_then(|id| Some((symbol, id, index)))) + }) + .collect(); - let res = self.raw.get_prices(ids.as_slice()).await; + let ids: Vec<&str> = ids_with_index.iter().map(|(_, id, _)| *id).collect(); + let prices = self.raw.get_prices(ids.as_slice()).await; - res.into_iter() - .map(|result| result.map_err(Error::PriceAdapterRawError)) - .collect() + let mut res: Vec> = symbols + .iter() + .map(|_| Err(Error::UnsupportedSymbol)) + .collect(); + + for (&id, price) in ids_with_index.iter().zip(prices) { + res[id.2] = price + .map_err(Error::PriceAdapterRawError) + .map(|p| PriceInfo { + symbol: id.0.to_string(), + price: p.price, + timestamp: p.timestamp, + }); + } + + res } } diff --git a/price-adapter/src/error.rs b/price-adapter/src/error.rs index d5ffd273..09f87f28 100644 --- a/price-adapter/src/error.rs +++ b/price-adapter/src/error.rs @@ -10,4 +10,7 @@ pub enum Error { #[error("file error: {0}")] FileError(#[from] std::io::Error), + + #[error("unsupported symbol")] + UnsupportedSymbol, } diff --git a/price-adapter/src/lib.rs b/price-adapter/src/lib.rs index 3186caf1..b97a713f 100644 --- a/price-adapter/src/lib.rs +++ b/price-adapter/src/lib.rs @@ -1,5 +1,6 @@ mod coingecko; pub mod error; pub mod mapper; +pub mod types; pub use coingecko::CoinGecko; diff --git a/price-adapter/src/types.rs b/price-adapter/src/types.rs new file mode 100644 index 00000000..4e1baae2 --- /dev/null +++ b/price-adapter/src/types.rs @@ -0,0 +1,18 @@ +use core::fmt; + +#[derive(Clone, Debug)] +pub struct PriceInfo { + pub symbol: String, + pub price: f64, + pub timestamp: u64, +} + +impl fmt::Display for PriceInfo { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "PriceInfo {{ symbol: {}, price: {}, timestamp: {} }}", + self.symbol, self.price, self.timestamp + ) + } +} From d405206d8a70f297242e9ec2ae22c12dbefe4c38 Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Mon, 20 Nov 2023 18:06:27 +0700 Subject: [PATCH 06/46] fix based on comment --- price-adapter/examples/coingecko-basic.rs | 2 +- price-adapter/src/coingecko.rs | 86 +++++++++++-------- price-adapter/src/error.rs | 6 ++ .../src/mapper/band_static_mapper.rs | 37 ++++++-- price-adapter/src/mapper/types.rs | 3 +- 5 files changed, 88 insertions(+), 46 deletions(-) diff --git a/price-adapter/examples/coingecko-basic.rs b/price-adapter/examples/coingecko-basic.rs index fda520d6..0281175f 100644 --- a/price-adapter/examples/coingecko-basic.rs +++ b/price-adapter/examples/coingecko-basic.rs @@ -3,7 +3,7 @@ use price_adapter::CoinGecko; #[tokio::main] async fn main() { - let band_static_mapper = BandStaticMapper::new("coingecko".to_string()); + let band_static_mapper = BandStaticMapper::from_source("coingecko").unwrap(); let coingecko = CoinGecko::new(band_static_mapper, None); let queries = vec!["ETH", "BAND"]; let prices = coingecko.get_prices(&queries).await; diff --git a/price-adapter/src/coingecko.rs b/price-adapter/src/coingecko.rs index 1bc68f52..1b617450 100644 --- a/price-adapter/src/coingecko.rs +++ b/price-adapter/src/coingecko.rs @@ -3,56 +3,72 @@ use crate::error::Error; use crate::types::PriceInfo; use price_adapter_raw::CoinGecko as CoinGeckoRaw; -/// An object to query Coingecko public api. +// Generic struct `CoinGecko` parameterized over a `Mapper` type. pub struct CoinGecko { raw: CoinGeckoRaw, mapper: M, } impl CoinGecko { + // Constructor for the `CoinGecko` struct. pub fn new(mapper: M, api_key: Option) -> Self { - let raw: CoinGeckoRaw; - if let Some(key) = api_key { - raw = CoinGeckoRaw::new_with_api_key(key); + // Initialize `CoinGeckoRaw` based on the presence of an API key. + let raw = if let Some(key) = api_key { + CoinGeckoRaw::new_with_api_key(key) } else { - raw = CoinGeckoRaw::new(); - } + CoinGeckoRaw::new() + }; Self { raw, mapper } } - /// get pair prices from the given queries (list of a tuple of (base, quote)). + // Asynchronous function to get prices for symbols. pub async fn get_prices(&self, symbols: &[&str]) -> Vec> { + // Retrieve the symbol-to-id mapping from the provided mapper. let mapping = self.mapper.get_mapping(); - let ids_with_index: Vec<(&str, &str, usize)> = symbols - .iter() - .enumerate() - .filter_map(|(index, &symbol)| { - mapping - .get(symbol) - .and_then(|id| id.as_str().and_then(|id| Some((symbol, id, index)))) - }) - .collect(); - - let ids: Vec<&str> = ids_with_index.iter().map(|(_, id, _)| *id).collect(); - let prices = self.raw.get_prices(ids.as_slice()).await; - - let mut res: Vec> = symbols - .iter() - .map(|_| Err(Error::UnsupportedSymbol)) - .collect(); - - for (&id, price) in ids_with_index.iter().zip(prices) { - res[id.2] = price - .map_err(Error::PriceAdapterRawError) - .map(|p| PriceInfo { - symbol: id.0.to_string(), - price: p.price, - timestamp: p.timestamp, - }); - } + // Match on the result of obtaining the mapping. + if let Ok(mapping) = mapping { + // Collect symbols with associated ids and indices. + let ids_with_index: Vec<(&str, &str, usize)> = symbols + .iter() + .enumerate() + .filter_map(|(index, &symbol)| { + mapping + .get(symbol) + .and_then(|id| id.as_str().map(|id| (symbol, id, index))) + }) + .collect(); + + // Extract only the ids from the collected tuples. + let ids: Vec<&str> = ids_with_index.iter().map(|(_, id, _)| *id).collect(); + + // Retrieve prices for the collected ids asynchronously. + let prices = self.raw.get_prices(ids.as_slice()).await; - res + // Initialize a vector to store the results. + let mut res: Vec> = symbols + .iter() + .map(|_| Err(Error::UnsupportedSymbol)) + .collect(); + + // Iterate over collected ids and prices to populate the results vector. + for (&id, price) in ids_with_index.iter().zip(prices) { + // Assign the result based on the price, mapping errors. + res[id.2] = price + .map_err(Error::PriceAdapterRawError) + .map(|p| PriceInfo { + symbol: id.0.to_string(), + price: p.price, + timestamp: p.timestamp, + }); + } + + // Return the results vector. + res + } else { + // Return errors for symbols if there's an issue with the mapping. + symbols.iter().map(|_| Err(Error::MappingError)).collect() + } } } diff --git a/price-adapter/src/error.rs b/price-adapter/src/error.rs index 09f87f28..8b21740c 100644 --- a/price-adapter/src/error.rs +++ b/price-adapter/src/error.rs @@ -11,6 +11,12 @@ pub enum Error { #[error("file error: {0}")] FileError(#[from] std::io::Error), + #[error("serde-json error: {0}")] + SerdeJsonError(#[from] serde_json::Error), + #[error("unsupported symbol")] UnsupportedSymbol, + + #[error("mapping error")] + MappingError, } diff --git a/price-adapter/src/mapper/band_static_mapper.rs b/price-adapter/src/mapper/band_static_mapper.rs index d11b2ddf..53eb395d 100644 --- a/price-adapter/src/mapper/band_static_mapper.rs +++ b/price-adapter/src/mapper/band_static_mapper.rs @@ -1,29 +1,48 @@ use super::types::Mapper; +use crate::error::Error; use serde_json::Value; use std::collections::HashMap; use std::fs::File; use std::io::Read; +use std::path::Path; +// A struct representing a static mapper using a HashMap of String keys to Values. pub struct BandStaticMapper { mapping: HashMap, } impl BandStaticMapper { - pub fn new(source: String) -> Self { - // Read the JSON file content - let mut file = File::open(format!("resources/{}.json", source)).unwrap(); + // Constructor to create a new BandStaticMapper from a pre-existing mapping. + pub fn new(mapping: HashMap) -> Self { + Self { mapping } + } + + // Constructor to create a BandStaticMapper from a source file. + pub fn from_source(source: &str) -> Result { + let path = format!("resources/{}.json", source.to_lowercase()); + Self::from_path(path) + } + + // Constructor to create a BandStaticMapper from a file path. + pub fn from_path>(path: P) -> Result { + // Attempt to open the file at the specified path. + let mut file = File::open(&path)?; + + // Read the file content into a String. let mut content = String::new(); - file.read_to_string(&mut content).unwrap(); + file.read_to_string(&mut content)?; - // Deserialize the JSON content into a Vec - let mapping = serde_json::from_str(&content).unwrap(); + // Deserialize the JSON content into a HashMap. + let mapping = serde_json::from_str(&content)?; - Self { mapping } + Ok(Self { mapping }) } } +// Implementing the Mapper trait for BandStaticMapper. impl Mapper for BandStaticMapper { - fn get_mapping(&self) -> &HashMap { - &self.mapping + // Retrieve the mapping as a reference, wrapped in a Result. + fn get_mapping(&self) -> Result<&HashMap, Error> { + Ok(&self.mapping) } } diff --git a/price-adapter/src/mapper/types.rs b/price-adapter/src/mapper/types.rs index a348b5e3..813b57b8 100644 --- a/price-adapter/src/mapper/types.rs +++ b/price-adapter/src/mapper/types.rs @@ -1,6 +1,7 @@ +use crate::error::Error; use serde_json::Value; use std::collections::HashMap; pub trait Mapper { - fn get_mapping(&self) -> &HashMap; + fn get_mapping(&self) -> Result<&HashMap, Error>; } From d06cd536faa8ce329ee939ce898d7a813bae0a3f Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Tue, 21 Nov 2023 14:37:49 +0700 Subject: [PATCH 07/46] add default --- Cargo.lock | 15 +++++++++++++++ price-adapter/Cargo.toml | 4 ++++ price-adapter/examples/coingecko-basic.rs | 5 ++--- price-adapter/src/coingecko.rs | 19 +++++++++++++++---- .../src/mapper/band_static_mapper.rs | 3 ++- price-adapter/src/mapper/types.rs | 5 +++-- price-adapter/src/types.rs | 6 ++++++ 7 files changed, 47 insertions(+), 10 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index decae958..159339d8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -32,6 +32,17 @@ dependencies = [ "libc", ] +[[package]] +name = "async-trait" +version = "0.1.74" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a66537f1bb974b254c98ed142ff995236e81b9d0fe4db0575f46612cb15eb0f9" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "autocfg" version = "1.1.0" @@ -729,11 +740,15 @@ checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de" name = "price-adapter" version = "0.1.0" dependencies = [ + "async-trait", + "futures-util", "price-adapter-raw", "serde", "serde_json", "thiserror", "tokio", + "tokio-tungstenite", + "tokio-util", ] [[package]] diff --git a/price-adapter/Cargo.toml b/price-adapter/Cargo.toml index 5f272461..b79e291d 100644 --- a/price-adapter/Cargo.toml +++ b/price-adapter/Cargo.toml @@ -9,3 +9,7 @@ thiserror = "1.0.50" tokio = { version = "1.0", features = ["full"] } serde = { version = "1.0.192", features = ["serde_derive"] } serde_json = "1.0.108" +tokio-tungstenite = { version = "0.20.1", features = ["native-tls"] } +futures-util = "0.3.29" +tokio-util = "0.7.10" +async-trait = "0.1.74" diff --git a/price-adapter/examples/coingecko-basic.rs b/price-adapter/examples/coingecko-basic.rs index 0281175f..fdee0404 100644 --- a/price-adapter/examples/coingecko-basic.rs +++ b/price-adapter/examples/coingecko-basic.rs @@ -1,10 +1,9 @@ -use price_adapter::mapper::BandStaticMapper; +use price_adapter::types::PriceAdapter; use price_adapter::CoinGecko; #[tokio::main] async fn main() { - let band_static_mapper = BandStaticMapper::from_source("coingecko").unwrap(); - let coingecko = CoinGecko::new(band_static_mapper, None); + let coingecko = CoinGecko::default(None).unwrap(); let queries = vec!["ETH", "BAND"]; let prices = coingecko.get_prices(&queries).await; println!("prices: {:?}", prices); diff --git a/price-adapter/src/coingecko.rs b/price-adapter/src/coingecko.rs index 1b617450..775d269f 100644 --- a/price-adapter/src/coingecko.rs +++ b/price-adapter/src/coingecko.rs @@ -1,6 +1,7 @@ -use super::mapper::types::Mapper; use crate::error::Error; -use crate::types::PriceInfo; +use crate::mapper::types::Mapper; +use crate::mapper::BandStaticMapper; +use crate::types::{PriceAdapter, PriceInfo}; use price_adapter_raw::CoinGecko as CoinGeckoRaw; // Generic struct `CoinGecko` parameterized over a `Mapper` type. @@ -21,11 +22,21 @@ impl CoinGecko { Self { raw, mapper } } +} + +impl CoinGecko { + pub fn default(api_key: Option) -> Result { + let mapper = BandStaticMapper::from_source("coingecko")?; + Ok(Self::new(mapper, api_key)) + } +} +#[async_trait::async_trait] +impl PriceAdapter for CoinGecko { // Asynchronous function to get prices for symbols. - pub async fn get_prices(&self, symbols: &[&str]) -> Vec> { + async fn get_prices(&self, symbols: &[&str]) -> Vec> { // Retrieve the symbol-to-id mapping from the provided mapper. - let mapping = self.mapper.get_mapping(); + let mapping = self.mapper.get_mapping().await; // Match on the result of obtaining the mapping. if let Ok(mapping) = mapping { diff --git a/price-adapter/src/mapper/band_static_mapper.rs b/price-adapter/src/mapper/band_static_mapper.rs index 53eb395d..b0132cc4 100644 --- a/price-adapter/src/mapper/band_static_mapper.rs +++ b/price-adapter/src/mapper/band_static_mapper.rs @@ -40,9 +40,10 @@ impl BandStaticMapper { } // Implementing the Mapper trait for BandStaticMapper. +#[async_trait::async_trait] impl Mapper for BandStaticMapper { // Retrieve the mapping as a reference, wrapped in a Result. - fn get_mapping(&self) -> Result<&HashMap, Error> { + async fn get_mapping(&self) -> Result<&HashMap, Error> { Ok(&self.mapping) } } diff --git a/price-adapter/src/mapper/types.rs b/price-adapter/src/mapper/types.rs index 813b57b8..76ff39f8 100644 --- a/price-adapter/src/mapper/types.rs +++ b/price-adapter/src/mapper/types.rs @@ -2,6 +2,7 @@ use crate::error::Error; use serde_json::Value; use std::collections::HashMap; -pub trait Mapper { - fn get_mapping(&self) -> Result<&HashMap, Error>; +#[async_trait::async_trait] +pub trait Mapper: Send + Sync + Sized + 'static { + async fn get_mapping(&self) -> Result<&HashMap, Error>; } diff --git a/price-adapter/src/types.rs b/price-adapter/src/types.rs index 4e1baae2..8f84fe06 100644 --- a/price-adapter/src/types.rs +++ b/price-adapter/src/types.rs @@ -1,3 +1,4 @@ +use crate::error::Error; use core::fmt; #[derive(Clone, Debug)] @@ -16,3 +17,8 @@ impl fmt::Display for PriceInfo { ) } } + +#[async_trait::async_trait] +pub trait PriceAdapter: Send + Sync + 'static { + async fn get_prices(&self, symbols: &[&str]) -> Vec>; +} From 669798be1e454ae55bc8140a1c6e3dd232b6d061 Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Wed, 22 Nov 2023 17:08:07 +0700 Subject: [PATCH 08/46] add binance first draft --- price-adapter/examples/binance-websocket.rs | 18 ++++ price-adapter/src/binance.rs | 3 + price-adapter/src/binance/websocket.rs | 107 ++++++++++++++++++++ price-adapter/src/lib.rs | 2 + resources/binance.json | 4 + 5 files changed, 134 insertions(+) create mode 100644 price-adapter/examples/binance-websocket.rs create mode 100644 price-adapter/src/binance.rs create mode 100644 price-adapter/src/binance/websocket.rs create mode 100644 resources/binance.json diff --git a/price-adapter/examples/binance-websocket.rs b/price-adapter/examples/binance-websocket.rs new file mode 100644 index 00000000..6f89542f --- /dev/null +++ b/price-adapter/examples/binance-websocket.rs @@ -0,0 +1,18 @@ +use futures_util::StreamExt; +use price_adapter::BinanceWebsocket; + +#[tokio::main] +async fn main() { + let mut binance_websocket = BinanceWebsocket::default().unwrap(); + let symbols = vec!["ETH", "BTC"]; + + binance_websocket.connect().await.unwrap(); + binance_websocket + .subscribe(symbols.as_slice()) + .await + .unwrap(); + + while let Some(data) = binance_websocket.next().await { + println!("{:?}", data); + } +} diff --git a/price-adapter/src/binance.rs b/price-adapter/src/binance.rs new file mode 100644 index 00000000..5db6a293 --- /dev/null +++ b/price-adapter/src/binance.rs @@ -0,0 +1,3 @@ +mod websocket; + +pub use websocket::BinanceWebsocket; diff --git a/price-adapter/src/binance/websocket.rs b/price-adapter/src/binance/websocket.rs new file mode 100644 index 00000000..6788b15b --- /dev/null +++ b/price-adapter/src/binance/websocket.rs @@ -0,0 +1,107 @@ +use crate::error::Error; +use crate::mapper::types::Mapper; +use crate::mapper::BandStaticMapper; +use futures_util::{Stream, StreamExt}; +use price_adapter_raw::types::WebsocketMessage as WebsocketMessageRaw; +use price_adapter_raw::BinanceWebsocket as BinanceWebsocketRaw; +use std::{ + pin::Pin, + sync::Arc, + task::{Context, Poll}, +}; +use tokio::sync::Mutex; + +// Generic struct `BinanceWebsocket` parameterized over a `Mapper` type. +pub struct BinanceWebsocket { + raw: Option>>, + mapper: M, +} + +impl BinanceWebsocket { + // Constructor for the `BinanceWebsocket` struct. + pub fn new(mapper: M) -> Self { + Self { raw: None, mapper } + } + + pub async fn connect(&mut self) -> Result<(), Error> { + let raw = Arc::new(Mutex::new(BinanceWebsocketRaw::new( + "wss://stream.binance.com:9443", + ))); + + let mut locked_raw = raw.lock().await; + if !locked_raw.is_connected() { + locked_raw.connect().await?; + } + drop(locked_raw); + + self.raw = Some(raw); + + Ok(()) + } + + pub async fn subscribe(&mut self, symbols: &[&str]) -> Result { + // Retrieve the symbol-to-id mapping from the provided mapper. + let mapping = self.mapper.get_mapping().await?; + + let ids: Vec<&str> = symbols + .iter() + .filter_map(|&symbol| mapping.get(symbol)) + .filter_map(|val| val.as_str()) + .collect(); + + if ids.len() != symbols.len() { + return Err(Error::UnsupportedSymbol); + } + + let raw = self.raw.as_mut().ok_or(Error::Unknown)?; + let mut locked_raw = raw.lock().await; + locked_raw + .subscribe(ids.as_slice()) + .await + .map_err(Error::PriceAdapterRawError) + } + + pub fn is_connected(&self) -> bool { + self.raw.is_some() + } +} + +impl BinanceWebsocket { + pub fn default() -> Result { + let mapper = BandStaticMapper::from_source("binance")?; + Ok(Self::new(mapper)) + } +} + +impl Stream for BinanceWebsocket { + type Item = Result; + + fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let Some(raw) = &self.raw else { + return Poll::Ready(None); + }; + + loop { + let Ok(mut locked_raw) = raw.try_lock() else { + + continue; + }; + + match locked_raw.poll_next_unpin(cx) { + Poll::Ready(Some(message)) => { + let result = match message { + Ok(WebsocketMessageRaw::PriceInfo(price_info)) => { + println!("internal: {:?}", price_info); + Poll::Ready(Some(Ok(0_u64))) + } + Ok(_) => continue, + Err(err) => Poll::Ready(Some(Err(err.into()))), + }; + return result; + } + Poll::Ready(None) => return Poll::Ready(None), + Poll::Pending => return Poll::Pending, + }; + } + } +} diff --git a/price-adapter/src/lib.rs b/price-adapter/src/lib.rs index b97a713f..3fed0063 100644 --- a/price-adapter/src/lib.rs +++ b/price-adapter/src/lib.rs @@ -1,6 +1,8 @@ +mod binance; mod coingecko; pub mod error; pub mod mapper; pub mod types; +pub use binance::BinanceWebsocket; pub use coingecko::CoinGecko; diff --git a/resources/binance.json b/resources/binance.json new file mode 100644 index 00000000..a6e04053 --- /dev/null +++ b/resources/binance.json @@ -0,0 +1,4 @@ +{ + "BTC": "btcusdt", + "ETH": "ethusdt" +} From 2108b7f7068d662b97e2e62444c257f885e90c2d Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Wed, 22 Nov 2023 18:00:15 +0700 Subject: [PATCH 09/46] fix to waker --- price-adapter/src/binance/websocket.rs | 53 +++++++++++++++----------- 1 file changed, 31 insertions(+), 22 deletions(-) diff --git a/price-adapter/src/binance/websocket.rs b/price-adapter/src/binance/websocket.rs index 6788b15b..213a1b7c 100644 --- a/price-adapter/src/binance/websocket.rs +++ b/price-adapter/src/binance/websocket.rs @@ -77,31 +77,40 @@ impl Stream for BinanceWebsocket { type Item = Result; fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + println!("start poll_next"); let Some(raw) = &self.raw else { return Poll::Ready(None); }; - loop { - let Ok(mut locked_raw) = raw.try_lock() else { - - continue; - }; - - match locked_raw.poll_next_unpin(cx) { - Poll::Ready(Some(message)) => { - let result = match message { - Ok(WebsocketMessageRaw::PriceInfo(price_info)) => { - println!("internal: {:?}", price_info); - Poll::Ready(Some(Ok(0_u64))) - } - Ok(_) => continue, - Err(err) => Poll::Ready(Some(Err(err.into()))), - }; - return result; - } - Poll::Ready(None) => return Poll::Ready(None), - Poll::Pending => return Poll::Pending, - }; - } + let Ok(mut locked_raw) = raw.try_lock() else { + cx.waker().wake_by_ref(); + return Poll::Pending; + }; + + match locked_raw.poll_next_unpin(cx) { + Poll::Ready(Some(message)) => { + println!("message: {:?}", message); + let result = match message { + Ok(WebsocketMessageRaw::PriceInfo(price_info)) => { + println!("internal: {:?}", price_info); + Poll::Ready(Some(Ok(0_u64))) + } + Ok(_) => { + cx.waker().wake_by_ref(); + println!("!!! before sleep"); + std::thread::sleep(tokio::time::Duration::from_secs(4)); + println!("!!! after sleep"); + + return Poll::Pending; + } + Err(err) => Poll::Ready(Some(Err(err.into()))), + }; + return result; + } + Poll::Ready(None) => return Poll::Ready(None), + Poll::Pending => { + return Poll::Pending; + } + }; } } From 9fad96cf7af6271ca1e1a1e032882e7c2296558f Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Wed, 22 Nov 2023 18:18:06 +0700 Subject: [PATCH 10/46] fix mapping --- price-adapter/src/binance/websocket.rs | 40 ++++++++++++++++++-------- price-adapter/src/types.rs | 14 +++++++++ 2 files changed, 42 insertions(+), 12 deletions(-) diff --git a/price-adapter/src/binance/websocket.rs b/price-adapter/src/binance/websocket.rs index 213a1b7c..797cda03 100644 --- a/price-adapter/src/binance/websocket.rs +++ b/price-adapter/src/binance/websocket.rs @@ -1,10 +1,12 @@ -use crate::error::Error; use crate::mapper::types::Mapper; use crate::mapper::BandStaticMapper; +use crate::types::WebsocketMessage; +use crate::{error::Error, types::PriceInfo}; use futures_util::{Stream, StreamExt}; use price_adapter_raw::types::WebsocketMessage as WebsocketMessageRaw; use price_adapter_raw::BinanceWebsocket as BinanceWebsocketRaw; use std::{ + collections::HashMap, pin::Pin, sync::Arc, task::{Context, Poll}, @@ -14,13 +16,18 @@ use tokio::sync::Mutex; // Generic struct `BinanceWebsocket` parameterized over a `Mapper` type. pub struct BinanceWebsocket { raw: Option>>, + mapping_back: HashMap, mapper: M, } impl BinanceWebsocket { // Constructor for the `BinanceWebsocket` struct. pub fn new(mapper: M) -> Self { - Self { raw: None, mapper } + Self { + raw: None, + mapping_back: HashMap::new(), + mapper, + } } pub async fn connect(&mut self) -> Result<(), Error> { @@ -43,6 +50,13 @@ impl BinanceWebsocket { // Retrieve the symbol-to-id mapping from the provided mapper. let mapping = self.mapper.get_mapping().await?; + for (key, value) in mapping { + if let Some(pair) = value.as_str() { + self.mapping_back + .insert(pair.to_string().to_uppercase(), key.to_string()); + } + } + let ids: Vec<&str> = symbols .iter() .filter_map(|&symbol| mapping.get(symbol)) @@ -74,10 +88,9 @@ impl BinanceWebsocket { } impl Stream for BinanceWebsocket { - type Item = Result; + type Item = Result; fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { - println!("start poll_next"); let Some(raw) = &self.raw else { return Poll::Ready(None); }; @@ -89,18 +102,21 @@ impl Stream for BinanceWebsocket { match locked_raw.poll_next_unpin(cx) { Poll::Ready(Some(message)) => { - println!("message: {:?}", message); let result = match message { - Ok(WebsocketMessageRaw::PriceInfo(price_info)) => { - println!("internal: {:?}", price_info); - Poll::Ready(Some(Ok(0_u64))) + Ok(WebsocketMessageRaw::PriceInfo(price_info_raw)) => { + if let Some(symbol) = self.mapping_back.get(&price_info_raw.id) { + return Poll::Ready(Some(Ok(WebsocketMessage::PriceInfo(PriceInfo { + symbol: symbol.to_string(), + price: price_info_raw.price, + timestamp: price_info_raw.timestamp, + })))); + } + + cx.waker().wake_by_ref(); + return Poll::Pending; } Ok(_) => { cx.waker().wake_by_ref(); - println!("!!! before sleep"); - std::thread::sleep(tokio::time::Duration::from_secs(4)); - println!("!!! after sleep"); - return Poll::Pending; } Err(err) => Poll::Ready(Some(Err(err.into()))), diff --git a/price-adapter/src/types.rs b/price-adapter/src/types.rs index 8f84fe06..7a054626 100644 --- a/price-adapter/src/types.rs +++ b/price-adapter/src/types.rs @@ -1,3 +1,6 @@ +use serde::Deserialize; +use serde_json::Value; + use crate::error::Error; use core::fmt; @@ -22,3 +25,14 @@ impl fmt::Display for PriceInfo { pub trait PriceAdapter: Send + Sync + 'static { async fn get_prices(&self, symbols: &[&str]) -> Vec>; } + +#[derive(Debug, Deserialize)] +pub struct SettingResponse { + pub data: Value, +} + +#[derive(Debug)] +pub enum WebsocketMessage { + PriceInfo(PriceInfo), + SettingResponse(SettingResponse), +} From 9dc893b0161d7480b8ae4de4a8310bba332a5747 Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Thu, 23 Nov 2023 13:02:14 +0700 Subject: [PATCH 11/46] add service --- .../examples/binance-websocket-service.rs | 14 +++ price-adapter/src/binance.rs | 2 + price-adapter/src/binance/service.rs | 92 ++++++++++++++++++ price-adapter/src/binance/websocket.rs | 97 ++++++++++++------- price-adapter/src/error.rs | 9 ++ price-adapter/src/lib.rs | 5 +- price-adapter/src/mapper/types.rs | 2 +- price-adapter/src/stable_coin.rs | 4 + .../src/stable_coin/band_stable_coin.rs | 26 +++++ price-adapter/src/stable_coin/types.rs | 5 + price-adapter/src/types.rs | 7 ++ 11 files changed, 223 insertions(+), 40 deletions(-) create mode 100644 price-adapter/examples/binance-websocket-service.rs create mode 100644 price-adapter/src/binance/service.rs create mode 100644 price-adapter/src/stable_coin.rs create mode 100644 price-adapter/src/stable_coin/band_stable_coin.rs create mode 100644 price-adapter/src/stable_coin/types.rs diff --git a/price-adapter/examples/binance-websocket-service.rs b/price-adapter/examples/binance-websocket-service.rs new file mode 100644 index 00000000..57a16a97 --- /dev/null +++ b/price-adapter/examples/binance-websocket-service.rs @@ -0,0 +1,14 @@ +use price_adapter::{BinanceWebsocket, BinanceWebsocketService}; +use std::time::Duration; + +#[tokio::main] +async fn main() { + let binance_websocket = BinanceWebsocket::default().unwrap(); + let mut service = BinanceWebsocketService::new(binance_websocket); + service.start(vec!["BTC"].as_slice()).await.unwrap(); + + loop { + tokio::time::sleep(Duration::from_secs(1)).await; + println!("{:?}", service.get_prices(&["BTC"]).await); + } +} diff --git a/price-adapter/src/binance.rs b/price-adapter/src/binance.rs index 5db6a293..7a01bdf9 100644 --- a/price-adapter/src/binance.rs +++ b/price-adapter/src/binance.rs @@ -1,3 +1,5 @@ +mod service; mod websocket; +pub use service::BinanceWebsocketService; pub use websocket::BinanceWebsocket; diff --git a/price-adapter/src/binance/service.rs b/price-adapter/src/binance/service.rs new file mode 100644 index 00000000..555f6796 --- /dev/null +++ b/price-adapter/src/binance/service.rs @@ -0,0 +1,92 @@ +use super::websocket::BinanceWebsocket; +use crate::mapper::types::Mapper; +use crate::stable_coin::types::StableCoin; +use crate::{ + error::Error, + types::{PriceInfo, WebsocketMessage}, +}; +use futures_util::StreamExt; +use std::{collections::HashMap, sync::Arc}; +use tokio::sync::Mutex; +use tokio_util::sync::CancellationToken; + +/// A caching object storing prices received from binance websocket. +pub struct BinanceWebsocketService { + socket: Arc>>, + cached_price: Arc>>, + cancellation_token: Option, +} + +impl BinanceWebsocketService { + /// initiate new object from created socket. + pub fn new(socket: BinanceWebsocket) -> Self { + Self { + socket: Arc::new(Mutex::new(socket)), + cached_price: Arc::new(Mutex::new(HashMap::new())), + cancellation_token: None, + } + } + + /// start a service. + pub async fn start(&mut self, symbols: &[&str]) -> Result<(), Error> { + if self.cancellation_token.is_some() { + return Err(Error::AlreadyStarted); + } + + let mut locked_socket = self.socket.lock().await; + if !locked_socket.is_connected() { + locked_socket.connect().await?; + locked_socket.subscribe(symbols).await?; + } + drop(locked_socket); + + let token = CancellationToken::new(); + let cloned_socket = Arc::clone(&self.socket); + let cloned_cached_price = Arc::clone(&self.cached_price); + self.cancellation_token = Some(token); + + tokio::spawn(async move { + loop { + let mut locked_socket = cloned_socket.lock().await; + + while let Some(result) = locked_socket.next().await { + match result { + Ok(WebsocketMessage::PriceInfo(price_info)) => { + let mut locked_cached_price = cloned_cached_price.lock().await; + locked_cached_price + .insert(price_info.symbol.to_string(), price_info.clone()); + } + Ok(WebsocketMessage::SettingResponse(_response)) => {} + Err(_) => {} + } + } + } + }); + + Ok(()) + } + + /// stop a service. + pub fn stop(&mut self) { + if let Some(token) = &self.cancellation_token { + token.cancel(); + } + self.cancellation_token = None; + } + + pub async fn get_prices(&self, symbols: &[&str]) -> Vec> { + let mut prices = Vec::new(); + let locked_cached_price = self.cached_price.lock().await; + + for &symbol in symbols { + let price = match locked_cached_price.get(&symbol.to_ascii_uppercase()) { + Some(price) => Ok(price.clone()), + None => Err(Error::NotFound(symbol.to_string())), + }; + + prices.push(price); + } + + prices + } +} diff --git a/price-adapter/src/binance/websocket.rs b/price-adapter/src/binance/websocket.rs index 797cda03..95befbd5 100644 --- a/price-adapter/src/binance/websocket.rs +++ b/price-adapter/src/binance/websocket.rs @@ -1,10 +1,11 @@ -use crate::mapper::types::Mapper; -use crate::mapper::BandStaticMapper; +use crate::mapper::{types::Mapper, BandStaticMapper}; +use crate::stable_coin::{types::StableCoin, BandStableCoin}; use crate::types::WebsocketMessage; use crate::{error::Error, types::PriceInfo}; use futures_util::{Stream, StreamExt}; -use price_adapter_raw::types::WebsocketMessage as WebsocketMessageRaw; -use price_adapter_raw::BinanceWebsocket as BinanceWebsocketRaw; +use price_adapter_raw::{ + types::WebsocketMessage as WebsocketMessageRaw, BinanceWebsocket as BinanceWebsocketRaw, +}; use std::{ collections::HashMap, pin::Pin, @@ -14,19 +15,22 @@ use std::{ use tokio::sync::Mutex; // Generic struct `BinanceWebsocket` parameterized over a `Mapper` type. -pub struct BinanceWebsocket { +pub struct BinanceWebsocket { + mapper: M, + stable_coin: S, + raw: Option>>, mapping_back: HashMap, - mapper: M, } -impl BinanceWebsocket { +impl BinanceWebsocket { // Constructor for the `BinanceWebsocket` struct. - pub fn new(mapper: M) -> Self { + pub fn new(mapper: M, stable_coin: S) -> Self { Self { + mapper, + stable_coin, raw: None, mapping_back: HashMap::new(), - mapper, } } @@ -75,19 +79,39 @@ impl BinanceWebsocket { .map_err(Error::PriceAdapterRawError) } + pub async fn unsubscribe(&mut self, symbols: &[&str]) -> Result { + let ids: Vec<&str> = symbols + .iter() + .filter_map(|&symbol| self.mapping_back.get(symbol)) + .map(|string_ref| string_ref.as_str()) + .collect(); + + if ids.len() != symbols.len() { + return Err(Error::UnsupportedSymbol); + } + + let raw = self.raw.as_mut().ok_or(Error::Unknown)?; + let mut locked_raw = raw.lock().await; + locked_raw + .unsubscribe(ids.as_slice()) + .await + .map_err(Error::PriceAdapterRawError) + } + pub fn is_connected(&self) -> bool { self.raw.is_some() } } -impl BinanceWebsocket { +impl BinanceWebsocket { pub fn default() -> Result { let mapper = BandStaticMapper::from_source("binance")?; - Ok(Self::new(mapper)) + let stable_coin = BandStableCoin::new(); + Ok(Self::new(mapper, stable_coin)) } } -impl Stream for BinanceWebsocket { +impl Stream for BinanceWebsocket { type Item = Result; fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { @@ -101,32 +125,31 @@ impl Stream for BinanceWebsocket { }; match locked_raw.poll_next_unpin(cx) { - Poll::Ready(Some(message)) => { - let result = match message { - Ok(WebsocketMessageRaw::PriceInfo(price_info_raw)) => { - if let Some(symbol) = self.mapping_back.get(&price_info_raw.id) { - return Poll::Ready(Some(Ok(WebsocketMessage::PriceInfo(PriceInfo { - symbol: symbol.to_string(), - price: price_info_raw.price, - timestamp: price_info_raw.timestamp, - })))); - } - - cx.waker().wake_by_ref(); - return Poll::Pending; - } - Ok(_) => { + Poll::Ready(Some(message)) => match message { + Ok(WebsocketMessageRaw::PriceInfo(price_info_raw)) => { + if let Some(symbol) = self.mapping_back.get(&price_info_raw.id) { + let Ok(usdt_price) = self.stable_coin.get_price("USDT".to_string()) else { + return Poll::Pending; + }; + + Poll::Ready(Some(Ok(WebsocketMessage::PriceInfo(PriceInfo { + symbol: symbol.to_string(), + price: price_info_raw.price / usdt_price, + timestamp: price_info_raw.timestamp, + })))) + } else { cx.waker().wake_by_ref(); - return Poll::Pending; + Poll::Pending } - Err(err) => Poll::Ready(Some(Err(err.into()))), - }; - return result; - } - Poll::Ready(None) => return Poll::Ready(None), - Poll::Pending => { - return Poll::Pending; - } - }; + } + Ok(_) => { + cx.waker().wake_by_ref(); + Poll::Pending + } + Err(err) => Poll::Ready(Some(Err(err.into()))), + }, + Poll::Ready(None) => Poll::Ready(None), + Poll::Pending => Poll::Pending, + } } } diff --git a/price-adapter/src/error.rs b/price-adapter/src/error.rs index 8b21740c..8c5d019a 100644 --- a/price-adapter/src/error.rs +++ b/price-adapter/src/error.rs @@ -19,4 +19,13 @@ pub enum Error { #[error("mapping error")] MappingError, + + #[error("service already started")] + AlreadyStarted, + + #[error("service not connected")] + NotConnected, + + #[error("Not found: {0}")] + NotFound(String), } diff --git a/price-adapter/src/lib.rs b/price-adapter/src/lib.rs index 3fed0063..62ba04da 100644 --- a/price-adapter/src/lib.rs +++ b/price-adapter/src/lib.rs @@ -2,7 +2,8 @@ mod binance; mod coingecko; pub mod error; pub mod mapper; +pub mod stable_coin; pub mod types; -pub use binance::BinanceWebsocket; -pub use coingecko::CoinGecko; +pub use binance::*; +pub use coingecko::*; diff --git a/price-adapter/src/mapper/types.rs b/price-adapter/src/mapper/types.rs index 76ff39f8..053e907d 100644 --- a/price-adapter/src/mapper/types.rs +++ b/price-adapter/src/mapper/types.rs @@ -3,6 +3,6 @@ use serde_json::Value; use std::collections::HashMap; #[async_trait::async_trait] -pub trait Mapper: Send + Sync + Sized + 'static { +pub trait Mapper: Send + Sync + Sized + Unpin + 'static { async fn get_mapping(&self) -> Result<&HashMap, Error>; } diff --git a/price-adapter/src/stable_coin.rs b/price-adapter/src/stable_coin.rs new file mode 100644 index 00000000..0db53ba7 --- /dev/null +++ b/price-adapter/src/stable_coin.rs @@ -0,0 +1,4 @@ +mod band_stable_coin; +pub mod types; + +pub use band_stable_coin::*; diff --git a/price-adapter/src/stable_coin/band_stable_coin.rs b/price-adapter/src/stable_coin/band_stable_coin.rs new file mode 100644 index 00000000..711cd2a7 --- /dev/null +++ b/price-adapter/src/stable_coin/band_stable_coin.rs @@ -0,0 +1,26 @@ +use super::types::StableCoin; +use crate::error::Error; + +// A struct representing a static mapper using a HashMap of String keys to Values. +pub struct BandStableCoin {} + +impl BandStableCoin { + // Constructor to create a new BandStaticMapper from a pre-existing mapping. + pub fn new() -> Self { + Self {} + } +} + +impl Default for BandStableCoin { + fn default() -> Self { + Self::new() + } +} + +// Implementing the Mapper trait for BandStaticMapper. +impl StableCoin for BandStableCoin { + // Retrieve the mapping as a reference, wrapped in a Result. + fn get_price(&self, _symbol: String) -> Result { + Ok(1_f64) + } +} diff --git a/price-adapter/src/stable_coin/types.rs b/price-adapter/src/stable_coin/types.rs new file mode 100644 index 00000000..55a557eb --- /dev/null +++ b/price-adapter/src/stable_coin/types.rs @@ -0,0 +1,5 @@ +use crate::error::Error; + +pub trait StableCoin: Send + Sync + Sized + Unpin + 'static { + fn get_price(&self, symbol: String) -> Result; +} diff --git a/price-adapter/src/types.rs b/price-adapter/src/types.rs index 7a054626..ab2c4a77 100644 --- a/price-adapter/src/types.rs +++ b/price-adapter/src/types.rs @@ -26,6 +26,13 @@ pub trait PriceAdapter: Send + Sync + 'static { async fn get_prices(&self, symbols: &[&str]) -> Vec>; } +#[async_trait::async_trait] +pub trait WebsocketPriceAdapter: Sync + 'static { + async fn connect(&mut self) -> Result<(), Error>; + async fn subscribe(&mut self, symbols: &[&str]) -> Result; + fn is_connected(&self) -> bool; +} + #[derive(Debug, Deserialize)] pub struct SettingResponse { pub data: Value, From e83bcdef4f82ddf9ffce35c00bbd9a4e45d52e1d Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Thu, 23 Nov 2023 14:46:40 +0700 Subject: [PATCH 12/46] add stop --- price-adapter/src/binance/service.rs | 30 +++++++++++++++++++--------- price-adapter/src/types.rs | 3 ++- 2 files changed, 23 insertions(+), 10 deletions(-) diff --git a/price-adapter/src/binance/service.rs b/price-adapter/src/binance/service.rs index 555f6796..952ef446 100644 --- a/price-adapter/src/binance/service.rs +++ b/price-adapter/src/binance/service.rs @@ -5,9 +5,10 @@ use crate::{ error::Error, types::{PriceInfo, WebsocketMessage}, }; +use tokio::{select, sync::Mutex}; + use futures_util::StreamExt; use std::{collections::HashMap, sync::Arc}; -use tokio::sync::Mutex; use tokio_util::sync::CancellationToken; /// A caching object storing prices received from binance websocket. @@ -41,6 +42,7 @@ impl BinanceWebsocketService { drop(locked_socket); let token = CancellationToken::new(); + let cloned_token = token.clone(); let cloned_socket = Arc::clone(&self.socket); let cloned_cached_price = Arc::clone(&self.cached_price); self.cancellation_token = Some(token); @@ -48,16 +50,26 @@ impl BinanceWebsocketService { tokio::spawn(async move { loop { let mut locked_socket = cloned_socket.lock().await; + select! { + _ = cloned_token.cancelled() => { + break; + } + + result = locked_socket.next() => { + drop(locked_socket); - while let Some(result) = locked_socket.next().await { - match result { - Ok(WebsocketMessage::PriceInfo(price_info)) => { - let mut locked_cached_price = cloned_cached_price.lock().await; - locked_cached_price - .insert(price_info.symbol.to_string(), price_info.clone()); + match result { + Some(Ok(WebsocketMessage::PriceInfo(price_info))) => { + let mut locked_cached_price = cloned_cached_price.lock().await; + locked_cached_price.insert(price_info.symbol.to_string(), price_info); + } + Some(Ok(WebsocketMessage::SettingResponse(_response))) => {} + Some(Err(_)) => { + } + None => { + break; + } } - Ok(WebsocketMessage::SettingResponse(_response)) => {} - Err(_) => {} } } } diff --git a/price-adapter/src/types.rs b/price-adapter/src/types.rs index ab2c4a77..eaee5c35 100644 --- a/price-adapter/src/types.rs +++ b/price-adapter/src/types.rs @@ -27,9 +27,10 @@ pub trait PriceAdapter: Send + Sync + 'static { } #[async_trait::async_trait] -pub trait WebsocketPriceAdapter: Sync + 'static { +pub trait WebsocketPriceAdapter: Send + Sync + 'static { async fn connect(&mut self) -> Result<(), Error>; async fn subscribe(&mut self, symbols: &[&str]) -> Result; + async fn unsubscribe(&mut self, symbols: &[&str]) -> Result; fn is_connected(&self) -> bool; } From 3d8731fba0122930e4b572964411cd523a423e17 Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Thu, 23 Nov 2023 14:47:33 +0700 Subject: [PATCH 13/46] trait --- price-adapter/src/binance/websocket.rs | 45 ++++++++++++++++++-------- 1 file changed, 32 insertions(+), 13 deletions(-) diff --git a/price-adapter/src/binance/websocket.rs b/price-adapter/src/binance/websocket.rs index 95befbd5..21cb8cce 100644 --- a/price-adapter/src/binance/websocket.rs +++ b/price-adapter/src/binance/websocket.rs @@ -1,8 +1,8 @@ use crate::mapper::{types::Mapper, BandStaticMapper}; use crate::stable_coin::{types::StableCoin, BandStableCoin}; -use crate::types::WebsocketMessage; +use crate::types::{WebsocketMessage, WebsocketPriceAdapter}; use crate::{error::Error, types::PriceInfo}; -use futures_util::{Stream, StreamExt}; +use futures_util::{stream::FusedStream, Stream, StreamExt}; use price_adapter_raw::{ types::WebsocketMessage as WebsocketMessageRaw, BinanceWebsocket as BinanceWebsocketRaw, }; @@ -21,8 +21,8 @@ pub struct BinanceWebsocket { raw: Option>>, mapping_back: HashMap, + ended: bool, } - impl BinanceWebsocket { // Constructor for the `BinanceWebsocket` struct. pub fn new(mapper: M, stable_coin: S) -> Self { @@ -31,10 +31,14 @@ impl BinanceWebsocket { stable_coin, raw: None, mapping_back: HashMap::new(), + ended: false, } } +} - pub async fn connect(&mut self) -> Result<(), Error> { +#[async_trait::async_trait] +impl WebsocketPriceAdapter for BinanceWebsocket { + async fn connect(&mut self) -> Result<(), Error> { let raw = Arc::new(Mutex::new(BinanceWebsocketRaw::new( "wss://stream.binance.com:9443", ))); @@ -50,7 +54,7 @@ impl BinanceWebsocket { Ok(()) } - pub async fn subscribe(&mut self, symbols: &[&str]) -> Result { + async fn subscribe(&mut self, symbols: &[&str]) -> Result { // Retrieve the symbol-to-id mapping from the provided mapper. let mapping = self.mapper.get_mapping().await?; @@ -73,13 +77,14 @@ impl BinanceWebsocket { let raw = self.raw.as_mut().ok_or(Error::Unknown)?; let mut locked_raw = raw.lock().await; - locked_raw - .subscribe(ids.as_slice()) - .await - .map_err(Error::PriceAdapterRawError) + + let result = locked_raw.subscribe(ids.as_slice()).await; + // .map_err(Error::PriceAdapterRawError); + + Ok(0) } - pub async fn unsubscribe(&mut self, symbols: &[&str]) -> Result { + async fn unsubscribe(&mut self, symbols: &[&str]) -> Result { let ids: Vec<&str> = symbols .iter() .filter_map(|&symbol| self.mapping_back.get(symbol)) @@ -98,7 +103,7 @@ impl BinanceWebsocket { .map_err(Error::PriceAdapterRawError) } - pub fn is_connected(&self) -> bool { + fn is_connected(&self) -> bool { self.raw.is_some() } } @@ -114,7 +119,11 @@ impl BinanceWebsocket { impl Stream for BinanceWebsocket { type Item = Result; - fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + if self.ended { + return Poll::Ready(None); + } + let Some(raw) = &self.raw else { return Poll::Ready(None); }; @@ -148,8 +157,18 @@ impl Stream for BinanceWebsocket { } Err(err) => Poll::Ready(Some(Err(err.into()))), }, - Poll::Ready(None) => Poll::Ready(None), + Poll::Ready(None) => { + drop(locked_raw); + self.ended = true; + Poll::Ready(None) + } Poll::Pending => Poll::Pending, } } } + +impl FusedStream for BinanceWebsocket { + fn is_terminated(&self) -> bool { + self.ended + } +} From 653d9ec1681d95c674250c09a5df25b2d4da2ebb Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Thu, 23 Nov 2023 16:45:39 +0700 Subject: [PATCH 14/46] update --- price-adapter/examples/binance-websocket.rs | 1 + price-adapter/src/binance/service.rs | 1 + price-adapter/src/binance/websocket.rs | 8 ++++---- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/price-adapter/examples/binance-websocket.rs b/price-adapter/examples/binance-websocket.rs index 6f89542f..c48e85c7 100644 --- a/price-adapter/examples/binance-websocket.rs +++ b/price-adapter/examples/binance-websocket.rs @@ -1,4 +1,5 @@ use futures_util::StreamExt; +use price_adapter::types::WebsocketPriceAdapter; use price_adapter::BinanceWebsocket; #[tokio::main] diff --git a/price-adapter/src/binance/service.rs b/price-adapter/src/binance/service.rs index 952ef446..724f63ec 100644 --- a/price-adapter/src/binance/service.rs +++ b/price-adapter/src/binance/service.rs @@ -1,6 +1,7 @@ use super::websocket::BinanceWebsocket; use crate::mapper::types::Mapper; use crate::stable_coin::types::StableCoin; +use crate::types::WebsocketPriceAdapter; use crate::{ error::Error, types::{PriceInfo, WebsocketMessage}, diff --git a/price-adapter/src/binance/websocket.rs b/price-adapter/src/binance/websocket.rs index 21cb8cce..ea901603 100644 --- a/price-adapter/src/binance/websocket.rs +++ b/price-adapter/src/binance/websocket.rs @@ -78,10 +78,10 @@ impl WebsocketPriceAdapter for BinanceWebsocket let raw = self.raw.as_mut().ok_or(Error::Unknown)?; let mut locked_raw = raw.lock().await; - let result = locked_raw.subscribe(ids.as_slice()).await; - // .map_err(Error::PriceAdapterRawError); - - Ok(0) + locked_raw + .subscribe(ids.as_slice()) + .await + .map_err(Error::PriceAdapterRawError) } async fn unsubscribe(&mut self, symbols: &[&str]) -> Result { From 5faf3db9f3d6e096ee1b9060c79df5d577121e58 Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Thu, 23 Nov 2023 17:05:44 +0700 Subject: [PATCH 15/46] add license --- price-adapter/Cargo.toml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/price-adapter/Cargo.toml b/price-adapter/Cargo.toml index b79e291d..0b7136b5 100644 --- a/price-adapter/Cargo.toml +++ b/price-adapter/Cargo.toml @@ -1,7 +1,9 @@ [package] name = "price-adapter" +description = "price-adapter" version = "0.1.0" edition = "2021" +license = "MIT OR Apache-2.0" [dependencies] price-adapter-raw = { version = "0.1.0", path = "../price-adapter-raw" } From a21c119a8a2f6c17b02e18d1e311f871b840fafe Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Thu, 23 Nov 2023 18:12:57 +0700 Subject: [PATCH 16/46] move service out --- .../examples/binance-websocket-service.rs | 2 +- price-adapter/src/binance.rs | 4 +--- price-adapter/src/lib.rs | 1 + price-adapter/src/service.rs | 3 +++ .../{binance/service.rs => service/websocket.rs} | 15 +++++---------- price-adapter/src/types.rs | 10 +++++++++- 6 files changed, 20 insertions(+), 15 deletions(-) create mode 100644 price-adapter/src/service.rs rename price-adapter/src/{binance/service.rs => service/websocket.rs} (89%) diff --git a/price-adapter/examples/binance-websocket-service.rs b/price-adapter/examples/binance-websocket-service.rs index 57a16a97..775509bf 100644 --- a/price-adapter/examples/binance-websocket-service.rs +++ b/price-adapter/examples/binance-websocket-service.rs @@ -1,4 +1,4 @@ -use price_adapter::{BinanceWebsocket, BinanceWebsocketService}; +use price_adapter::BinanceWebsocket; use std::time::Duration; #[tokio::main] diff --git a/price-adapter/src/binance.rs b/price-adapter/src/binance.rs index 7a01bdf9..187b8412 100644 --- a/price-adapter/src/binance.rs +++ b/price-adapter/src/binance.rs @@ -1,5 +1,3 @@ -mod service; mod websocket; -pub use service::BinanceWebsocketService; -pub use websocket::BinanceWebsocket; +pub use websocket::*; diff --git a/price-adapter/src/lib.rs b/price-adapter/src/lib.rs index 62ba04da..e6912323 100644 --- a/price-adapter/src/lib.rs +++ b/price-adapter/src/lib.rs @@ -2,6 +2,7 @@ mod binance; mod coingecko; pub mod error; pub mod mapper; +pub mod service; pub mod stable_coin; pub mod types; diff --git a/price-adapter/src/service.rs b/price-adapter/src/service.rs new file mode 100644 index 00000000..187b8412 --- /dev/null +++ b/price-adapter/src/service.rs @@ -0,0 +1,3 @@ +mod websocket; + +pub use websocket::*; diff --git a/price-adapter/src/binance/service.rs b/price-adapter/src/service/websocket.rs similarity index 89% rename from price-adapter/src/binance/service.rs rename to price-adapter/src/service/websocket.rs index 724f63ec..82c180fb 100644 --- a/price-adapter/src/binance/service.rs +++ b/price-adapter/src/service/websocket.rs @@ -1,27 +1,22 @@ -use super::websocket::BinanceWebsocket; -use crate::mapper::types::Mapper; -use crate::stable_coin::types::StableCoin; use crate::types::WebsocketPriceAdapter; use crate::{ error::Error, types::{PriceInfo, WebsocketMessage}, }; -use tokio::{select, sync::Mutex}; - -use futures_util::StreamExt; use std::{collections::HashMap, sync::Arc}; +use tokio::{select, sync::Mutex}; use tokio_util::sync::CancellationToken; /// A caching object storing prices received from binance websocket. -pub struct BinanceWebsocketService { - socket: Arc>>, +pub struct WebsocketService { + socket: Arc>, cached_price: Arc>>, cancellation_token: Option, } -impl BinanceWebsocketService { +impl WebsocketService { /// initiate new object from created socket. - pub fn new(socket: BinanceWebsocket) -> Self { + pub fn new(socket: W) -> Self { Self { socket: Arc::new(Mutex::new(socket)), cached_price: Arc::new(Mutex::new(HashMap::new())), diff --git a/price-adapter/src/types.rs b/price-adapter/src/types.rs index eaee5c35..d3e286ea 100644 --- a/price-adapter/src/types.rs +++ b/price-adapter/src/types.rs @@ -1,3 +1,4 @@ +use futures_util::{stream::FusedStream, Stream, StreamExt}; use serde::Deserialize; use serde_json::Value; @@ -27,13 +28,20 @@ pub trait PriceAdapter: Send + Sync + 'static { } #[async_trait::async_trait] -pub trait WebsocketPriceAdapter: Send + Sync + 'static { +pub trait WebsocketPriceAdapter: Send + Sync + StreamExt + FusedStream + Unpin + 'static { async fn connect(&mut self) -> Result<(), Error>; async fn subscribe(&mut self, symbols: &[&str]) -> Result; async fn unsubscribe(&mut self, symbols: &[&str]) -> Result; fn is_connected(&self) -> bool; } +// #[async_trait::async_trait] +// pub trait ServicePriceAdapter: Send + Sync + 'static { +// async fn start(&mut self, symbols: &[&str]) -> Result<(), Error>; +// fn stop(&mut self); +// async fn get_prices(&self, symbols: &[&str]) -> Vec>; +// } + #[derive(Debug, Deserialize)] pub struct SettingResponse { pub data: Value, From 34c069dfc4d9a805d8009b23b934c42a4fba9d0c Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Thu, 23 Nov 2023 23:17:15 +0700 Subject: [PATCH 17/46] implement interval and websocket service --- .../examples/binance-websocket-service.rs | 3 +- .../examples/coingecko-interval-service.rs | 15 +++ price-adapter/src/service.rs | 2 + price-adapter/src/service/interval.rs | 92 +++++++++++++++++++ price-adapter/src/types.rs | 13 +-- 5 files changed, 115 insertions(+), 10 deletions(-) create mode 100644 price-adapter/examples/coingecko-interval-service.rs create mode 100644 price-adapter/src/service/interval.rs diff --git a/price-adapter/examples/binance-websocket-service.rs b/price-adapter/examples/binance-websocket-service.rs index 775509bf..d95cde57 100644 --- a/price-adapter/examples/binance-websocket-service.rs +++ b/price-adapter/examples/binance-websocket-service.rs @@ -1,10 +1,11 @@ +use price_adapter::service::WebsocketService; use price_adapter::BinanceWebsocket; use std::time::Duration; #[tokio::main] async fn main() { let binance_websocket = BinanceWebsocket::default().unwrap(); - let mut service = BinanceWebsocketService::new(binance_websocket); + let mut service = WebsocketService::new(binance_websocket); service.start(vec!["BTC"].as_slice()).await.unwrap(); loop { diff --git a/price-adapter/examples/coingecko-interval-service.rs b/price-adapter/examples/coingecko-interval-service.rs new file mode 100644 index 00000000..a6cb3917 --- /dev/null +++ b/price-adapter/examples/coingecko-interval-service.rs @@ -0,0 +1,15 @@ +use price_adapter::service::IntervalService; +use price_adapter::CoinGecko; +use std::time::Duration; + +#[tokio::main] +async fn main() { + let coingecko = CoinGecko::default(None).unwrap(); + let mut service = IntervalService::new(coingecko); + service.start(vec!["BTC"].as_slice(), 20).await.unwrap(); + + loop { + tokio::time::sleep(Duration::from_secs(1)).await; + println!("{:?}", service.get_prices(&["BTC"]).await); + } +} diff --git a/price-adapter/src/service.rs b/price-adapter/src/service.rs index 187b8412..fba4e8a7 100644 --- a/price-adapter/src/service.rs +++ b/price-adapter/src/service.rs @@ -1,3 +1,5 @@ +mod interval; mod websocket; +pub use interval::*; pub use websocket::*; diff --git a/price-adapter/src/service/interval.rs b/price-adapter/src/service/interval.rs new file mode 100644 index 00000000..3eb6360e --- /dev/null +++ b/price-adapter/src/service/interval.rs @@ -0,0 +1,92 @@ +use crate::types::PriceAdapter; +use crate::{error::Error, types::PriceInfo}; +use std::time::Duration; +use std::{collections::HashMap, sync::Arc}; +use tokio::time::sleep; +use tokio::{select, sync::Mutex}; +use tokio_util::sync::CancellationToken; + +/// A caching object storing prices received from binance websocket. +pub struct IntervalService { + adapter: Arc>, + cached_price: Arc>>, + cancellation_token: Option, +} + +impl IntervalService

{ + /// initiate new object from created socket. + pub fn new(adapter: P) -> Self { + Self { + adapter: Arc::new(Mutex::new(adapter)), + cached_price: Arc::new(Mutex::new(HashMap::new())), + cancellation_token: None, + } + } + + /// start a service. + pub async fn start(&mut self, symbols: &[&str], interval_sec: u64) -> Result<(), Error> { + if self.cancellation_token.is_some() { + return Err(Error::AlreadyStarted); + } + + let token = CancellationToken::new(); + let cloned_token = token.clone(); + let cloned_adapter = Arc::clone(&self.adapter); + let cloned_symbols: Vec = symbols.iter().map(|&s| s.to_string()).collect(); + let cloned_cached_price = Arc::clone(&self.cached_price); + let interval_duration = Duration::from_secs(interval_sec); + self.cancellation_token = Some(token); + + tokio::spawn(async move { + loop { + let borrowed_symbols: Vec<&str> = + cloned_symbols.iter().map(|s| s.as_str()).collect(); + let locked_adapter: tokio::sync::MutexGuard<'_, P> = cloned_adapter.lock().await; + select! { + _ = cloned_token.cancelled() => { + break; + } + + prices = locked_adapter.get_prices(borrowed_symbols.as_slice()) => { + drop(locked_adapter); + + for price in prices { + if let Ok(p) = price { + let mut locked_cached_price = cloned_cached_price.lock().await; + locked_cached_price.insert(p.symbol.to_string(), p); + } + } + } + } + + sleep(interval_duration).await; + } + }); + + Ok(()) + } + + /// stop a service. + pub fn stop(&mut self) { + if let Some(token) = &self.cancellation_token { + token.cancel(); + } + self.cancellation_token = None; + } + + pub async fn get_prices(&self, symbols: &[&str]) -> Vec> { + let mut prices = Vec::new(); + let locked_cached_price = self.cached_price.lock().await; + + for &symbol in symbols { + let price = match locked_cached_price.get(&symbol.to_ascii_uppercase()) { + Some(price) => Ok(price.clone()), + None => Err(Error::NotFound(symbol.to_string())), + }; + + prices.push(price); + } + + prices + } +} diff --git a/price-adapter/src/types.rs b/price-adapter/src/types.rs index d3e286ea..cf790959 100644 --- a/price-adapter/src/types.rs +++ b/price-adapter/src/types.rs @@ -1,4 +1,4 @@ -use futures_util::{stream::FusedStream, Stream, StreamExt}; +use futures_util::{stream::FusedStream, StreamExt}; use serde::Deserialize; use serde_json::Value; @@ -28,20 +28,15 @@ pub trait PriceAdapter: Send + Sync + 'static { } #[async_trait::async_trait] -pub trait WebsocketPriceAdapter: Send + Sync + StreamExt + FusedStream + Unpin + 'static { +pub trait WebsocketPriceAdapter: + Send + Sync + StreamExt> + FusedStream + Unpin + 'static +{ async fn connect(&mut self) -> Result<(), Error>; async fn subscribe(&mut self, symbols: &[&str]) -> Result; async fn unsubscribe(&mut self, symbols: &[&str]) -> Result; fn is_connected(&self) -> bool; } -// #[async_trait::async_trait] -// pub trait ServicePriceAdapter: Send + Sync + 'static { -// async fn start(&mut self, symbols: &[&str]) -> Result<(), Error>; -// fn stop(&mut self); -// async fn get_prices(&self, symbols: &[&str]) -> Vec>; -// } - #[derive(Debug, Deserialize)] pub struct SettingResponse { pub data: Value, From 92ec4e7f393491f27691a57bef755774b04fa645 Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Thu, 23 Nov 2023 23:25:00 +0700 Subject: [PATCH 18/46] fix clippy --- price-adapter/examples/binance-websocket-service.rs | 2 +- price-adapter/examples/binance-websocket.rs | 2 +- price-adapter/src/binance/websocket.rs | 2 +- price-adapter/src/service/interval.rs | 8 +++----- 4 files changed, 6 insertions(+), 8 deletions(-) diff --git a/price-adapter/examples/binance-websocket-service.rs b/price-adapter/examples/binance-websocket-service.rs index d95cde57..e9389cc2 100644 --- a/price-adapter/examples/binance-websocket-service.rs +++ b/price-adapter/examples/binance-websocket-service.rs @@ -4,7 +4,7 @@ use std::time::Duration; #[tokio::main] async fn main() { - let binance_websocket = BinanceWebsocket::default().unwrap(); + let binance_websocket = BinanceWebsocket::new_with_default().unwrap(); let mut service = WebsocketService::new(binance_websocket); service.start(vec!["BTC"].as_slice()).await.unwrap(); diff --git a/price-adapter/examples/binance-websocket.rs b/price-adapter/examples/binance-websocket.rs index c48e85c7..be504c00 100644 --- a/price-adapter/examples/binance-websocket.rs +++ b/price-adapter/examples/binance-websocket.rs @@ -4,7 +4,7 @@ use price_adapter::BinanceWebsocket; #[tokio::main] async fn main() { - let mut binance_websocket = BinanceWebsocket::default().unwrap(); + let mut binance_websocket = BinanceWebsocket::new_with_default().unwrap(); let symbols = vec!["ETH", "BTC"]; binance_websocket.connect().await.unwrap(); diff --git a/price-adapter/src/binance/websocket.rs b/price-adapter/src/binance/websocket.rs index ea901603..f7a12ba9 100644 --- a/price-adapter/src/binance/websocket.rs +++ b/price-adapter/src/binance/websocket.rs @@ -109,7 +109,7 @@ impl WebsocketPriceAdapter for BinanceWebsocket } impl BinanceWebsocket { - pub fn default() -> Result { + pub fn new_with_default() -> Result { let mapper = BandStaticMapper::from_source("binance")?; let stable_coin = BandStableCoin::new(); Ok(Self::new(mapper, stable_coin)) diff --git a/price-adapter/src/service/interval.rs b/price-adapter/src/service/interval.rs index 3eb6360e..b0f7edbe 100644 --- a/price-adapter/src/service/interval.rs +++ b/price-adapter/src/service/interval.rs @@ -50,11 +50,9 @@ impl IntervalService

{ prices = locked_adapter.get_prices(borrowed_symbols.as_slice()) => { drop(locked_adapter); - for price in prices { - if let Ok(p) = price { - let mut locked_cached_price = cloned_cached_price.lock().await; - locked_cached_price.insert(p.symbol.to_string(), p); - } + for price in prices.into_iter().flatten() { + let mut locked_cached_price = cloned_cached_price.lock().await; + locked_cached_price.insert(price.symbol.to_string(), price); } } } From 042aa174f297dc2c2b4c085ab03c386a23466768 Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Fri, 24 Nov 2023 00:54:12 +0700 Subject: [PATCH 19/46] adjust structure and refactor --- .../examples/binance-websocket-service.rs | 4 +- price-adapter/examples/binance-websocket.rs | 4 +- price-adapter/examples/coingecko-basic.rs | 4 +- .../examples/coingecko-interval-service.rs | 4 +- price-adapter/src/error.rs | 1 + price-adapter/src/lib.rs | 10 +--- price-adapter/src/mapper/types.rs | 8 --- price-adapter/src/{mapper.rs => mappers.rs} | 1 - .../{mapper => mappers}/band_static_mapper.rs | 14 ++--- price-adapter/src/{service.rs => services.rs} | 0 .../src/{service => services}/interval.rs | 59 ++++++++++--------- .../src/{service => services}/websocket.rs | 58 +++++++++--------- price-adapter/src/sources.rs | 5 ++ price-adapter/src/{ => sources}/binance.rs | 0 .../src/{ => sources}/binance/websocket.rs | 34 +++++++---- price-adapter/src/{ => sources}/coingecko.rs | 15 ++--- price-adapter/src/stable_coin.rs | 1 - .../src/stable_coin/band_stable_coin.rs | 18 +++--- price-adapter/src/stable_coin/types.rs | 5 -- price-adapter/src/types.rs | 58 +++--------------- price-adapter/src/types/mapper.rs | 13 ++++ price-adapter/src/types/response.rs | 46 +++++++++++++++ price-adapter/src/types/source.rs | 44 ++++++++++++++ price-adapter/src/types/stable.rs | 13 ++++ 24 files changed, 248 insertions(+), 171 deletions(-) delete mode 100644 price-adapter/src/mapper/types.rs rename price-adapter/src/{mapper.rs => mappers.rs} (78%) rename price-adapter/src/{mapper => mappers}/band_static_mapper.rs (71%) rename price-adapter/src/{service.rs => services.rs} (100%) rename price-adapter/src/{service => services}/interval.rs (54%) rename price-adapter/src/{service => services}/websocket.rs (58%) create mode 100644 price-adapter/src/sources.rs rename price-adapter/src/{ => sources}/binance.rs (100%) rename price-adapter/src/{ => sources}/binance/websocket.rs (79%) rename price-adapter/src/{ => sources}/coingecko.rs (88%) delete mode 100644 price-adapter/src/stable_coin/types.rs create mode 100644 price-adapter/src/types/mapper.rs create mode 100644 price-adapter/src/types/response.rs create mode 100644 price-adapter/src/types/source.rs create mode 100644 price-adapter/src/types/stable.rs diff --git a/price-adapter/examples/binance-websocket-service.rs b/price-adapter/examples/binance-websocket-service.rs index e9389cc2..6f952e7b 100644 --- a/price-adapter/examples/binance-websocket-service.rs +++ b/price-adapter/examples/binance-websocket-service.rs @@ -1,5 +1,5 @@ -use price_adapter::service::WebsocketService; -use price_adapter::BinanceWebsocket; +use price_adapter::services::WebsocketService; +use price_adapter::sources::BinanceWebsocket; use std::time::Duration; #[tokio::main] diff --git a/price-adapter/examples/binance-websocket.rs b/price-adapter/examples/binance-websocket.rs index be504c00..e6596e07 100644 --- a/price-adapter/examples/binance-websocket.rs +++ b/price-adapter/examples/binance-websocket.rs @@ -1,6 +1,6 @@ use futures_util::StreamExt; -use price_adapter::types::WebsocketPriceAdapter; -use price_adapter::BinanceWebsocket; +use price_adapter::sources::BinanceWebsocket; +use price_adapter::types::WebSocketSource; #[tokio::main] async fn main() { diff --git a/price-adapter/examples/coingecko-basic.rs b/price-adapter/examples/coingecko-basic.rs index fdee0404..cb7e4f62 100644 --- a/price-adapter/examples/coingecko-basic.rs +++ b/price-adapter/examples/coingecko-basic.rs @@ -1,5 +1,5 @@ -use price_adapter::types::PriceAdapter; -use price_adapter::CoinGecko; +use price_adapter::sources::CoinGecko; +use price_adapter::types::HttpSource; #[tokio::main] async fn main() { diff --git a/price-adapter/examples/coingecko-interval-service.rs b/price-adapter/examples/coingecko-interval-service.rs index a6cb3917..4a9657f2 100644 --- a/price-adapter/examples/coingecko-interval-service.rs +++ b/price-adapter/examples/coingecko-interval-service.rs @@ -1,5 +1,5 @@ -use price_adapter::service::IntervalService; -use price_adapter::CoinGecko; +use price_adapter::services::IntervalService; +use price_adapter::sources::CoinGecko; use std::time::Duration; #[tokio::main] diff --git a/price-adapter/src/error.rs b/price-adapter/src/error.rs index 8c5d019a..c553de34 100644 --- a/price-adapter/src/error.rs +++ b/price-adapter/src/error.rs @@ -1,5 +1,6 @@ use thiserror::Error; +/// Custom error type for the application. #[derive(Debug, Error)] pub enum Error { #[error("unknown error")] diff --git a/price-adapter/src/lib.rs b/price-adapter/src/lib.rs index e6912323..541b2f07 100644 --- a/price-adapter/src/lib.rs +++ b/price-adapter/src/lib.rs @@ -1,10 +1,6 @@ -mod binance; -mod coingecko; pub mod error; -pub mod mapper; -pub mod service; +pub mod mappers; +pub mod services; +pub mod sources; pub mod stable_coin; pub mod types; - -pub use binance::*; -pub use coingecko::*; diff --git a/price-adapter/src/mapper/types.rs b/price-adapter/src/mapper/types.rs deleted file mode 100644 index 053e907d..00000000 --- a/price-adapter/src/mapper/types.rs +++ /dev/null @@ -1,8 +0,0 @@ -use crate::error::Error; -use serde_json::Value; -use std::collections::HashMap; - -#[async_trait::async_trait] -pub trait Mapper: Send + Sync + Sized + Unpin + 'static { - async fn get_mapping(&self) -> Result<&HashMap, Error>; -} diff --git a/price-adapter/src/mapper.rs b/price-adapter/src/mappers.rs similarity index 78% rename from price-adapter/src/mapper.rs rename to price-adapter/src/mappers.rs index 714317d1..c6f6e88d 100644 --- a/price-adapter/src/mapper.rs +++ b/price-adapter/src/mappers.rs @@ -1,4 +1,3 @@ mod band_static_mapper; -pub mod types; pub use band_static_mapper::*; diff --git a/price-adapter/src/mapper/band_static_mapper.rs b/price-adapter/src/mappers/band_static_mapper.rs similarity index 71% rename from price-adapter/src/mapper/band_static_mapper.rs rename to price-adapter/src/mappers/band_static_mapper.rs index b0132cc4..f26744c9 100644 --- a/price-adapter/src/mapper/band_static_mapper.rs +++ b/price-adapter/src/mappers/band_static_mapper.rs @@ -1,29 +1,29 @@ -use super::types::Mapper; use crate::error::Error; +use crate::types::Mapper; use serde_json::Value; use std::collections::HashMap; use std::fs::File; use std::io::Read; use std::path::Path; -// A struct representing a static mapper using a HashMap of String keys to Values. +/// A struct representing a static mapper using a HashMap of String keys to Values. pub struct BandStaticMapper { mapping: HashMap, } impl BandStaticMapper { - // Constructor to create a new BandStaticMapper from a pre-existing mapping. + /// Constructor to create a new BandStaticMapper from a pre-existing mapping. pub fn new(mapping: HashMap) -> Self { Self { mapping } } - // Constructor to create a BandStaticMapper from a source file. + /// Constructor to create a BandStaticMapper from a source file. pub fn from_source(source: &str) -> Result { let path = format!("resources/{}.json", source.to_lowercase()); Self::from_path(path) } - // Constructor to create a BandStaticMapper from a file path. + /// Constructor to create a BandStaticMapper from a file path. pub fn from_path>(path: P) -> Result { // Attempt to open the file at the specified path. let mut file = File::open(&path)?; @@ -39,10 +39,10 @@ impl BandStaticMapper { } } -// Implementing the Mapper trait for BandStaticMapper. +/// Implementing the Mapper trait for BandStaticMapper. #[async_trait::async_trait] impl Mapper for BandStaticMapper { - // Retrieve the mapping as a reference, wrapped in a Result. + /// Retrieve the mapping as a reference, wrapped in a Result. async fn get_mapping(&self) -> Result<&HashMap, Error> { Ok(&self.mapping) } diff --git a/price-adapter/src/service.rs b/price-adapter/src/services.rs similarity index 100% rename from price-adapter/src/service.rs rename to price-adapter/src/services.rs diff --git a/price-adapter/src/service/interval.rs b/price-adapter/src/services/interval.rs similarity index 54% rename from price-adapter/src/service/interval.rs rename to price-adapter/src/services/interval.rs index b0f7edbe..096825a4 100644 --- a/price-adapter/src/service/interval.rs +++ b/price-adapter/src/services/interval.rs @@ -1,4 +1,4 @@ -use crate::types::PriceAdapter; +use crate::types::HttpSource; use crate::{error::Error, types::PriceInfo}; use std::time::Duration; use std::{collections::HashMap, sync::Arc}; @@ -6,24 +6,24 @@ use tokio::time::sleep; use tokio::{select, sync::Mutex}; use tokio_util::sync::CancellationToken; -/// A caching object storing prices received from binance websocket. -pub struct IntervalService { - adapter: Arc>, - cached_price: Arc>>, +/// A caching object storing prices received from Binance WebSocket at regular intervals. +pub struct IntervalService { + adapter: Arc>, + cached_prices: Arc>>, cancellation_token: Option, } -impl IntervalService

{ - /// initiate new object from created socket. - pub fn new(adapter: P) -> Self { +impl IntervalService { + /// Creates a new `IntervalService` with the provided HTTP source adapter. + pub fn new(adapter: S) -> Self { Self { adapter: Arc::new(Mutex::new(adapter)), - cached_price: Arc::new(Mutex::new(HashMap::new())), + cached_prices: Arc::new(Mutex::new(HashMap::new())), cancellation_token: None, } } - /// start a service. + /// Starts the service, fetching prices at regular intervals and caching them. pub async fn start(&mut self, symbols: &[&str], interval_sec: u64) -> Result<(), Error> { if self.cancellation_token.is_some() { return Err(Error::AlreadyStarted); @@ -33,7 +33,7 @@ impl IntervalService

{ let cloned_token = token.clone(); let cloned_adapter = Arc::clone(&self.adapter); let cloned_symbols: Vec = symbols.iter().map(|&s| s.to_string()).collect(); - let cloned_cached_price = Arc::clone(&self.cached_price); + let cloned_cached_prices = Arc::clone(&self.cached_prices); let interval_duration = Duration::from_secs(interval_sec); self.cancellation_token = Some(token); @@ -41,18 +41,19 @@ impl IntervalService

{ loop { let borrowed_symbols: Vec<&str> = cloned_symbols.iter().map(|s| s.as_str()).collect(); - let locked_adapter: tokio::sync::MutexGuard<'_, P> = cloned_adapter.lock().await; + let locked_adapter = cloned_adapter.lock().await; + select! { _ = cloned_token.cancelled() => { break; } - prices = locked_adapter.get_prices(borrowed_symbols.as_slice()) => { + prices = locked_adapter.get_prices(&borrowed_symbols) => { drop(locked_adapter); + let mut locked_cached_prices = cloned_cached_prices.lock().await; for price in prices.into_iter().flatten() { - let mut locked_cached_price = cloned_cached_price.lock().await; - locked_cached_price.insert(price.symbol.to_string(), price); + locked_cached_prices.insert(price.symbol.to_string(), price); } } } @@ -64,7 +65,7 @@ impl IntervalService

{ Ok(()) } - /// stop a service. + /// Stops the service, cancelling the interval fetching. pub fn stop(&mut self) { if let Some(token) = &self.cancellation_token { token.cancel(); @@ -72,19 +73,19 @@ impl IntervalService

{ self.cancellation_token = None; } + /// Retrieves prices for the specified symbols from the cached prices. pub async fn get_prices(&self, symbols: &[&str]) -> Vec> { - let mut prices = Vec::new(); - let locked_cached_price = self.cached_price.lock().await; - - for &symbol in symbols { - let price = match locked_cached_price.get(&symbol.to_ascii_uppercase()) { - Some(price) => Ok(price.clone()), - None => Err(Error::NotFound(symbol.to_string())), - }; - - prices.push(price); - } - - prices + let locked_cached_prices = self.cached_prices.lock().await; + symbols + .iter() + .map(|&symbol| { + locked_cached_prices + .get(&symbol.to_ascii_uppercase()) + .map_or_else( + || Err(Error::NotFound(symbol.to_string())), + |price| Ok(price.clone()), + ) + }) + .collect() } } diff --git a/price-adapter/src/service/websocket.rs b/price-adapter/src/services/websocket.rs similarity index 58% rename from price-adapter/src/service/websocket.rs rename to price-adapter/src/services/websocket.rs index 82c180fb..382f0225 100644 --- a/price-adapter/src/service/websocket.rs +++ b/price-adapter/src/services/websocket.rs @@ -1,30 +1,29 @@ -use crate::types::WebsocketPriceAdapter; use crate::{ error::Error, - types::{PriceInfo, WebsocketMessage}, + types::{PriceInfo, WebSocketSource, WebsocketMessage}, }; use std::{collections::HashMap, sync::Arc}; use tokio::{select, sync::Mutex}; use tokio_util::sync::CancellationToken; -/// A caching object storing prices received from binance websocket. -pub struct WebsocketService { - socket: Arc>, - cached_price: Arc>>, +/// A caching object storing prices received from Binance WebSocket. +pub struct WebsocketService { + socket: Arc>, + cached_prices: Arc>>, cancellation_token: Option, } -impl WebsocketService { - /// initiate new object from created socket. - pub fn new(socket: W) -> Self { +impl WebsocketService { + /// Creates a new `WebsocketService` with the provided WebSocket source. + pub fn new(socket: S) -> Self { Self { socket: Arc::new(Mutex::new(socket)), - cached_price: Arc::new(Mutex::new(HashMap::new())), + cached_prices: Arc::new(Mutex::new(HashMap::new())), cancellation_token: None, } } - /// start a service. + /// Starts the service, connecting to the WebSocket and subscribing to symbols. pub async fn start(&mut self, symbols: &[&str]) -> Result<(), Error> { if self.cancellation_token.is_some() { return Err(Error::AlreadyStarted); @@ -40,7 +39,7 @@ impl WebsocketService { let token = CancellationToken::new(); let cloned_token = token.clone(); let cloned_socket = Arc::clone(&self.socket); - let cloned_cached_price = Arc::clone(&self.cached_price); + let cloned_cached_prices = Arc::clone(&self.cached_prices); self.cancellation_token = Some(token); tokio::spawn(async move { @@ -56,12 +55,11 @@ impl WebsocketService { match result { Some(Ok(WebsocketMessage::PriceInfo(price_info))) => { - let mut locked_cached_price = cloned_cached_price.lock().await; - locked_cached_price.insert(price_info.symbol.to_string(), price_info); + let mut locked_cached_prices = cloned_cached_prices.lock().await; + locked_cached_prices.insert(price_info.symbol.to_string(), price_info); } Some(Ok(WebsocketMessage::SettingResponse(_response))) => {} - Some(Err(_)) => { - } + Some(Err(_)) => {} None => { break; } @@ -74,7 +72,7 @@ impl WebsocketService { Ok(()) } - /// stop a service. + /// Stops the service, cancelling the WebSocket subscription. pub fn stop(&mut self) { if let Some(token) = &self.cancellation_token { token.cancel(); @@ -82,19 +80,19 @@ impl WebsocketService { self.cancellation_token = None; } + /// Retrieves prices for the specified symbols from the cached prices. pub async fn get_prices(&self, symbols: &[&str]) -> Vec> { - let mut prices = Vec::new(); - let locked_cached_price = self.cached_price.lock().await; - - for &symbol in symbols { - let price = match locked_cached_price.get(&symbol.to_ascii_uppercase()) { - Some(price) => Ok(price.clone()), - None => Err(Error::NotFound(symbol.to_string())), - }; - - prices.push(price); - } - - prices + let locked_cached_prices = self.cached_prices.lock().await; + symbols + .iter() + .map(|&symbol| { + locked_cached_prices + .get(&symbol.to_ascii_uppercase()) + .map_or_else( + || Err(Error::NotFound(symbol.to_string())), + |price| Ok(price.clone()), + ) + }) + .collect() } } diff --git a/price-adapter/src/sources.rs b/price-adapter/src/sources.rs new file mode 100644 index 00000000..46e9cf16 --- /dev/null +++ b/price-adapter/src/sources.rs @@ -0,0 +1,5 @@ +mod binance; +mod coingecko; + +pub use binance::*; +pub use coingecko::*; diff --git a/price-adapter/src/binance.rs b/price-adapter/src/sources/binance.rs similarity index 100% rename from price-adapter/src/binance.rs rename to price-adapter/src/sources/binance.rs diff --git a/price-adapter/src/binance/websocket.rs b/price-adapter/src/sources/binance/websocket.rs similarity index 79% rename from price-adapter/src/binance/websocket.rs rename to price-adapter/src/sources/binance/websocket.rs index f7a12ba9..040cae37 100644 --- a/price-adapter/src/binance/websocket.rs +++ b/price-adapter/src/sources/binance/websocket.rs @@ -1,6 +1,6 @@ -use crate::mapper::{types::Mapper, BandStaticMapper}; -use crate::stable_coin::{types::StableCoin, BandStableCoin}; -use crate::types::{WebsocketMessage, WebsocketPriceAdapter}; +use crate::mappers::BandStaticMapper; +use crate::stable_coin::BandStableCoin; +use crate::types::{Mapper, SettingResponse, StableCoin, WebSocketSource, WebsocketMessage}; use crate::{error::Error, types::PriceInfo}; use futures_util::{stream::FusedStream, Stream, StreamExt}; use price_adapter_raw::{ @@ -14,17 +14,17 @@ use std::{ }; use tokio::sync::Mutex; -// Generic struct `BinanceWebsocket` parameterized over a `Mapper` type. +/// A generic struct `BinanceWebsocket` parameterized over `Mapper` and `StableCoin` types. pub struct BinanceWebsocket { mapper: M, stable_coin: S, - raw: Option>>, mapping_back: HashMap, ended: bool, } + impl BinanceWebsocket { - // Constructor for the `BinanceWebsocket` struct. + /// Constructor for the `BinanceWebsocket` struct. pub fn new(mapper: M, stable_coin: S) -> Self { Self { mapper, @@ -36,8 +36,10 @@ impl BinanceWebsocket { } } +// Implementing the WebSocketSource trait for BinanceWebsocket. #[async_trait::async_trait] -impl WebsocketPriceAdapter for BinanceWebsocket { +impl WebSocketSource for BinanceWebsocket { + /// Asynchronous function to connect to the WebSocket. async fn connect(&mut self) -> Result<(), Error> { let raw = Arc::new(Mutex::new(BinanceWebsocketRaw::new( "wss://stream.binance.com:9443", @@ -54,6 +56,7 @@ impl WebsocketPriceAdapter for BinanceWebsocket Ok(()) } + /// Asynchronous function to subscribe to symbols. async fn subscribe(&mut self, symbols: &[&str]) -> Result { // Retrieve the symbol-to-id mapping from the provided mapper. let mapping = self.mapper.get_mapping().await?; @@ -84,6 +87,7 @@ impl WebsocketPriceAdapter for BinanceWebsocket .map_err(Error::PriceAdapterRawError) } + /// Asynchronous function to unsubscribe from symbols. async fn unsubscribe(&mut self, symbols: &[&str]) -> Result { let ids: Vec<&str> = symbols .iter() @@ -103,12 +107,15 @@ impl WebsocketPriceAdapter for BinanceWebsocket .map_err(Error::PriceAdapterRawError) } + /// Check if the WebSocket is connected. fn is_connected(&self) -> bool { self.raw.is_some() } } +// Implementing BinanceWebsocket for specific types (BandStaticMapper, BandStableCoin). impl BinanceWebsocket { + /// Constructor for creating a new BinanceWebsocket with default settings. pub fn new_with_default() -> Result { let mapper = BandStaticMapper::from_source("binance")?; let stable_coin = BandStableCoin::new(); @@ -116,6 +123,7 @@ impl BinanceWebsocket { } } +// Implementing Stream for BinanceWebsocket. impl Stream for BinanceWebsocket { type Item = Result; @@ -147,14 +155,16 @@ impl Stream for BinanceWebsocket { timestamp: price_info_raw.timestamp, })))) } else { + // If symbol not found, wake up the waker and return Pending. cx.waker().wake_by_ref(); Poll::Pending } } - Ok(_) => { - cx.waker().wake_by_ref(); - Poll::Pending - } + Ok(WebsocketMessageRaw::SettingResponse(response)) => Poll::Ready(Some(Ok( + WebsocketMessage::SettingResponse(SettingResponse { + data: response.data, + }), + ))), Err(err) => Poll::Ready(Some(Err(err.into()))), }, Poll::Ready(None) => { @@ -167,7 +177,9 @@ impl Stream for BinanceWebsocket { } } +// Implementing FusedStream for BinanceWebsocket. impl FusedStream for BinanceWebsocket { + /// Check if the stream is terminated. fn is_terminated(&self) -> bool { self.ended } diff --git a/price-adapter/src/coingecko.rs b/price-adapter/src/sources/coingecko.rs similarity index 88% rename from price-adapter/src/coingecko.rs rename to price-adapter/src/sources/coingecko.rs index 775d269f..eb155db1 100644 --- a/price-adapter/src/coingecko.rs +++ b/price-adapter/src/sources/coingecko.rs @@ -1,7 +1,7 @@ use crate::error::Error; -use crate::mapper::types::Mapper; -use crate::mapper::BandStaticMapper; -use crate::types::{PriceAdapter, PriceInfo}; +use crate::mappers::BandStaticMapper; +use crate::types::Mapper; +use crate::types::{HttpSource, PriceInfo}; use price_adapter_raw::CoinGecko as CoinGeckoRaw; // Generic struct `CoinGecko` parameterized over a `Mapper` type. @@ -14,8 +14,8 @@ impl CoinGecko { // Constructor for the `CoinGecko` struct. pub fn new(mapper: M, api_key: Option) -> Self { // Initialize `CoinGeckoRaw` based on the presence of an API key. - let raw = if let Some(key) = api_key { - CoinGeckoRaw::new_with_api_key(key) + let raw = if let Some(key) = &api_key { + CoinGeckoRaw::new_with_api_key(key.to_string()) } else { CoinGeckoRaw::new() }; @@ -25,6 +25,7 @@ impl CoinGecko { } impl CoinGecko { + // Constructor for a default `CoinGecko` instance with `BandStaticMapper`. pub fn default(api_key: Option) -> Result { let mapper = BandStaticMapper::from_source("coingecko")?; Ok(Self::new(mapper, api_key)) @@ -32,14 +33,14 @@ impl CoinGecko { } #[async_trait::async_trait] -impl PriceAdapter for CoinGecko { +impl HttpSource for CoinGecko { // Asynchronous function to get prices for symbols. async fn get_prices(&self, symbols: &[&str]) -> Vec> { // Retrieve the symbol-to-id mapping from the provided mapper. let mapping = self.mapper.get_mapping().await; // Match on the result of obtaining the mapping. - if let Ok(mapping) = mapping { + if let Ok(mapping) = &mapping { // Collect symbols with associated ids and indices. let ids_with_index: Vec<(&str, &str, usize)> = symbols .iter() diff --git a/price-adapter/src/stable_coin.rs b/price-adapter/src/stable_coin.rs index 0db53ba7..1c4773ce 100644 --- a/price-adapter/src/stable_coin.rs +++ b/price-adapter/src/stable_coin.rs @@ -1,4 +1,3 @@ mod band_stable_coin; -pub mod types; pub use band_stable_coin::*; diff --git a/price-adapter/src/stable_coin/band_stable_coin.rs b/price-adapter/src/stable_coin/band_stable_coin.rs index 711cd2a7..99987dc2 100644 --- a/price-adapter/src/stable_coin/band_stable_coin.rs +++ b/price-adapter/src/stable_coin/band_stable_coin.rs @@ -1,13 +1,13 @@ -use super::types::StableCoin; use crate::error::Error; +use crate::types::StableCoin; -// A struct representing a static mapper using a HashMap of String keys to Values. -pub struct BandStableCoin {} +/// A struct representing a stable coin with a constant price. +pub struct BandStableCoin; impl BandStableCoin { - // Constructor to create a new BandStaticMapper from a pre-existing mapping. + /// Constructor to create a new BandStableCoin. pub fn new() -> Self { - Self {} + Self } } @@ -17,10 +17,12 @@ impl Default for BandStableCoin { } } -// Implementing the Mapper trait for BandStaticMapper. +// Implementing the StableCoin trait for BandStableCoin. impl StableCoin for BandStableCoin { - // Retrieve the mapping as a reference, wrapped in a Result. + /// Retrieve the price of the stable coin. + /// + /// This method returns a constant value of 1.0 for any symbol. fn get_price(&self, _symbol: String) -> Result { - Ok(1_f64) + Ok(1.0) } } diff --git a/price-adapter/src/stable_coin/types.rs b/price-adapter/src/stable_coin/types.rs deleted file mode 100644 index 55a557eb..00000000 --- a/price-adapter/src/stable_coin/types.rs +++ /dev/null @@ -1,5 +0,0 @@ -use crate::error::Error; - -pub trait StableCoin: Send + Sync + Sized + Unpin + 'static { - fn get_price(&self, symbol: String) -> Result; -} diff --git a/price-adapter/src/types.rs b/price-adapter/src/types.rs index cf790959..7973cc21 100644 --- a/price-adapter/src/types.rs +++ b/price-adapter/src/types.rs @@ -1,49 +1,9 @@ -use futures_util::{stream::FusedStream, StreamExt}; -use serde::Deserialize; -use serde_json::Value; - -use crate::error::Error; -use core::fmt; - -#[derive(Clone, Debug)] -pub struct PriceInfo { - pub symbol: String, - pub price: f64, - pub timestamp: u64, -} - -impl fmt::Display for PriceInfo { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!( - f, - "PriceInfo {{ symbol: {}, price: {}, timestamp: {} }}", - self.symbol, self.price, self.timestamp - ) - } -} - -#[async_trait::async_trait] -pub trait PriceAdapter: Send + Sync + 'static { - async fn get_prices(&self, symbols: &[&str]) -> Vec>; -} - -#[async_trait::async_trait] -pub trait WebsocketPriceAdapter: - Send + Sync + StreamExt> + FusedStream + Unpin + 'static -{ - async fn connect(&mut self) -> Result<(), Error>; - async fn subscribe(&mut self, symbols: &[&str]) -> Result; - async fn unsubscribe(&mut self, symbols: &[&str]) -> Result; - fn is_connected(&self) -> bool; -} - -#[derive(Debug, Deserialize)] -pub struct SettingResponse { - pub data: Value, -} - -#[derive(Debug)] -pub enum WebsocketMessage { - PriceInfo(PriceInfo), - SettingResponse(SettingResponse), -} +mod mapper; +mod response; +mod source; +mod stable; + +pub use mapper::*; +pub use response::*; +pub use source::*; +pub use stable::*; diff --git a/price-adapter/src/types/mapper.rs b/price-adapter/src/types/mapper.rs new file mode 100644 index 00000000..5c9a3d8f --- /dev/null +++ b/price-adapter/src/types/mapper.rs @@ -0,0 +1,13 @@ +use crate::error::Error; +use serde_json::Value; +use std::collections::HashMap; + +#[async_trait::async_trait] +pub trait Mapper: Send + Sync + Sized + Unpin + 'static { + /// Asynchronously retrieves the mapping data. + /// + /// This method is responsible for fetching and returning the mapping data, + /// which is represented as a `HashMap`. It returns a `Result` + /// containing the mapping data or an `Error` if the operation fails. + async fn get_mapping(&self) -> Result<&HashMap, Error>; +} diff --git a/price-adapter/src/types/response.rs b/price-adapter/src/types/response.rs new file mode 100644 index 00000000..039746a2 --- /dev/null +++ b/price-adapter/src/types/response.rs @@ -0,0 +1,46 @@ +use core::fmt; +use serde::Deserialize; +use serde_json::Value; + +/// Represents information about the price of a symbol. +/// +/// This struct is used to store details about the price of a symbol, +/// including the symbol name, the price value, and the timestamp. +#[derive(Clone, Debug)] +pub struct PriceInfo { + pub symbol: String, + pub price: f64, + pub timestamp: u64, +} + +impl fmt::Display for PriceInfo { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "PriceInfo {{ symbol: {}, price: {}, timestamp: {} }}", + self.symbol, self.price, self.timestamp + ) + } +} + +/// Represents the response structure for setting-related data. +/// +/// This struct is used to deserialize JSON responses containing +/// setting-related information. +#[derive(Debug, Deserialize)] +pub struct SettingResponse { + pub data: Value, +} + +/// Represents different types of messages received over a WebSocket connection. +/// +/// This enum encapsulates various types of messages that can be received +/// over a WebSocket connection, such as price information or setting responses. +#[derive(Debug)] +pub enum WebsocketMessage { + /// Represents a message containing price information. + PriceInfo(PriceInfo), + + /// Represents a message containing setting-related data. + SettingResponse(SettingResponse), +} diff --git a/price-adapter/src/types/source.rs b/price-adapter/src/types/source.rs new file mode 100644 index 00000000..776540fa --- /dev/null +++ b/price-adapter/src/types/source.rs @@ -0,0 +1,44 @@ +use crate::error::Error; +use crate::types::{PriceInfo, WebsocketMessage}; +use futures_util::{stream::FusedStream, StreamExt}; + +#[async_trait::async_trait] +/// Represents a source for fetching prices through HTTP requests. +/// +/// This trait defines methods for obtaining price information for a given set +/// of symbols using HTTP requests. Implementors are expected to provide an +/// asynchronous implementation for retrieving prices. +pub trait HttpSource: Send + Sync + 'static { + /// Asynchronously retrieves prices for the specified symbols. + /// + /// This method takes a slice of symbol strings and returns a vector of + /// `Result`. Each result represents the outcome of + /// attempting to fetch price information for a specific symbol. + async fn get_prices(&self, symbols: &[&str]) -> Vec>; +} + +#[async_trait::async_trait] +/// Represents a source for streaming WebSocket messages. +/// +/// This trait defines methods for connecting to a WebSocket, subscribing and +/// unsubscribing to symbols, checking the connection status, and streaming +/// WebSocket messages. +pub trait WebSocketSource: + Send + Sync + StreamExt> + FusedStream + Unpin + 'static +{ + /// Asynchronously establishes a connection to the WebSocket. + async fn connect(&mut self) -> Result<(), Error>; + + /// Asynchronously subscribes to the specified symbols on the WebSocket. + /// + /// Returns the number of symbols successfully subscribed. + async fn subscribe(&mut self, symbols: &[&str]) -> Result; + + /// Asynchronously unsubscribes from the specified symbols on the WebSocket. + /// + /// Returns the number of symbols successfully unsubscribed. + async fn unsubscribe(&mut self, symbols: &[&str]) -> Result; + + /// Checks whether the WebSocket is currently connected. + fn is_connected(&self) -> bool; +} diff --git a/price-adapter/src/types/stable.rs b/price-adapter/src/types/stable.rs new file mode 100644 index 00000000..86f59f12 --- /dev/null +++ b/price-adapter/src/types/stable.rs @@ -0,0 +1,13 @@ +use crate::error::Error; + +/// Trait for interacting with stable coins and retrieving their prices. +/// +/// This trait defines a method for obtaining the price of a stable coin for a given symbol. +pub trait StableCoin: Send + Sync + Sized + Unpin + 'static { + /// Gets the price of the stable coin for the specified symbol. + /// + /// This method takes a symbol representing a stable coin and returns a `Result`, + /// where the `f64` is the price of the stable coin and `Error` represents any error that + /// may occur during the operation. + fn get_price(&self, symbol: String) -> Result; +} From f610364e127161aaf3b1d601ae21c5e5b51e06df Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Fri, 24 Nov 2023 01:00:38 +0700 Subject: [PATCH 20/46] bump version --- Cargo.lock | 2 +- price-adapter/Cargo.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 159339d8..f0448240 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -738,7 +738,7 @@ checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de" [[package]] name = "price-adapter" -version = "0.1.0" +version = "0.1.1" dependencies = [ "async-trait", "futures-util", diff --git a/price-adapter/Cargo.toml b/price-adapter/Cargo.toml index 0b7136b5..a03e5171 100644 --- a/price-adapter/Cargo.toml +++ b/price-adapter/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "price-adapter" description = "price-adapter" -version = "0.1.0" +version = "0.1.1" edition = "2021" license = "MIT OR Apache-2.0" From 9491cafbee4b5ee1b6be2f8d5652fd50f4b4039b Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Fri, 24 Nov 2023 01:06:11 +0700 Subject: [PATCH 21/46] update lock --- Cargo.lock | 68 +++++++++++++++++++++++++++++------------------------- 1 file changed, 37 insertions(+), 31 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index f0448240..c82f11a4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -111,9 +111,9 @@ checksum = "a2bd12c1caf447e69cd4528f47f94d203fd2582878ecb9e9465484c4148a8223" [[package]] name = "cc" -version = "1.0.84" +version = "1.0.83" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f8e7c90afad890484a21653d08b6e209ae34770fb5ee298f9c699fcc1e5c856" +checksum = "f1174fb0b6ec23863f8b971027804a42614e347eafb0a95bf0b12cdae21fc4d0" dependencies = [ "libc", ] @@ -175,9 +175,9 @@ dependencies = [ [[package]] name = "data-encoding" -version = "2.4.0" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c2e66c9d817f1720209181c316d28635c050fa304f9c79e47a520882661b7308" +checksum = "7e962a19be5cfc3f3bf6dd8f61eb50107f356ad6270fbb3ed41476571db78be5" [[package]] name = "digest" @@ -204,11 +204,17 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "equivalent" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5" + [[package]] name = "errno" -version = "0.3.6" +version = "0.3.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7c18ee0ed65a5f1f81cac6b1d213b69c35fa47d4252ad41f1486dbd8226fe36e" +checksum = "f258a7194e7f7c2a7837a8913aeab7fd8c383457034fa20ce4dd3dcb813e8eb8" dependencies = [ "libc", "windows-sys", @@ -243,9 +249,9 @@ checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" [[package]] name = "form_urlencoded" -version = "1.2.0" +version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a62bc1cf6f830c2ec14a513a9fb124d0a213a629668a4186f329db21fe045652" +checksum = "e13624c2627564efccf4934284bdd98cbaa14e79b0b5a141218e507b3a823456" dependencies = [ "percent-encoding", ] @@ -332,9 +338,9 @@ checksum = "6fb8d784f27acf97159b40fc4db5ecd8aa23b9ad5ef69cdd136d3bc80665f0c0" [[package]] name = "h2" -version = "0.3.21" +version = "0.3.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91fc23aa11be92976ef4729127f1a74adf36d8436f7816b185d18df956790833" +checksum = "4d6250322ef6e60f93f9a2162799302cd6f68f79f6e5d85c8c16f14d1d958178" dependencies = [ "bytes", "fnv", @@ -351,9 +357,9 @@ dependencies = [ [[package]] name = "hashbrown" -version = "0.12.3" +version = "0.14.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" +checksum = "f93e7192158dbcda357bdec5fb5788eebf8bbac027f3f33e719d29135ae84156" [[package]] name = "hermit-abi" @@ -457,9 +463,9 @@ dependencies = [ [[package]] name = "idna" -version = "0.4.0" +version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d20d6b07bfbc108882d88ed8e37d39636dcc260e15e30c45e6ba089610b917c" +checksum = "634d9b1461af396cad843f47fdba5597a4f9e6ddd4bfb6ff5d85028c25cb12f6" dependencies = [ "unicode-bidi", "unicode-normalization", @@ -467,11 +473,11 @@ dependencies = [ [[package]] name = "indexmap" -version = "1.9.3" +version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99" +checksum = "d530e1a18b1cb4c484e6e34556a0d948706958449fca0cab753d649f2bce3d1f" dependencies = [ - "autocfg", + "equivalent", "hashbrown", ] @@ -635,9 +641,9 @@ checksum = "dd8b5dd2ae5ed71462c540258bedcb51965123ad7e7ccf4b9a8cafaa4a63576d" [[package]] name = "openssl" -version = "0.10.59" +version = "0.10.60" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a257ad03cd8fb16ad4172fedf8094451e1af1c4b70097636ef2eac9a5f0cc33" +checksum = "79a4c6c3a2b158f7f8f2a2fc5a969fa3a068df6fc9dbb4a43845436e3af7c800" dependencies = [ "bitflags 2.4.1", "cfg-if", @@ -667,9 +673,9 @@ checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf" [[package]] name = "openssl-sys" -version = "0.9.95" +version = "0.9.96" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40a4130519a360279579c2053038317e40eff64d13fd3f004f9e1b72b8a6aaf9" +checksum = "3812c071ba60da8b5677cc12bcb1d42989a65553772897a7e0355545a819838f" dependencies = [ "cc", "libc", @@ -708,9 +714,9 @@ dependencies = [ [[package]] name = "percent-encoding" -version = "2.3.0" +version = "2.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b2a4787296e9989611394c33f193f676704af1686e70b8f8033ab5ba9a35a94" +checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e" [[package]] name = "pin-project-lite" @@ -873,9 +879,9 @@ checksum = "d626bb9dae77e28219937af045c257c28bfd3f69333c512553507f5f9798cb76" [[package]] name = "rustix" -version = "0.38.22" +version = "0.38.25" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "80109a168d9bc0c7f483083244543a6eb0dba02295d33ca268145e6190d6df0c" +checksum = "dc99bc2d4f1fed22595588a013687477aedf3cdcfb26558c559edb67b4d9b22e" dependencies = [ "bitflags 2.4.1", "errno", @@ -930,18 +936,18 @@ dependencies = [ [[package]] name = "serde" -version = "1.0.192" +version = "1.0.193" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bca2a08484b285dcb282d0f67b26cadc0df8b19f8c12502c13d966bf9482f001" +checksum = "25dd9975e68d0cb5aa1120c288333fc98731bd1dd12f561e468ea4728c042b89" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" -version = "1.0.192" +version = "1.0.193" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6c7207fbec9faa48073f3e3074cbe553af6ea512d7c21ba46e434e70ea9fbc1" +checksum = "43576ca501357b9b071ac53cdc7da8ef0cbd9493d8df094cd821777ea6e894d3" dependencies = [ "proc-macro2", "quote", @@ -1311,9 +1317,9 @@ dependencies = [ [[package]] name = "url" -version = "2.4.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "143b538f18257fac9cad154828a57c6bf5157e1aa604d4816b5995bf6de87ae5" +checksum = "31e6302e3bb753d46e83516cae55ae196fc0c309407cf11ab35cc51a4c2a4633" dependencies = [ "form_urlencoded", "idna", From e55d9ad32a6cc0ff9be129e44b6fa4d6f01799ef Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Fri, 24 Nov 2023 15:26:16 +0700 Subject: [PATCH 22/46] fix path --- price-adapter/src/error.rs | 3 +++ .../src/mappers/band_static_mapper.rs | 19 +++++++++++++++++-- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/price-adapter/src/error.rs b/price-adapter/src/error.rs index c553de34..c9fda72f 100644 --- a/price-adapter/src/error.rs +++ b/price-adapter/src/error.rs @@ -18,6 +18,9 @@ pub enum Error { #[error("unsupported symbol")] UnsupportedSymbol, + #[error("unsupported source")] + UnsupportedSource, + #[error("mapping error")] MappingError, diff --git a/price-adapter/src/mappers/band_static_mapper.rs b/price-adapter/src/mappers/band_static_mapper.rs index f26744c9..4b22c776 100644 --- a/price-adapter/src/mappers/band_static_mapper.rs +++ b/price-adapter/src/mappers/band_static_mapper.rs @@ -1,5 +1,6 @@ use crate::error::Error; use crate::types::Mapper; +use include_dir::{include_dir, Dir}; use serde_json::Value; use std::collections::HashMap; use std::fs::File; @@ -19,8 +20,22 @@ impl BandStaticMapper { /// Constructor to create a BandStaticMapper from a source file. pub fn from_source(source: &str) -> Result { - let path = format!("resources/{}.json", source.to_lowercase()); - Self::from_path(path) + let content = match source { + "binance" => Ok(include_str!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../resources/binance.json" + ))), + "coingecko" => Ok(include_str!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../resources/coingecko.json" + ))), + _ => Err(Error::UnsupportedSource), // Add more matches for other sources + }?; + + // Deserialize the JSON content into a HashMap. + let mapping = serde_json::from_str(&content)?; + + Ok(Self { mapping }) } /// Constructor to create a BandStaticMapper from a file path. From ccd12efd70f367ec18c38e16a89249b3ceebd5e8 Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Fri, 24 Nov 2023 15:28:08 +0700 Subject: [PATCH 23/46] fix import source --- Cargo.lock | 2 +- price-adapter/Cargo.toml | 2 +- price-adapter/examples/coingecko-basic.rs | 2 +- price-adapter/examples/coingecko-interval-service.rs | 2 +- price-adapter/src/mappers/band_static_mapper.rs | 1 - price-adapter/src/sources/coingecko.rs | 2 +- 6 files changed, 5 insertions(+), 6 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index c82f11a4..3a8fbe2f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -744,7 +744,7 @@ checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de" [[package]] name = "price-adapter" -version = "0.1.1" +version = "0.1.2" dependencies = [ "async-trait", "futures-util", diff --git a/price-adapter/Cargo.toml b/price-adapter/Cargo.toml index a03e5171..54a49982 100644 --- a/price-adapter/Cargo.toml +++ b/price-adapter/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "price-adapter" description = "price-adapter" -version = "0.1.1" +version = "0.1.2" edition = "2021" license = "MIT OR Apache-2.0" diff --git a/price-adapter/examples/coingecko-basic.rs b/price-adapter/examples/coingecko-basic.rs index cb7e4f62..3763a2d5 100644 --- a/price-adapter/examples/coingecko-basic.rs +++ b/price-adapter/examples/coingecko-basic.rs @@ -3,7 +3,7 @@ use price_adapter::types::HttpSource; #[tokio::main] async fn main() { - let coingecko = CoinGecko::default(None).unwrap(); + let coingecko = CoinGecko::new_with_default(None).unwrap(); let queries = vec!["ETH", "BAND"]; let prices = coingecko.get_prices(&queries).await; println!("prices: {:?}", prices); diff --git a/price-adapter/examples/coingecko-interval-service.rs b/price-adapter/examples/coingecko-interval-service.rs index 4a9657f2..aedf7e93 100644 --- a/price-adapter/examples/coingecko-interval-service.rs +++ b/price-adapter/examples/coingecko-interval-service.rs @@ -4,7 +4,7 @@ use std::time::Duration; #[tokio::main] async fn main() { - let coingecko = CoinGecko::default(None).unwrap(); + let coingecko = CoinGecko::new_with_default(None).unwrap(); let mut service = IntervalService::new(coingecko); service.start(vec!["BTC"].as_slice(), 20).await.unwrap(); diff --git a/price-adapter/src/mappers/band_static_mapper.rs b/price-adapter/src/mappers/band_static_mapper.rs index 4b22c776..d36e7b86 100644 --- a/price-adapter/src/mappers/band_static_mapper.rs +++ b/price-adapter/src/mappers/band_static_mapper.rs @@ -1,6 +1,5 @@ use crate::error::Error; use crate::types::Mapper; -use include_dir::{include_dir, Dir}; use serde_json::Value; use std::collections::HashMap; use std::fs::File; diff --git a/price-adapter/src/sources/coingecko.rs b/price-adapter/src/sources/coingecko.rs index eb155db1..390a814b 100644 --- a/price-adapter/src/sources/coingecko.rs +++ b/price-adapter/src/sources/coingecko.rs @@ -26,7 +26,7 @@ impl CoinGecko { impl CoinGecko { // Constructor for a default `CoinGecko` instance with `BandStaticMapper`. - pub fn default(api_key: Option) -> Result { + pub fn new_with_default(api_key: Option) -> Result { let mapper = BandStaticMapper::from_source("coingecko")?; Ok(Self::new(mapper, api_key)) } From b80782abe9ec1dfceab6dcbf4ff40891f6ddca0f Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Fri, 24 Nov 2023 16:21:06 +0700 Subject: [PATCH 24/46] move resourcses --- {resources => price-adapter/resources}/binance.json | 0 {resources => price-adapter/resources}/coingecko.json | 0 price-adapter/src/mappers/band_static_mapper.rs | 4 ++-- 3 files changed, 2 insertions(+), 2 deletions(-) rename {resources => price-adapter/resources}/binance.json (100%) rename {resources => price-adapter/resources}/coingecko.json (100%) diff --git a/resources/binance.json b/price-adapter/resources/binance.json similarity index 100% rename from resources/binance.json rename to price-adapter/resources/binance.json diff --git a/resources/coingecko.json b/price-adapter/resources/coingecko.json similarity index 100% rename from resources/coingecko.json rename to price-adapter/resources/coingecko.json diff --git a/price-adapter/src/mappers/band_static_mapper.rs b/price-adapter/src/mappers/band_static_mapper.rs index d36e7b86..d6594942 100644 --- a/price-adapter/src/mappers/band_static_mapper.rs +++ b/price-adapter/src/mappers/band_static_mapper.rs @@ -22,11 +22,11 @@ impl BandStaticMapper { let content = match source { "binance" => Ok(include_str!(concat!( env!("CARGO_MANIFEST_DIR"), - "/../resources/binance.json" + "/resources/binance.json" ))), "coingecko" => Ok(include_str!(concat!( env!("CARGO_MANIFEST_DIR"), - "/../resources/coingecko.json" + "/resources/coingecko.json" ))), _ => Err(Error::UnsupportedSource), // Add more matches for other sources }?; From 9ea5e1a488e759959b65c1d1ceae5ca7e5edb0a6 Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Fri, 24 Nov 2023 18:10:19 +0700 Subject: [PATCH 25/46] adjust trait --- .../examples/binance-websocket-service.rs | 1 + price-adapter/examples/coingecko-basic.rs | 2 +- .../examples/coingecko-interval-service.rs | 1 + price-adapter/src/services/interval.rs | 19 +++++++++++++++---- price-adapter/src/services/websocket.rs | 15 +++++++++++++-- price-adapter/src/sources/coingecko.rs | 12 ++++++++++-- price-adapter/src/types/source.rs | 12 ++++++++---- 7 files changed, 49 insertions(+), 13 deletions(-) diff --git a/price-adapter/examples/binance-websocket-service.rs b/price-adapter/examples/binance-websocket-service.rs index 6f952e7b..827d1c85 100644 --- a/price-adapter/examples/binance-websocket-service.rs +++ b/price-adapter/examples/binance-websocket-service.rs @@ -1,5 +1,6 @@ use price_adapter::services::WebsocketService; use price_adapter::sources::BinanceWebsocket; +use price_adapter::types::Source; use std::time::Duration; #[tokio::main] diff --git a/price-adapter/examples/coingecko-basic.rs b/price-adapter/examples/coingecko-basic.rs index 3763a2d5..143fe39b 100644 --- a/price-adapter/examples/coingecko-basic.rs +++ b/price-adapter/examples/coingecko-basic.rs @@ -1,5 +1,5 @@ use price_adapter::sources::CoinGecko; -use price_adapter::types::HttpSource; +use price_adapter::types::Source; #[tokio::main] async fn main() { diff --git a/price-adapter/examples/coingecko-interval-service.rs b/price-adapter/examples/coingecko-interval-service.rs index aedf7e93..b9e9e46a 100644 --- a/price-adapter/examples/coingecko-interval-service.rs +++ b/price-adapter/examples/coingecko-interval-service.rs @@ -1,5 +1,6 @@ use price_adapter::services::IntervalService; use price_adapter::sources::CoinGecko; +use price_adapter::types::Source; use std::time::Duration; #[tokio::main] diff --git a/price-adapter/src/services/interval.rs b/price-adapter/src/services/interval.rs index 096825a4..f2ea7c73 100644 --- a/price-adapter/src/services/interval.rs +++ b/price-adapter/src/services/interval.rs @@ -1,4 +1,4 @@ -use crate::types::HttpSource; +use crate::types::Source; use crate::{error::Error, types::PriceInfo}; use std::time::Duration; use std::{collections::HashMap, sync::Arc}; @@ -7,13 +7,13 @@ use tokio::{select, sync::Mutex}; use tokio_util::sync::CancellationToken; /// A caching object storing prices received from Binance WebSocket at regular intervals. -pub struct IntervalService { +pub struct IntervalService { adapter: Arc>, cached_prices: Arc>>, cancellation_token: Option, } -impl IntervalService { +impl IntervalService { /// Creates a new `IntervalService` with the provided HTTP source adapter. pub fn new(adapter: S) -> Self { Self { @@ -72,9 +72,12 @@ impl IntervalService { } self.cancellation_token = None; } +} +#[async_trait::async_trait] +impl Source for IntervalService { /// Retrieves prices for the specified symbols from the cached prices. - pub async fn get_prices(&self, symbols: &[&str]) -> Vec> { + async fn get_prices(&self, symbols: &[&str]) -> Vec> { let locked_cached_prices = self.cached_prices.lock().await; symbols .iter() @@ -88,4 +91,12 @@ impl IntervalService { }) .collect() } + + // Asynchronous function to get price for a symbol. + async fn get_price(&self, symbol: &str) -> Result { + self.get_prices(&[symbol]) + .await + .pop() + .ok_or(Error::Unknown)? + } } diff --git a/price-adapter/src/services/websocket.rs b/price-adapter/src/services/websocket.rs index 382f0225..14e953c0 100644 --- a/price-adapter/src/services/websocket.rs +++ b/price-adapter/src/services/websocket.rs @@ -1,6 +1,6 @@ use crate::{ error::Error, - types::{PriceInfo, WebSocketSource, WebsocketMessage}, + types::{PriceInfo, Source, WebSocketSource, WebsocketMessage}, }; use std::{collections::HashMap, sync::Arc}; use tokio::{select, sync::Mutex}; @@ -79,9 +79,12 @@ impl WebsocketService { } self.cancellation_token = None; } +} +#[async_trait::async_trait] +impl Source for WebsocketService { /// Retrieves prices for the specified symbols from the cached prices. - pub async fn get_prices(&self, symbols: &[&str]) -> Vec> { + async fn get_prices(&self, symbols: &[&str]) -> Vec> { let locked_cached_prices = self.cached_prices.lock().await; symbols .iter() @@ -95,4 +98,12 @@ impl WebsocketService { }) .collect() } + + // Asynchronous function to get price for a symbol. + async fn get_price(&self, symbol: &str) -> Result { + self.get_prices(&[symbol]) + .await + .pop() + .ok_or(Error::Unknown)? + } } diff --git a/price-adapter/src/sources/coingecko.rs b/price-adapter/src/sources/coingecko.rs index 390a814b..1358c830 100644 --- a/price-adapter/src/sources/coingecko.rs +++ b/price-adapter/src/sources/coingecko.rs @@ -1,7 +1,7 @@ use crate::error::Error; use crate::mappers::BandStaticMapper; use crate::types::Mapper; -use crate::types::{HttpSource, PriceInfo}; +use crate::types::{PriceInfo, Source}; use price_adapter_raw::CoinGecko as CoinGeckoRaw; // Generic struct `CoinGecko` parameterized over a `Mapper` type. @@ -33,7 +33,7 @@ impl CoinGecko { } #[async_trait::async_trait] -impl HttpSource for CoinGecko { +impl Source for CoinGecko { // Asynchronous function to get prices for symbols. async fn get_prices(&self, symbols: &[&str]) -> Vec> { // Retrieve the symbol-to-id mapping from the provided mapper. @@ -83,4 +83,12 @@ impl HttpSource for CoinGecko { symbols.iter().map(|_| Err(Error::MappingError)).collect() } } + + // Asynchronous function to get price for a symbol. + async fn get_price(&self, symbol: &str) -> Result { + self.get_prices(&[symbol]) + .await + .pop() + .ok_or(Error::Unknown)? + } } diff --git a/price-adapter/src/types/source.rs b/price-adapter/src/types/source.rs index 776540fa..d8f49c09 100644 --- a/price-adapter/src/types/source.rs +++ b/price-adapter/src/types/source.rs @@ -6,15 +6,19 @@ use futures_util::{stream::FusedStream, StreamExt}; /// Represents a source for fetching prices through HTTP requests. /// /// This trait defines methods for obtaining price information for a given set -/// of symbols using HTTP requests. Implementors are expected to provide an +/// of symbols. Implementors are expected to provide an /// asynchronous implementation for retrieving prices. -pub trait HttpSource: Send + Sync + 'static { +pub trait Source: Send + Sync + 'static { /// Asynchronously retrieves prices for the specified symbols. /// - /// This method takes a slice of symbol strings and returns a vector of - /// `Result`. Each result represents the outcome of + /// Return a vector of `Result`. Each result represents the outcome of /// attempting to fetch price information for a specific symbol. async fn get_prices(&self, symbols: &[&str]) -> Vec>; + + /// Asynchronously retrieves the price for a specified symbol. + /// + /// Return price information for the specified symbol. + async fn get_price(&self, symbol: &str) -> Result; } #[async_trait::async_trait] From a9bd3ad84e8c2276fba76d0a16e398500f3435f3 Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Sat, 25 Nov 2023 17:40:46 +0700 Subject: [PATCH 26/46] move stable coin to be as a source --- price-adapter/src/error.rs | 3 + price-adapter/src/lib.rs | 1 - .../src/mappers/band_static_mapper.rs | 2 +- price-adapter/src/sources.rs | 2 + price-adapter/src/sources/band_stable_coin.rs | 56 ++++++++++++++++ .../src/sources/binance/websocket.rs | 67 ++++++++++++++----- price-adapter/src/stable_coin.rs | 3 - .../src/stable_coin/band_stable_coin.rs | 28 -------- price-adapter/src/types/source.rs | 2 +- 9 files changed, 113 insertions(+), 51 deletions(-) create mode 100644 price-adapter/src/sources/band_stable_coin.rs delete mode 100644 price-adapter/src/stable_coin.rs delete mode 100644 price-adapter/src/stable_coin/band_stable_coin.rs diff --git a/price-adapter/src/error.rs b/price-adapter/src/error.rs index c9fda72f..1b78c4ca 100644 --- a/price-adapter/src/error.rs +++ b/price-adapter/src/error.rs @@ -32,4 +32,7 @@ pub enum Error { #[error("Not found: {0}")] NotFound(String), + + #[error("system-time error: {0}")] + SystemTimeError(#[from] std::time::SystemTimeError), } diff --git a/price-adapter/src/lib.rs b/price-adapter/src/lib.rs index 541b2f07..e26c154a 100644 --- a/price-adapter/src/lib.rs +++ b/price-adapter/src/lib.rs @@ -2,5 +2,4 @@ pub mod error; pub mod mappers; pub mod services; pub mod sources; -pub mod stable_coin; pub mod types; diff --git a/price-adapter/src/mappers/band_static_mapper.rs b/price-adapter/src/mappers/band_static_mapper.rs index d6594942..10317f5d 100644 --- a/price-adapter/src/mappers/band_static_mapper.rs +++ b/price-adapter/src/mappers/band_static_mapper.rs @@ -32,7 +32,7 @@ impl BandStaticMapper { }?; // Deserialize the JSON content into a HashMap. - let mapping = serde_json::from_str(&content)?; + let mapping = serde_json::from_str(content)?; Ok(Self { mapping }) } diff --git a/price-adapter/src/sources.rs b/price-adapter/src/sources.rs index 46e9cf16..793a4e81 100644 --- a/price-adapter/src/sources.rs +++ b/price-adapter/src/sources.rs @@ -1,5 +1,7 @@ +mod band_stable_coin; mod binance; mod coingecko; +pub use band_stable_coin::*; pub use binance::*; pub use coingecko::*; diff --git a/price-adapter/src/sources/band_stable_coin.rs b/price-adapter/src/sources/band_stable_coin.rs new file mode 100644 index 00000000..d6b2bc38 --- /dev/null +++ b/price-adapter/src/sources/band_stable_coin.rs @@ -0,0 +1,56 @@ +use crate::error::Error; +use crate::types::{PriceInfo, Source}; +use std::time::{SystemTime, UNIX_EPOCH}; + +/// A struct representing a stable coin with a constant price. +pub struct BandStableCoin; + +impl BandStableCoin { + /// Constructor to create a new BandStableCoin. + pub fn new() -> Self { + Self + } +} + +impl Default for BandStableCoin { + fn default() -> Self { + Self::new() + } +} + +// Implementing the StableCoin trait for BandStableCoin. +#[async_trait::async_trait] +impl Source for BandStableCoin { + async fn get_prices(&self, symbols: &[&str]) -> Vec> { + let cur_time = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_err(Error::SystemTimeError); + + match cur_time { + Ok(time) => symbols + .iter() + .map(|symbol| { + Ok(PriceInfo { + symbol: symbol.to_string(), + price: 1_f64, + timestamp: time.as_secs(), + }) + }) + .collect(), + Err(_) => { + return symbols.iter().map(|_| Err(Error::Unknown)).collect(); + } + } + } + + /// Retrieve the price of the stable coin. + /// + /// This method returns a constant value of 1.0 for any symbol. + async fn get_price(&self, symbol: &str) -> Result { + Ok(PriceInfo { + symbol: symbol.to_string(), + price: 1_f64, + timestamp: SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs(), + }) + } +} diff --git a/price-adapter/src/sources/binance/websocket.rs b/price-adapter/src/sources/binance/websocket.rs index 040cae37..4b7565eb 100644 --- a/price-adapter/src/sources/binance/websocket.rs +++ b/price-adapter/src/sources/binance/websocket.rs @@ -1,11 +1,12 @@ use crate::mappers::BandStaticMapper; -use crate::stable_coin::BandStableCoin; -use crate::types::{Mapper, SettingResponse, StableCoin, WebSocketSource, WebsocketMessage}; +use crate::sources::BandStableCoin; +use crate::types::{Mapper, SettingResponse, Source, WebSocketSource, WebsocketMessage}; use crate::{error::Error, types::PriceInfo}; use futures_util::{stream::FusedStream, Stream, StreamExt}; use price_adapter_raw::{ types::WebsocketMessage as WebsocketMessageRaw, BinanceWebsocket as BinanceWebsocketRaw, }; +use std::time::Duration; use std::{ collections::HashMap, pin::Pin, @@ -13,22 +14,28 @@ use std::{ task::{Context, Poll}, }; use tokio::sync::Mutex; +use tokio::time::sleep; /// A generic struct `BinanceWebsocket` parameterized over `Mapper` and `StableCoin` types. -pub struct BinanceWebsocket { +pub struct BinanceWebsocket { mapper: M, - stable_coin: S, + usdt_source: Arc, + usdt_interval: Duration, + + usdt_price: Arc>>, raw: Option>>, mapping_back: HashMap, ended: bool, } -impl BinanceWebsocket { +impl BinanceWebsocket { /// Constructor for the `BinanceWebsocket` struct. - pub fn new(mapper: M, stable_coin: S) -> Self { + pub fn new(mapper: M, usdt_source: S, usdt_interval: Duration) -> Self { Self { mapper, - stable_coin, + usdt_source: Arc::new(usdt_source), + usdt_interval, + usdt_price: Arc::new(Mutex::new(None)), raw: None, mapping_back: HashMap::new(), ended: false, @@ -38,7 +45,7 @@ impl BinanceWebsocket { // Implementing the WebSocketSource trait for BinanceWebsocket. #[async_trait::async_trait] -impl WebSocketSource for BinanceWebsocket { +impl WebSocketSource for BinanceWebsocket { /// Asynchronous function to connect to the WebSocket. async fn connect(&mut self) -> Result<(), Error> { let raw = Arc::new(Mutex::new(BinanceWebsocketRaw::new( @@ -53,6 +60,25 @@ impl WebSocketSource for BinanceWebsocket { self.raw = Some(raw); + let cloned_usdt_source = Arc::clone(&self.usdt_source); + let cloned_usdt_price = Arc::clone(&self.usdt_price); + let cloned_usdt_interval = self.usdt_interval; + + tokio::spawn(async move { + loop { + let price_info = cloned_usdt_source.get_price("USDT").await; + let mut locked_usdt_price = cloned_usdt_price.lock().await; + if let Ok(price) = price_info { + *locked_usdt_price = Some(price); + } else { + *locked_usdt_price = None; + } + drop(locked_usdt_price); + + sleep(cloned_usdt_interval).await; + } + }); + Ok(()) } @@ -118,13 +144,13 @@ impl BinanceWebsocket { /// Constructor for creating a new BinanceWebsocket with default settings. pub fn new_with_default() -> Result { let mapper = BandStaticMapper::from_source("binance")?; - let stable_coin = BandStableCoin::new(); - Ok(Self::new(mapper, stable_coin)) + let band_stable_coin = BandStableCoin::new(); + Ok(Self::new(mapper, band_stable_coin, Duration::from_secs(5))) } } // Implementing Stream for BinanceWebsocket. -impl Stream for BinanceWebsocket { +impl Stream for BinanceWebsocket { type Item = Result; fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { @@ -141,17 +167,24 @@ impl Stream for BinanceWebsocket { return Poll::Pending; }; + let clone_usdt_price = Arc::clone(&self.usdt_price); + let Ok(locked_usdt_price) = clone_usdt_price.try_lock() else { + cx.waker().wake_by_ref(); + return Poll::Pending; + }; + + let Some(usdt_price) = &*locked_usdt_price else { + cx.waker().wake_by_ref(); + return Poll::Pending; + }; + match locked_raw.poll_next_unpin(cx) { Poll::Ready(Some(message)) => match message { Ok(WebsocketMessageRaw::PriceInfo(price_info_raw)) => { if let Some(symbol) = self.mapping_back.get(&price_info_raw.id) { - let Ok(usdt_price) = self.stable_coin.get_price("USDT".to_string()) else { - return Poll::Pending; - }; - Poll::Ready(Some(Ok(WebsocketMessage::PriceInfo(PriceInfo { symbol: symbol.to_string(), - price: price_info_raw.price / usdt_price, + price: price_info_raw.price / usdt_price.price, timestamp: price_info_raw.timestamp, })))) } else { @@ -178,7 +211,7 @@ impl Stream for BinanceWebsocket { } // Implementing FusedStream for BinanceWebsocket. -impl FusedStream for BinanceWebsocket { +impl FusedStream for BinanceWebsocket { /// Check if the stream is terminated. fn is_terminated(&self) -> bool { self.ended diff --git a/price-adapter/src/stable_coin.rs b/price-adapter/src/stable_coin.rs deleted file mode 100644 index 1c4773ce..00000000 --- a/price-adapter/src/stable_coin.rs +++ /dev/null @@ -1,3 +0,0 @@ -mod band_stable_coin; - -pub use band_stable_coin::*; diff --git a/price-adapter/src/stable_coin/band_stable_coin.rs b/price-adapter/src/stable_coin/band_stable_coin.rs deleted file mode 100644 index 99987dc2..00000000 --- a/price-adapter/src/stable_coin/band_stable_coin.rs +++ /dev/null @@ -1,28 +0,0 @@ -use crate::error::Error; -use crate::types::StableCoin; - -/// A struct representing a stable coin with a constant price. -pub struct BandStableCoin; - -impl BandStableCoin { - /// Constructor to create a new BandStableCoin. - pub fn new() -> Self { - Self - } -} - -impl Default for BandStableCoin { - fn default() -> Self { - Self::new() - } -} - -// Implementing the StableCoin trait for BandStableCoin. -impl StableCoin for BandStableCoin { - /// Retrieve the price of the stable coin. - /// - /// This method returns a constant value of 1.0 for any symbol. - fn get_price(&self, _symbol: String) -> Result { - Ok(1.0) - } -} diff --git a/price-adapter/src/types/source.rs b/price-adapter/src/types/source.rs index d8f49c09..96a61f9b 100644 --- a/price-adapter/src/types/source.rs +++ b/price-adapter/src/types/source.rs @@ -8,7 +8,7 @@ use futures_util::{stream::FusedStream, StreamExt}; /// This trait defines methods for obtaining price information for a given set /// of symbols. Implementors are expected to provide an /// asynchronous implementation for retrieving prices. -pub trait Source: Send + Sync + 'static { +pub trait Source: Send + Sync + Unpin + 'static { /// Asynchronously retrieves prices for the specified symbols. /// /// Return a vector of `Result`. Each result represents the outcome of From e5dd8006b9b803961558a1c6251382facc769124 Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Mon, 27 Nov 2023 15:21:35 +0700 Subject: [PATCH 27/46] bump --- Cargo.lock | 2 +- price-adapter/Cargo.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 3a8fbe2f..27679702 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -744,7 +744,7 @@ checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de" [[package]] name = "price-adapter" -version = "0.1.2" +version = "0.1.3" dependencies = [ "async-trait", "futures-util", diff --git a/price-adapter/Cargo.toml b/price-adapter/Cargo.toml index 54a49982..61f01330 100644 --- a/price-adapter/Cargo.toml +++ b/price-adapter/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "price-adapter" description = "price-adapter" -version = "0.1.2" +version = "0.1.3" edition = "2021" license = "MIT OR Apache-2.0" From 1c5a8a0f6c20339dd006e7be1e0dab0c4e07bd95 Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Tue, 28 Nov 2023 13:33:38 +0700 Subject: [PATCH 28/46] fix comment --- price-adapter/src/services/interval.rs | 4 ++-- price-adapter/src/services/websocket.rs | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/price-adapter/src/services/interval.rs b/price-adapter/src/services/interval.rs index f2ea7c73..b3f496c0 100644 --- a/price-adapter/src/services/interval.rs +++ b/price-adapter/src/services/interval.rs @@ -6,7 +6,7 @@ use tokio::time::sleep; use tokio::{select, sync::Mutex}; use tokio_util::sync::CancellationToken; -/// A caching object storing prices received from Binance WebSocket at regular intervals. +/// A caching object storing prices received from Source at regular intervals. pub struct IntervalService { adapter: Arc>, cached_prices: Arc>>, @@ -14,7 +14,7 @@ pub struct IntervalService { } impl IntervalService { - /// Creates a new `IntervalService` with the provided HTTP source adapter. + /// Creates a new `IntervalService` with the provided Source. pub fn new(adapter: S) -> Self { Self { adapter: Arc::new(Mutex::new(adapter)), diff --git a/price-adapter/src/services/websocket.rs b/price-adapter/src/services/websocket.rs index 14e953c0..3c22c470 100644 --- a/price-adapter/src/services/websocket.rs +++ b/price-adapter/src/services/websocket.rs @@ -6,7 +6,7 @@ use std::{collections::HashMap, sync::Arc}; use tokio::{select, sync::Mutex}; use tokio_util::sync::CancellationToken; -/// A caching object storing prices received from Binance WebSocket. +/// A caching object storing prices received from WebSocketSource. pub struct WebsocketService { socket: Arc>, cached_prices: Arc>>, @@ -14,7 +14,7 @@ pub struct WebsocketService { } impl WebsocketService { - /// Creates a new `WebsocketService` with the provided WebSocket source. + /// Creates a new `WebsocketService` with the provided WebSocketSource. pub fn new(socket: S) -> Self { Self { socket: Arc::new(Mutex::new(socket)), From a5b9b6fcfe8054a7059a714bc6852f8dd6ea241d Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Tue, 28 Nov 2023 13:47:38 +0700 Subject: [PATCH 29/46] add serialize, deserialize --- price-adapter/src/types/response.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/price-adapter/src/types/response.rs b/price-adapter/src/types/response.rs index 039746a2..a51749fe 100644 --- a/price-adapter/src/types/response.rs +++ b/price-adapter/src/types/response.rs @@ -1,12 +1,12 @@ use core::fmt; -use serde::Deserialize; +use serde::{Deserialize, Serialize}; use serde_json::Value; /// Represents information about the price of a symbol. /// /// This struct is used to store details about the price of a symbol, /// including the symbol name, the price value, and the timestamp. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, Serialize, Deserialize)] pub struct PriceInfo { pub symbol: String, pub price: f64, From 72ed2108cf6a075e86226685ec326817150a4111 Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Tue, 28 Nov 2023 13:48:36 +0700 Subject: [PATCH 30/46] add se,de --- Cargo.lock | 2 +- price-adapter/Cargo.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 27679702..1c106800 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -744,7 +744,7 @@ checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de" [[package]] name = "price-adapter" -version = "0.1.3" +version = "0.1.4" dependencies = [ "async-trait", "futures-util", diff --git a/price-adapter/Cargo.toml b/price-adapter/Cargo.toml index 61f01330..e3802a3c 100644 --- a/price-adapter/Cargo.toml +++ b/price-adapter/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "price-adapter" description = "price-adapter" -version = "0.1.3" +version = "0.1.4" edition = "2021" license = "MIT OR Apache-2.0" From 37b786525122fc4dfaaf6087cf88100dcb1e0315 Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Wed, 29 Nov 2023 14:17:12 +0700 Subject: [PATCH 31/46] add started function to check status --- Cargo.lock | 2 +- price-adapter/Cargo.toml | 2 +- price-adapter/src/services/interval.rs | 7 ++++++- price-adapter/src/services/websocket.rs | 7 ++++++- 4 files changed, 14 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 1c106800..eead6629 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -744,7 +744,7 @@ checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de" [[package]] name = "price-adapter" -version = "0.1.4" +version = "0.1.5" dependencies = [ "async-trait", "futures-util", diff --git a/price-adapter/Cargo.toml b/price-adapter/Cargo.toml index e3802a3c..aca3ba62 100644 --- a/price-adapter/Cargo.toml +++ b/price-adapter/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "price-adapter" description = "price-adapter" -version = "0.1.4" +version = "0.1.5" edition = "2021" license = "MIT OR Apache-2.0" diff --git a/price-adapter/src/services/interval.rs b/price-adapter/src/services/interval.rs index b3f496c0..db7196eb 100644 --- a/price-adapter/src/services/interval.rs +++ b/price-adapter/src/services/interval.rs @@ -25,7 +25,7 @@ impl IntervalService { /// Starts the service, fetching prices at regular intervals and caching them. pub async fn start(&mut self, symbols: &[&str], interval_sec: u64) -> Result<(), Error> { - if self.cancellation_token.is_some() { + if self.started() { return Err(Error::AlreadyStarted); } @@ -72,6 +72,11 @@ impl IntervalService { } self.cancellation_token = None; } + + // To check if the service is started. + pub fn started(&self) -> bool { + self.cancellation_token.is_some() + } } #[async_trait::async_trait] diff --git a/price-adapter/src/services/websocket.rs b/price-adapter/src/services/websocket.rs index 3c22c470..218ac616 100644 --- a/price-adapter/src/services/websocket.rs +++ b/price-adapter/src/services/websocket.rs @@ -25,7 +25,7 @@ impl WebsocketService { /// Starts the service, connecting to the WebSocket and subscribing to symbols. pub async fn start(&mut self, symbols: &[&str]) -> Result<(), Error> { - if self.cancellation_token.is_some() { + if self.started() { return Err(Error::AlreadyStarted); } @@ -79,6 +79,11 @@ impl WebsocketService { } self.cancellation_token = None; } + + // To check if the service is started. + pub fn started(&self) -> bool { + self.cancellation_token.is_some() + } } #[async_trait::async_trait] From 2498670cabd4efb8eabdf6653394c7445a5d52b1 Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Wed, 29 Nov 2023 15:41:18 +0700 Subject: [PATCH 32/46] add trait service --- Cargo.lock | 2 +- price-adapter/Cargo.toml | 2 +- .../examples/binance-websocket-service.rs | 2 +- .../examples/coingecko-interval-service.rs | 6 +++--- price-adapter/src/services/interval.rs | 17 +++++++++++------ price-adapter/src/services/websocket.rs | 11 +++++++---- price-adapter/src/types.rs | 2 ++ price-adapter/src/types/service.rs | 9 +++++++++ 8 files changed, 35 insertions(+), 16 deletions(-) create mode 100644 price-adapter/src/types/service.rs diff --git a/Cargo.lock b/Cargo.lock index eead6629..571680a8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -744,7 +744,7 @@ checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de" [[package]] name = "price-adapter" -version = "0.1.5" +version = "0.1.6" dependencies = [ "async-trait", "futures-util", diff --git a/price-adapter/Cargo.toml b/price-adapter/Cargo.toml index aca3ba62..6a437bfb 100644 --- a/price-adapter/Cargo.toml +++ b/price-adapter/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "price-adapter" description = "price-adapter" -version = "0.1.5" +version = "0.1.6" edition = "2021" license = "MIT OR Apache-2.0" diff --git a/price-adapter/examples/binance-websocket-service.rs b/price-adapter/examples/binance-websocket-service.rs index 827d1c85..e79425c1 100644 --- a/price-adapter/examples/binance-websocket-service.rs +++ b/price-adapter/examples/binance-websocket-service.rs @@ -1,6 +1,6 @@ use price_adapter::services::WebsocketService; use price_adapter::sources::BinanceWebsocket; -use price_adapter::types::Source; +use price_adapter::types::{Service, Source}; use std::time::Duration; #[tokio::main] diff --git a/price-adapter/examples/coingecko-interval-service.rs b/price-adapter/examples/coingecko-interval-service.rs index b9e9e46a..5b1e6748 100644 --- a/price-adapter/examples/coingecko-interval-service.rs +++ b/price-adapter/examples/coingecko-interval-service.rs @@ -1,13 +1,13 @@ use price_adapter::services::IntervalService; use price_adapter::sources::CoinGecko; -use price_adapter::types::Source; +use price_adapter::types::{Service, Source}; use std::time::Duration; #[tokio::main] async fn main() { let coingecko = CoinGecko::new_with_default(None).unwrap(); - let mut service = IntervalService::new(coingecko); - service.start(vec!["BTC"].as_slice(), 20).await.unwrap(); + let mut service = IntervalService::new(coingecko, Duration::from_secs(20)); + service.start(vec!["BTC"].as_slice()).await.unwrap(); loop { tokio::time::sleep(Duration::from_secs(1)).await; diff --git a/price-adapter/src/services/interval.rs b/price-adapter/src/services/interval.rs index db7196eb..5ae44b85 100644 --- a/price-adapter/src/services/interval.rs +++ b/price-adapter/src/services/interval.rs @@ -1,4 +1,4 @@ -use crate::types::Source; +use crate::types::{Service, Source}; use crate::{error::Error, types::PriceInfo}; use std::time::Duration; use std::{collections::HashMap, sync::Arc}; @@ -9,22 +9,27 @@ use tokio_util::sync::CancellationToken; /// A caching object storing prices received from Source at regular intervals. pub struct IntervalService { adapter: Arc>, + interval: Duration, cached_prices: Arc>>, cancellation_token: Option, } impl IntervalService { /// Creates a new `IntervalService` with the provided Source. - pub fn new(adapter: S) -> Self { + pub fn new(adapter: S, interval: Duration) -> Self { Self { adapter: Arc::new(Mutex::new(adapter)), + interval, cached_prices: Arc::new(Mutex::new(HashMap::new())), cancellation_token: None, } } +} +#[async_trait::async_trait] +impl Service for IntervalService { /// Starts the service, fetching prices at regular intervals and caching them. - pub async fn start(&mut self, symbols: &[&str], interval_sec: u64) -> Result<(), Error> { + async fn start(&mut self, symbols: &[&str]) -> Result<(), Error> { if self.started() { return Err(Error::AlreadyStarted); } @@ -34,7 +39,7 @@ impl IntervalService { let cloned_adapter = Arc::clone(&self.adapter); let cloned_symbols: Vec = symbols.iter().map(|&s| s.to_string()).collect(); let cloned_cached_prices = Arc::clone(&self.cached_prices); - let interval_duration = Duration::from_secs(interval_sec); + let interval_duration = self.interval.clone(); self.cancellation_token = Some(token); tokio::spawn(async move { @@ -66,7 +71,7 @@ impl IntervalService { } /// Stops the service, cancelling the interval fetching. - pub fn stop(&mut self) { + fn stop(&mut self) { if let Some(token) = &self.cancellation_token { token.cancel(); } @@ -74,7 +79,7 @@ impl IntervalService { } // To check if the service is started. - pub fn started(&self) -> bool { + fn started(&self) -> bool { self.cancellation_token.is_some() } } diff --git a/price-adapter/src/services/websocket.rs b/price-adapter/src/services/websocket.rs index 218ac616..62a1cbab 100644 --- a/price-adapter/src/services/websocket.rs +++ b/price-adapter/src/services/websocket.rs @@ -1,6 +1,6 @@ use crate::{ error::Error, - types::{PriceInfo, Source, WebSocketSource, WebsocketMessage}, + types::{PriceInfo, Service, Source, WebSocketSource, WebsocketMessage}, }; use std::{collections::HashMap, sync::Arc}; use tokio::{select, sync::Mutex}; @@ -22,9 +22,12 @@ impl WebsocketService { cancellation_token: None, } } +} +#[async_trait::async_trait] +impl Service for WebsocketService { /// Starts the service, connecting to the WebSocket and subscribing to symbols. - pub async fn start(&mut self, symbols: &[&str]) -> Result<(), Error> { + async fn start(&mut self, symbols: &[&str]) -> Result<(), Error> { if self.started() { return Err(Error::AlreadyStarted); } @@ -73,7 +76,7 @@ impl WebsocketService { } /// Stops the service, cancelling the WebSocket subscription. - pub fn stop(&mut self) { + fn stop(&mut self) { if let Some(token) = &self.cancellation_token { token.cancel(); } @@ -81,7 +84,7 @@ impl WebsocketService { } // To check if the service is started. - pub fn started(&self) -> bool { + fn started(&self) -> bool { self.cancellation_token.is_some() } } diff --git a/price-adapter/src/types.rs b/price-adapter/src/types.rs index 7973cc21..cef5e767 100644 --- a/price-adapter/src/types.rs +++ b/price-adapter/src/types.rs @@ -1,9 +1,11 @@ mod mapper; mod response; +mod service; mod source; mod stable; pub use mapper::*; pub use response::*; +pub use service::*; pub use source::*; pub use stable::*; diff --git a/price-adapter/src/types/service.rs b/price-adapter/src/types/service.rs new file mode 100644 index 00000000..b1cef1a3 --- /dev/null +++ b/price-adapter/src/types/service.rs @@ -0,0 +1,9 @@ +use crate::error::Error; +use crate::types::Source; + +#[async_trait::async_trait] +pub trait Service: Source { + async fn start(&mut self, symbols: &[&str]) -> Result<(), Error>; + fn stop(&mut self); + fn started(&self) -> bool; +} From f24245ccab978b9762af22fc54e8cd5207cd51b6 Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Wed, 29 Nov 2023 17:12:03 +0700 Subject: [PATCH 33/46] default type --- Cargo.lock | 2 +- price-adapter/Cargo.toml | 2 +- price-adapter/src/sources/binance/websocket.rs | 4 +++- price-adapter/src/sources/coingecko.rs | 4 +++- 4 files changed, 8 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 571680a8..a75d3a3c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -744,7 +744,7 @@ checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de" [[package]] name = "price-adapter" -version = "0.1.6" +version = "0.1.7" dependencies = [ "async-trait", "futures-util", diff --git a/price-adapter/Cargo.toml b/price-adapter/Cargo.toml index 6a437bfb..054b7f16 100644 --- a/price-adapter/Cargo.toml +++ b/price-adapter/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "price-adapter" description = "price-adapter" -version = "0.1.6" +version = "0.1.7" edition = "2021" license = "MIT OR Apache-2.0" diff --git a/price-adapter/src/sources/binance/websocket.rs b/price-adapter/src/sources/binance/websocket.rs index 4b7565eb..525b6357 100644 --- a/price-adapter/src/sources/binance/websocket.rs +++ b/price-adapter/src/sources/binance/websocket.rs @@ -16,6 +16,8 @@ use std::{ use tokio::sync::Mutex; use tokio::time::sleep; +pub type DefaultBinanceWebsocket = BinanceWebsocket; + /// A generic struct `BinanceWebsocket` parameterized over `Mapper` and `StableCoin` types. pub struct BinanceWebsocket { mapper: M, @@ -140,7 +142,7 @@ impl WebSocketSource for BinanceWebsocket { } // Implementing BinanceWebsocket for specific types (BandStaticMapper, BandStableCoin). -impl BinanceWebsocket { +impl DefaultBinanceWebsocket { /// Constructor for creating a new BinanceWebsocket with default settings. pub fn new_with_default() -> Result { let mapper = BandStaticMapper::from_source("binance")?; diff --git a/price-adapter/src/sources/coingecko.rs b/price-adapter/src/sources/coingecko.rs index 1358c830..7d364f76 100644 --- a/price-adapter/src/sources/coingecko.rs +++ b/price-adapter/src/sources/coingecko.rs @@ -4,6 +4,8 @@ use crate::types::Mapper; use crate::types::{PriceInfo, Source}; use price_adapter_raw::CoinGecko as CoinGeckoRaw; +pub type DefaultCoinGecko = CoinGecko; + // Generic struct `CoinGecko` parameterized over a `Mapper` type. pub struct CoinGecko { raw: CoinGeckoRaw, @@ -24,7 +26,7 @@ impl CoinGecko { } } -impl CoinGecko { +impl DefaultCoinGecko { // Constructor for a default `CoinGecko` instance with `BandStaticMapper`. pub fn new_with_default(api_key: Option) -> Result { let mapper = BandStaticMapper::from_source("coingecko")?; From b4f4206216a5994f15210e6e70657db2d22c3597 Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Tue, 2 Jan 2024 15:04:24 +0700 Subject: [PATCH 34/46] fix test --- price-adapter/src/services/interval.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/price-adapter/src/services/interval.rs b/price-adapter/src/services/interval.rs index 5ae44b85..05946ff3 100644 --- a/price-adapter/src/services/interval.rs +++ b/price-adapter/src/services/interval.rs @@ -39,7 +39,7 @@ impl Service for IntervalService { let cloned_adapter = Arc::clone(&self.adapter); let cloned_symbols: Vec = symbols.iter().map(|&s| s.to_string()).collect(); let cloned_cached_prices = Arc::clone(&self.cached_prices); - let interval_duration = self.interval.clone(); + let interval_duration = self.interval self.cancellation_token = Some(token); tokio::spawn(async move { From 203190ccfa7675a684f01a39ef7ac518bdb34617 Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Tue, 2 Jan 2024 15:06:52 +0700 Subject: [PATCH 35/46] fix --- price-adapter/src/services/interval.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/price-adapter/src/services/interval.rs b/price-adapter/src/services/interval.rs index 05946ff3..b92b0f48 100644 --- a/price-adapter/src/services/interval.rs +++ b/price-adapter/src/services/interval.rs @@ -39,7 +39,7 @@ impl Service for IntervalService { let cloned_adapter = Arc::clone(&self.adapter); let cloned_symbols: Vec = symbols.iter().map(|&s| s.to_string()).collect(); let cloned_cached_prices = Arc::clone(&self.cached_prices); - let interval_duration = self.interval + let interval_duration = self.interval; self.cancellation_token = Some(token); tokio::spawn(async move { From 81bacd3a8dc413c6c1d63d7241cc016d681b3ea7 Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Mon, 15 Jan 2024 13:53:27 +0700 Subject: [PATCH 36/46] add gitignore --- .gitignore | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index ea8c4bf7..27ec2d4a 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,17 @@ -/target +# Generated by Cargo +# will have compiled files and executables +debug/ +target/ + +# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries +# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html +**/Cargo.lock + +# These are backup files generated by rustfmt +**/*.rs.bk + +# MSVC Windows builds of rustc generate these, which store debugging information +*.pdb + + +.vscode/ From c036ef3ca194a2da945a1f7b423b0cde1562c110 Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Mon, 15 Jan 2024 16:52:34 +0700 Subject: [PATCH 37/46] update mapper --- price-adapter/resources/binance.json | 131 +++++++++++++++- price-adapter/resources/coingecko.json | 201 ++++++++++++++++++++++++- 2 files changed, 330 insertions(+), 2 deletions(-) diff --git a/price-adapter/resources/binance.json b/price-adapter/resources/binance.json index a6e04053..ba9607bb 100644 --- a/price-adapter/resources/binance.json +++ b/price-adapter/resources/binance.json @@ -1,4 +1,133 @@ { + "1INCH": "1inchusdt", + "AAVE": "aaveusdt", + "ADA": "adausdt", + "ALGO": "algousdt", + "ALPHA": "alphausdt", + "ANKR": "ankrusdt", + "ANT": "antusdt", + "APE": "apeusdt", + "ARB": "arbusdt", + "ARPA": "arpausdt", + "ASTR": "astrusdt", + "ATOM": "atomusdt", + "AUTO": "autousdt", + "AVAX": "avaxusdt", + "AXS": "axsusdt", + "BAL": "balusdt", + "BAND": "bandusdt", + "BAT": "batusdt", + "BCH": "bchusdt", + "BEL": "belusdt", + "BETA": "betausdt", + "BLZ": "blzusdt", + "BNB": "bnbusdt", + "BNT": "bntusdt", "BTC": "btcusdt", - "ETH": "ethusdt" + "BTT": "bttcusdt", + "BUSD": "busdusdt", + "C98": "c98usdt", + "CAKE": "cakeusdt", + "CELO": "celousdt", + "CLV": "clvusdt", + "COMP": "compusdt", + "CRV": "crvusdt", + "CVC": "cvcusdt", + "DASH": "dashusdt", + "DCR": "dcrusdt", + "DOGE": "dogeusdt", + "DOT": "dotusdt", + "DYDX": "dydxusdt", + "EGLD": "egldusdt", + "ENJ": "enjusdt", + "EOS": "eosusdt", + "ETC": "etcusdt", + "ETH": "ethusdt", + "FET": "fetusdt", + "FIL": "filusdt", + "FLOW": "flowusdt", + "FTM": "ftmusdt", + "GLMR": "glmrusdt", + "GMX": "gmxusdt", + "GRT": "grtusdt", + "HBAR": "hbarusdt", + "ICX": "icxusdt", + "ILV": "ilvusdt", + "INJ": "injusdt", + "IOST": "iostusdt", + "IOTX": "iotxusdt", + "JST": "jstusdt", + "KAVA": "kavausdt", + "KDA": "kdausdt", + "KEY": "keyusdt", + "KLAY": "klayusdt", + "KNC": "kncusdt", + "KP3R": "kp3rusdt", + "KSM": "ksmusdt", + "LINK": "linkusdt", + "LRC": "lrcusdt", + "LSK": "lskusdt", + "LTC": "ltcusdt", + "MANA": "manausdt", + "MATIC": "maticusdt", + "MEME": "memeusdt", + "MKR": "mkrusdt", + "MTL": "mtlusdt", + "NEAR": "nearusdt", + "NEO": "neousdt", + "NMR": "nmrusdt", + "OCEAN": "oceanusdt", + "OGN": "ognusdt", + "OMG": "omgusdt", + "ONE": "oneusdt", + "ONT": "ontusdt", + "OP": "opusdt", + "PAXG": "paxgusdt", + "PENDLE": "pendleusdt", + "PEPE": "pepeusdt", + "PNT": "pntusdt", + "POWR": "powrusdt", + "QTUM": "qtumusdt", + "REN": "renusdt", + "REP": "repusdt", + "RLC": "rlcusdt", + "ROSE": "roseusdt", + "RSR": "rsrusdt", + "RUNE": "runeusdt", + "RVN": "rvnusdt", + "SAND": "sandusdt", + "SC": "scusdt", + "SCRT": "scrtusdt", + "SHIB": "shibusdt", + "SKL": "sklusdt", + "SNX": "snxusdt", + "SOL": "solusdt", + "SPELL": "spellusdt", + "SRM": "srmusdt", + "STX": "stxusdt", + "SUN": "sunusdt", + "SUSHI": "sushiusdt", + "SXP": "sxpusdt", + "THETA": "thetausdt", + "TOMO": "tomousdt", + "TRB": "trbusdt", + "TRX": "trxusdt", + "TWT": "twtusdt", + "UMA": "umausdt", + "UNI": "uniusdt", + "VET": "vetusdt", + "WAN": "wanusdt", + "WAVES": "wavesusdt", + "WNXM": "wnxmusdt", + "XLM": "xlmusdt", + "XMR": "xmrusdt", + "XRP": "xrpusdt", + "XTZ": "xtzusdt", + "XVS": "xvsusdt", + "YFI": "yfiusdt", + "YFII": "yfiiusdt", + "YGG": "yggusdt", + "ZEC": "zecusdt", + "ZIL": "zilusdt", + "ZRX": "zrxusdt" } diff --git a/price-adapter/resources/coingecko.json b/price-adapter/resources/coingecko.json index e556df28..07f08780 100644 --- a/price-adapter/resources/coingecko.json +++ b/price-adapter/resources/coingecko.json @@ -1,4 +1,203 @@ { + "1INCH": "1inch", + "AAVE": "aave", + "ABYSS": "the-abyss", + "ADA": "cardano", + "AKRO": "akropolis", + "ALCX": "alchemix", + "ALGO": "algorand", + "ALPHA": "alpha-finance", + "AMPL": "ampleforth", + "ANKR": "ankr", + "ANT": "aragon", + "APE": "apecoin", + "ARB": "arbitrum", + "ARPA": "arpa", + "AST": "airswap", + "ASTR": "astar", + "ATOM": "cosmos", + "AUTO": "auto", + "AVAX": "avalanche-2", + "AXS": "axie-infinity", + "BAL": "balancer", + "BAND": "band-protocol", + "BAT": "basic-attention-token", + "BCH": "bitcoin-cash", + "BEL": "bella-protocol", + "BETA": "beta-finance", + "BETH": "binance-eth", + "BLZ": "bluzelle", + "BNB": "binancecoin", + "BNT": "bancor", + "BOBA": "boba-network", + "BORA": "bora", + "BSV": "bitcoin-cash-sv", "BTC": "bitcoin", - "ETH": "ethereum" + "BTCB": "bitcoin-bep2", + "BTG": "bitcoin-gold", + "BTM": "bytom", + "BTS": "bitshares", + "BTT": "bittorrent", + "BUSD": "binance-usd", + "BZRX": "bzx-protocol", + "C98": "coin98", + "CAKE": "pancakeswap-token", + "CELO": "celo", + "CKB": "nervos-network", + "CLV": "clover-finance", + "COMP": "compound-governance-token", + "CREAM": "cream-2", + "CRO": "crypto-com-chain", + "CRV": "curve-dao-token", + "CUSD": "celo-dollar", + "CVC": "civic", + "DAI": "dai", + "DASH": "dash", + "DCR": "decred", + "DGB": "digibyte", + "DIA": "dia-data", + "DOGE": "dogecoin", + "DOT": "polkadot", + "DPI": "defipulse-index", + "DYDX": "dydx", + "EGLD": "elrond-erd-2", + "ELF": "aelf", + "ENJ": "enjincoin", + "EOS": "eos", + "ETC": "ethereum-classic", + "ETH": "ethereum", + "EURS": "stasis-eurs", + "EWT": "energy-web-token", + "FET": "fetch-ai", + "FIL": "filecoin", + "FLOW": "flow", + "FOR": "force-protocol", + "FRAX": "frax", + "FTM": "fantom", + "GALA": "gala", + "GLMR": "moonbeam", + "GMX": "gmx", + "GNO": "gnosis", + "GRT": "the-graph", + "GMT": "stepn", + "HBAR": "hedera-hashgraph", + "HEGIC": "hegic", + "HNT": "helium", + "HT": "huobi-token", + "ICX": "icon", + "ILV": "illuvium", + "INJ": "injective-protocol", + "IOST": "iostoken", + "IOTX": "iotex", + "JOE": "joe", + "JST": "just", + "KAI": "kardiachain", + "KAVA": "kava", + "KDA": "kadena", + "KEY": "selfkey", + "KLAY": "klay-token", + "KMD": "komodo", + "KNC": "kyber-network-crystal", + "KP3R": "keep3rv1", + "KSM": "kusama", + "LEO": "leo-token", + "LINA": "linear", + "LINK": "chainlink", + "LOOM": "loom-network", + "LRC": "loopring", + "LSK": "lisk", + "LTC": "litecoin", + "MANA": "decentraland", + "MATIC": "matic-network", + "MEME": "memecoin-2", + "MIM": "magic-internet-money", + "MIOTA": "iota", + "MKR": "maker", + "MLN": "melon", + "MOVR": "moonriver", + "MTL": "metal", + "MVL": "mass-vehicle-ledger", + "NEAR": "near", + "NEO": "neo", + "NFT": "apenft", + "NMR": "numeraire", + "OCEAN": "ocean-protocol", + "OGN": "origin-protocol", + "OKB": "okb", + "OMG": "omisego", + "ONE": "harmony", + "ONT": "ontology", + "OP": "optimism", + "OSMO": "osmosis", + "PAXG": "pax-gold", + "PENDLE": "pendle", + "PEPE": "pepe", + "PLR": "pillar", + "PNK": "kleros", + "PNT": "pnetwork", + "POLY": "polymath", + "POWR": "power-ledger", + "QKC": "quark-chain", + "QNT": "quant-network", + "QTUM": "qtum", + "REN": "republic-protocol", + "REP": "augur", + "REQ": "request-network", + "RLC": "iexec-rlc", + "ROSE": "oasis-network", + "RSR": "reserve-rights-token", + "RSV": "reserve", + "RUNE": "thorchain", + "RVN": "ravencoin", + "SAND": "the-sandbox", + "SC": "siacoin", + "SCRT": "secret", + "SFI": "saffron-finance", + "SHIB": "shiba-inu", + "SKL": "skale", + "SNT": "status", + "SNX": "havven", + "SOL": "solana", + "SPELL": "spell-token", + "SRM": "serum", + "STMX": "storm", + "STORJ": "storj", + "STRK": "strike", + "STX": "blockstack", + "SUN": "sun-token", + "SUSD": "nusd", + "SUSHI": "sushi", + "SXP": "swipe", + "THETA": "theta-token", + "TOMO": "tomochain", + "TRB": "tellor", + "TRX": "tron", + "TUSD": "true-usd", + "TWT": "trust-wallet-token", + "UBT": "unibright", + "UMA": "uma", + "UNI": "uniswap", + "UPP": "sentinel-protocol", + "USDC": "usd-coin", + "USDP": "paxos-standard", + "USDT": "tether", + "VET": "vechain", + "VIDT": "v-id-blockchain", + "WAN": "wanchain", + "WAVES": "waves", + "WBTC": "wrapped-bitcoin", + "WNXM": "wrapped-nxm", + "WRX": "wazirx", + "XEM": "nem", + "XLM": "stellar", + "XMR": "monero", + "XRP": "ripple", + "XTZ": "tezos", + "XVS": "venus", + "YFI": "yearn-finance", + "YFII": "yfii-finance", + "YGG": "yield-guild-games", + "ZEC": "zcash", + "ZIL": "zilliqa", + "ZRX": "0x" } From cee56fd4a9119132732b0779b2e904e8802d132c Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Mon, 15 Jan 2024 17:20:41 +0700 Subject: [PATCH 38/46] clean up --- .gitignore | 3 +- Cargo.lock | 1549 ----------------- price-adapter/Cargo.toml | 1 + price-adapter/src/services/interval.rs | 6 +- price-adapter/src/services/websocket.rs | 13 +- .../src/sources/binance/websocket.rs | 32 +- price-adapter/src/types.rs | 2 - price-adapter/src/types/service.rs | 4 +- price-adapter/src/types/source.rs | 2 +- price-adapter/src/types/stable.rs | 13 - 10 files changed, 28 insertions(+), 1597 deletions(-) delete mode 100644 Cargo.lock delete mode 100644 price-adapter/src/types/stable.rs diff --git a/.gitignore b/.gitignore index 27ec2d4a..68afbcf2 100644 --- a/.gitignore +++ b/.gitignore @@ -5,7 +5,7 @@ target/ # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries # More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html -**/Cargo.lock +Cargo.lock # These are backup files generated by rustfmt **/*.rs.bk @@ -15,3 +15,4 @@ target/ .vscode/ + \ No newline at end of file diff --git a/Cargo.lock b/Cargo.lock deleted file mode 100644 index a75d3a3c..00000000 --- a/Cargo.lock +++ /dev/null @@ -1,1549 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -version = 3 - -[[package]] -name = "addr2line" -version = "0.21.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a30b2e23b9e17a9f90641c7ab1549cd9b44f296d3ccbf309d2863cfe398a0cb" -dependencies = [ - "gimli", -] - -[[package]] -name = "adler" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" - -[[package]] -name = "android-tzdata" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e999941b234f3131b00bc13c22d06e8c5ff726d1b6318ac7eb276997bbb4fef0" - -[[package]] -name = "android_system_properties" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" -dependencies = [ - "libc", -] - -[[package]] -name = "async-trait" -version = "0.1.74" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a66537f1bb974b254c98ed142ff995236e81b9d0fe4db0575f46612cb15eb0f9" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "autocfg" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" - -[[package]] -name = "backtrace" -version = "0.3.69" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2089b7e3f35b9dd2d0ed921ead4f6d318c27680d4a5bd167b3ee120edb105837" -dependencies = [ - "addr2line", - "cc", - "cfg-if", - "libc", - "miniz_oxide", - "object", - "rustc-demangle", -] - -[[package]] -name = "base64" -version = "0.21.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "35636a1494ede3b646cc98f74f8e62c773a38a659ebc777a2cf26b9b74171df9" - -[[package]] -name = "bitflags" -version = "1.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" - -[[package]] -name = "bitflags" -version = "2.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "327762f6e5a765692301e5bb513e0d9fef63be86bbc14528052b1cd3e6f03e07" - -[[package]] -name = "block-buffer" -version = "0.10.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" -dependencies = [ - "generic-array", -] - -[[package]] -name = "bumpalo" -version = "3.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f30e7476521f6f8af1a1c4c0b8cc94f0bee37d91763d0ca2665f299b6cd8aec" - -[[package]] -name = "byteorder" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" - -[[package]] -name = "bytes" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a2bd12c1caf447e69cd4528f47f94d203fd2582878ecb9e9465484c4148a8223" - -[[package]] -name = "cc" -version = "1.0.83" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1174fb0b6ec23863f8b971027804a42614e347eafb0a95bf0b12cdae21fc4d0" -dependencies = [ - "libc", -] - -[[package]] -name = "cfg-if" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" - -[[package]] -name = "chrono" -version = "0.4.31" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f2c685bad3eb3d45a01354cedb7d5faa66194d1d58ba6e267a8de788f79db38" -dependencies = [ - "android-tzdata", - "iana-time-zone", - "js-sys", - "num-traits", - "wasm-bindgen", - "windows-targets", -] - -[[package]] -name = "core-foundation" -version = "0.9.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "194a7a9e6de53fa55116934067c844d9d749312f75c6f6d0980e8c252f8c2146" -dependencies = [ - "core-foundation-sys", - "libc", -] - -[[package]] -name = "core-foundation-sys" -version = "0.8.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e496a50fda8aacccc86d7529e2c1e0892dbd0f898a6b5645b5561b89c3210efa" - -[[package]] -name = "cpufeatures" -version = "0.2.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce420fe07aecd3e67c5f910618fe65e94158f6dcc0adf44e00d69ce2bdfe0fd0" -dependencies = [ - "libc", -] - -[[package]] -name = "crypto-common" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3" -dependencies = [ - "generic-array", - "typenum", -] - -[[package]] -name = "data-encoding" -version = "2.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e962a19be5cfc3f3bf6dd8f61eb50107f356ad6270fbb3ed41476571db78be5" - -[[package]] -name = "digest" -version = "0.10.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" -dependencies = [ - "block-buffer", - "crypto-common", -] - -[[package]] -name = "either" -version = "1.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a26ae43d7bcc3b814de94796a5e736d4029efb0ee900c12e2d54c993ad1a1e07" - -[[package]] -name = "encoding_rs" -version = "0.8.33" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7268b386296a025e474d5140678f75d6de9493ae55a5d709eeb9dd08149945e1" -dependencies = [ - "cfg-if", -] - -[[package]] -name = "equivalent" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5" - -[[package]] -name = "errno" -version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f258a7194e7f7c2a7837a8913aeab7fd8c383457034fa20ce4dd3dcb813e8eb8" -dependencies = [ - "libc", - "windows-sys", -] - -[[package]] -name = "fastrand" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25cbce373ec4653f1a01a31e8a5e5ec0c622dc27ff9c4e6606eefef5cbbed4a5" - -[[package]] -name = "fnv" -version = "1.0.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" - -[[package]] -name = "foreign-types" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" -dependencies = [ - "foreign-types-shared", -] - -[[package]] -name = "foreign-types-shared" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" - -[[package]] -name = "form_urlencoded" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e13624c2627564efccf4934284bdd98cbaa14e79b0b5a141218e507b3a823456" -dependencies = [ - "percent-encoding", -] - -[[package]] -name = "futures-channel" -version = "0.3.29" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff4dd66668b557604244583e3e1e1eada8c5c2e96a6d0d6653ede395b78bbacb" -dependencies = [ - "futures-core", -] - -[[package]] -name = "futures-core" -version = "0.3.29" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb1d22c66e66d9d72e1758f0bd7d4fd0bee04cad842ee34587d68c07e45d088c" - -[[package]] -name = "futures-macro" -version = "0.3.29" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53b153fd91e4b0147f4aced87be237c98248656bb01050b96bf3ee89220a8ddb" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "futures-sink" -version = "0.3.29" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e36d3378ee38c2a36ad710c5d30c2911d752cb941c00c72dbabfb786a7970817" - -[[package]] -name = "futures-task" -version = "0.3.29" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "efd193069b0ddadc69c46389b740bbccdd97203899b48d09c5f7969591d6bae2" - -[[package]] -name = "futures-util" -version = "0.3.29" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a19526d624e703a3179b3d322efec918b6246ea0fa51d41124525f00f1cc8104" -dependencies = [ - "futures-core", - "futures-macro", - "futures-sink", - "futures-task", - "pin-project-lite", - "pin-utils", - "slab", -] - -[[package]] -name = "generic-array" -version = "0.14.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" -dependencies = [ - "typenum", - "version_check", -] - -[[package]] -name = "getrandom" -version = "0.2.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fe9006bed769170c11f845cf00c7c1e9092aeb3f268e007c3e760ac68008070f" -dependencies = [ - "cfg-if", - "libc", - "wasi", -] - -[[package]] -name = "gimli" -version = "0.28.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6fb8d784f27acf97159b40fc4db5ecd8aa23b9ad5ef69cdd136d3bc80665f0c0" - -[[package]] -name = "h2" -version = "0.3.22" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4d6250322ef6e60f93f9a2162799302cd6f68f79f6e5d85c8c16f14d1d958178" -dependencies = [ - "bytes", - "fnv", - "futures-core", - "futures-sink", - "futures-util", - "http", - "indexmap", - "slab", - "tokio", - "tokio-util", - "tracing", -] - -[[package]] -name = "hashbrown" -version = "0.14.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f93e7192158dbcda357bdec5fb5788eebf8bbac027f3f33e719d29135ae84156" - -[[package]] -name = "hermit-abi" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d77f7ec81a6d05a3abb01ab6eb7590f6083d08449fe5a1c8b1e620283546ccb7" - -[[package]] -name = "http" -version = "0.2.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8947b1a6fad4393052c7ba1f4cd97bed3e953a95c79c92ad9b051a04611d9fbb" -dependencies = [ - "bytes", - "fnv", - "itoa", -] - -[[package]] -name = "http-body" -version = "0.4.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d5f38f16d184e36f2408a55281cd658ecbd3ca05cce6d6510a176eca393e26d1" -dependencies = [ - "bytes", - "http", - "pin-project-lite", -] - -[[package]] -name = "httparse" -version = "1.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d897f394bad6a705d5f4104762e116a75639e470d80901eed05a860a95cb1904" - -[[package]] -name = "httpdate" -version = "1.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" - -[[package]] -name = "hyper" -version = "0.14.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ffb1cfd654a8219eaef89881fdb3bb3b1cdc5fa75ded05d6933b2b382e395468" -dependencies = [ - "bytes", - "futures-channel", - "futures-core", - "futures-util", - "h2", - "http", - "http-body", - "httparse", - "httpdate", - "itoa", - "pin-project-lite", - "socket2 0.4.10", - "tokio", - "tower-service", - "tracing", - "want", -] - -[[package]] -name = "hyper-tls" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6183ddfa99b85da61a140bea0efc93fdf56ceaa041b37d553518030827f9905" -dependencies = [ - "bytes", - "hyper", - "native-tls", - "tokio", - "tokio-native-tls", -] - -[[package]] -name = "iana-time-zone" -version = "0.1.58" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8326b86b6cff230b97d0d312a6c40a60726df3332e721f72a1b035f451663b20" -dependencies = [ - "android_system_properties", - "core-foundation-sys", - "iana-time-zone-haiku", - "js-sys", - "wasm-bindgen", - "windows-core", -] - -[[package]] -name = "iana-time-zone-haiku" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" -dependencies = [ - "cc", -] - -[[package]] -name = "idna" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "634d9b1461af396cad843f47fdba5597a4f9e6ddd4bfb6ff5d85028c25cb12f6" -dependencies = [ - "unicode-bidi", - "unicode-normalization", -] - -[[package]] -name = "indexmap" -version = "2.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d530e1a18b1cb4c484e6e34556a0d948706958449fca0cab753d649f2bce3d1f" -dependencies = [ - "equivalent", - "hashbrown", -] - -[[package]] -name = "ipnet" -version = "2.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f518f335dce6725a761382244631d86cf0ccb2863413590b31338feb467f9c3" - -[[package]] -name = "itertools" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1c173a5686ce8bfa551b3563d0c2170bf24ca44da99c7ca4bfdab5418c3fe57" -dependencies = [ - "either", -] - -[[package]] -name = "itoa" -version = "1.0.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af150ab688ff2122fcef229be89cb50dd66af9e01a4ff320cc137eecc9bacc38" - -[[package]] -name = "js-sys" -version = "0.3.65" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "54c0c35952f67de54bb584e9fd912b3023117cbafc0a77d8f3dee1fb5f572fe8" -dependencies = [ - "wasm-bindgen", -] - -[[package]] -name = "lazy_static" -version = "1.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" - -[[package]] -name = "libc" -version = "0.2.150" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89d92a4743f9a61002fae18374ed11e7973f530cb3a3255fb354818118b2203c" - -[[package]] -name = "linux-raw-sys" -version = "0.4.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "969488b55f8ac402214f3f5fd243ebb7206cf82de60d3172994707a4bcc2b829" - -[[package]] -name = "lock_api" -version = "0.4.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c168f8615b12bc01f9c17e2eb0cc07dcae1940121185446edc3744920e8ef45" -dependencies = [ - "autocfg", - "scopeguard", -] - -[[package]] -name = "log" -version = "0.4.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5e6163cb8c49088c2c36f57875e58ccd8c87c7427f7fbd50ea6710b2f3f2e8f" - -[[package]] -name = "memchr" -version = "2.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f665ee40bc4a3c5590afb1e9677db74a508659dfd71e126420da8274909a0167" - -[[package]] -name = "mime" -version = "0.3.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" - -[[package]] -name = "miniz_oxide" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7810e0be55b428ada41041c41f32c9f1a42817901b4ccf45fa3d4b6561e74c7" -dependencies = [ - "adler", -] - -[[package]] -name = "mio" -version = "0.8.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3dce281c5e46beae905d4de1870d8b1509a9142b62eedf18b443b011ca8343d0" -dependencies = [ - "libc", - "wasi", - "windows-sys", -] - -[[package]] -name = "native-tls" -version = "0.2.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07226173c32f2926027b63cce4bcd8076c3552846cbe7925f3aaffeac0a3b92e" -dependencies = [ - "lazy_static", - "libc", - "log", - "openssl", - "openssl-probe", - "openssl-sys", - "schannel", - "security-framework", - "security-framework-sys", - "tempfile", -] - -[[package]] -name = "nu-ansi-term" -version = "0.46.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77a8165726e8236064dbb45459242600304b42a5ea24ee2948e18e023bf7ba84" -dependencies = [ - "overload", - "winapi", -] - -[[package]] -name = "num-traits" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39e3200413f237f41ab11ad6d161bc7239c84dcb631773ccd7de3dfe4b5c267c" -dependencies = [ - "autocfg", -] - -[[package]] -name = "num_cpus" -version = "1.16.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4161fcb6d602d4d2081af7c3a45852d875a03dd337a6bfdd6e06407b61342a43" -dependencies = [ - "hermit-abi", - "libc", -] - -[[package]] -name = "object" -version = "0.32.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9cf5f9dd3933bd50a9e1f149ec995f39ae2c496d31fd772c1fd45ebc27e902b0" -dependencies = [ - "memchr", -] - -[[package]] -name = "once_cell" -version = "1.18.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd8b5dd2ae5ed71462c540258bedcb51965123ad7e7ccf4b9a8cafaa4a63576d" - -[[package]] -name = "openssl" -version = "0.10.60" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "79a4c6c3a2b158f7f8f2a2fc5a969fa3a068df6fc9dbb4a43845436e3af7c800" -dependencies = [ - "bitflags 2.4.1", - "cfg-if", - "foreign-types", - "libc", - "once_cell", - "openssl-macros", - "openssl-sys", -] - -[[package]] -name = "openssl-macros" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "openssl-probe" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf" - -[[package]] -name = "openssl-sys" -version = "0.9.96" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3812c071ba60da8b5677cc12bcb1d42989a65553772897a7e0355545a819838f" -dependencies = [ - "cc", - "libc", - "pkg-config", - "vcpkg", -] - -[[package]] -name = "overload" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b15813163c1d831bf4a13c3610c05c0d03b39feb07f7e09fa234dac9b15aaf39" - -[[package]] -name = "parking_lot" -version = "0.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3742b2c103b9f06bc9fff0a37ff4912935851bee6d36f3c02bcc755bcfec228f" -dependencies = [ - "lock_api", - "parking_lot_core", -] - -[[package]] -name = "parking_lot_core" -version = "0.9.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c42a9226546d68acdd9c0a280d17ce19bfe27a46bf68784e4066115788d008e" -dependencies = [ - "cfg-if", - "libc", - "redox_syscall", - "smallvec", - "windows-targets", -] - -[[package]] -name = "percent-encoding" -version = "2.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e" - -[[package]] -name = "pin-project-lite" -version = "0.2.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8afb450f006bf6385ca15ef45d71d2288452bc3683ce2e2cacc0d18e4be60b58" - -[[package]] -name = "pin-utils" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" - -[[package]] -name = "pkg-config" -version = "0.3.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26072860ba924cbfa98ea39c8c19b4dd6a4a25423dbdf219c1eca91aa0cf6964" - -[[package]] -name = "ppv-lite86" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de" - -[[package]] -name = "price-adapter" -version = "0.1.7" -dependencies = [ - "async-trait", - "futures-util", - "price-adapter-raw", - "serde", - "serde_json", - "thiserror", - "tokio", - "tokio-tungstenite", - "tokio-util", -] - -[[package]] -name = "price-adapter-raw" -version = "0.1.0" -dependencies = [ - "chrono", - "futures-util", - "itertools", - "rand", - "reqwest", - "serde", - "serde_json", - "thiserror", - "tokio", - "tokio-tungstenite", - "tokio-util", - "tracing", - "tracing-subscriber", -] - -[[package]] -name = "proc-macro2" -version = "1.0.69" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "134c189feb4956b20f6f547d2cf727d4c0fe06722b20a0eec87ed445a97f92da" -dependencies = [ - "unicode-ident", -] - -[[package]] -name = "quote" -version = "1.0.33" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5267fca4496028628a95160fc423a33e8b2e6af8a5302579e322e4b520293cae" -dependencies = [ - "proc-macro2", -] - -[[package]] -name = "rand" -version = "0.8.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" -dependencies = [ - "libc", - "rand_chacha", - "rand_core", -] - -[[package]] -name = "rand_chacha" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" -dependencies = [ - "ppv-lite86", - "rand_core", -] - -[[package]] -name = "rand_core" -version = "0.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" -dependencies = [ - "getrandom", -] - -[[package]] -name = "redox_syscall" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4722d768eff46b75989dd134e5c353f0d6296e5aaa3132e776cbdb56be7731aa" -dependencies = [ - "bitflags 1.3.2", -] - -[[package]] -name = "reqwest" -version = "0.11.22" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "046cd98826c46c2ac8ddecae268eb5c2e58628688a5fc7a2643704a73faba95b" -dependencies = [ - "base64", - "bytes", - "encoding_rs", - "futures-core", - "futures-util", - "h2", - "http", - "http-body", - "hyper", - "hyper-tls", - "ipnet", - "js-sys", - "log", - "mime", - "native-tls", - "once_cell", - "percent-encoding", - "pin-project-lite", - "serde", - "serde_json", - "serde_urlencoded", - "system-configuration", - "tokio", - "tokio-native-tls", - "tower-service", - "url", - "wasm-bindgen", - "wasm-bindgen-futures", - "web-sys", - "winreg", -] - -[[package]] -name = "rustc-demangle" -version = "0.1.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d626bb9dae77e28219937af045c257c28bfd3f69333c512553507f5f9798cb76" - -[[package]] -name = "rustix" -version = "0.38.25" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc99bc2d4f1fed22595588a013687477aedf3cdcfb26558c559edb67b4d9b22e" -dependencies = [ - "bitflags 2.4.1", - "errno", - "libc", - "linux-raw-sys", - "windows-sys", -] - -[[package]] -name = "ryu" -version = "1.0.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ad4cc8da4ef723ed60bced201181d83791ad433213d8c24efffda1eec85d741" - -[[package]] -name = "schannel" -version = "0.1.22" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c3733bf4cf7ea0880754e19cb5a462007c4a8c1914bff372ccc95b464f1df88" -dependencies = [ - "windows-sys", -] - -[[package]] -name = "scopeguard" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" - -[[package]] -name = "security-framework" -version = "2.9.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05b64fb303737d99b81884b2c63433e9ae28abebe5eb5045dcdd175dc2ecf4de" -dependencies = [ - "bitflags 1.3.2", - "core-foundation", - "core-foundation-sys", - "libc", - "security-framework-sys", -] - -[[package]] -name = "security-framework-sys" -version = "2.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e932934257d3b408ed8f30db49d85ea163bfe74961f017f405b025af298f0c7a" -dependencies = [ - "core-foundation-sys", - "libc", -] - -[[package]] -name = "serde" -version = "1.0.193" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25dd9975e68d0cb5aa1120c288333fc98731bd1dd12f561e468ea4728c042b89" -dependencies = [ - "serde_derive", -] - -[[package]] -name = "serde_derive" -version = "1.0.193" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43576ca501357b9b071ac53cdc7da8ef0cbd9493d8df094cd821777ea6e894d3" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "serde_json" -version = "1.0.108" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d1c7e3eac408d115102c4c24ad393e0821bb3a5df4d506a80f85f7a742a526b" -dependencies = [ - "itoa", - "ryu", - "serde", -] - -[[package]] -name = "serde_urlencoded" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" -dependencies = [ - "form_urlencoded", - "itoa", - "ryu", - "serde", -] - -[[package]] -name = "sha1" -version = "0.10.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba" -dependencies = [ - "cfg-if", - "cpufeatures", - "digest", -] - -[[package]] -name = "sharded-slab" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" -dependencies = [ - "lazy_static", -] - -[[package]] -name = "signal-hook-registry" -version = "1.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d8229b473baa5980ac72ef434c4415e70c4b5e71b423043adb4ba059f89c99a1" -dependencies = [ - "libc", -] - -[[package]] -name = "slab" -version = "0.4.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f92a496fb766b417c996b9c5e57daf2f7ad3b0bebe1ccfca4856390e3d3bb67" -dependencies = [ - "autocfg", -] - -[[package]] -name = "smallvec" -version = "1.11.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4dccd0940a2dcdf68d092b8cbab7dc0ad8fa938bf95787e1b916b0e3d0e8e970" - -[[package]] -name = "socket2" -version = "0.4.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f7916fc008ca5542385b89a3d3ce689953c143e9304a9bf8beec1de48994c0d" -dependencies = [ - "libc", - "winapi", -] - -[[package]] -name = "socket2" -version = "0.5.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b5fac59a5cb5dd637972e5fca70daf0523c9067fcdc4842f053dae04a18f8e9" -dependencies = [ - "libc", - "windows-sys", -] - -[[package]] -name = "syn" -version = "2.0.39" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23e78b90f2fcf45d3e842032ce32e3f2d1545ba6636271dcbf24fa306d87be7a" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "system-configuration" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba3a3adc5c275d719af8cb4272ea1c4a6d668a777f37e115f6d11ddbc1c8e0e7" -dependencies = [ - "bitflags 1.3.2", - "core-foundation", - "system-configuration-sys", -] - -[[package]] -name = "system-configuration-sys" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a75fb188eb626b924683e3b95e3a48e63551fcfb51949de2f06a9d91dbee93c9" -dependencies = [ - "core-foundation-sys", - "libc", -] - -[[package]] -name = "tempfile" -version = "3.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ef1adac450ad7f4b3c28589471ade84f25f731a7a0fe30d71dfa9f60fd808e5" -dependencies = [ - "cfg-if", - "fastrand", - "redox_syscall", - "rustix", - "windows-sys", -] - -[[package]] -name = "thiserror" -version = "1.0.50" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9a7210f5c9a7156bb50aa36aed4c95afb51df0df00713949448cf9e97d382d2" -dependencies = [ - "thiserror-impl", -] - -[[package]] -name = "thiserror-impl" -version = "1.0.50" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "266b2e40bc00e5a6c09c3584011e08b06f123c00362c92b975ba9843aaaa14b8" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "thread_local" -version = "1.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3fdd6f064ccff2d6567adcb3873ca630700f00b5ad3f060c25b5dcfd9a4ce152" -dependencies = [ - "cfg-if", - "once_cell", -] - -[[package]] -name = "tinyvec" -version = "1.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87cc5ceb3875bb20c2890005a4e226a4651264a5c75edb2421b52861a0a0cb50" -dependencies = [ - "tinyvec_macros", -] - -[[package]] -name = "tinyvec_macros" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" - -[[package]] -name = "tokio" -version = "1.34.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d0c014766411e834f7af5b8f4cf46257aab4036ca95e9d2c144a10f59ad6f5b9" -dependencies = [ - "backtrace", - "bytes", - "libc", - "mio", - "num_cpus", - "parking_lot", - "pin-project-lite", - "signal-hook-registry", - "socket2 0.5.5", - "tokio-macros", - "windows-sys", -] - -[[package]] -name = "tokio-macros" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b8a1e28f2deaa14e508979454cb3a223b10b938b45af148bc0986de36f1923b" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "tokio-native-tls" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbae76ab933c85776efabc971569dd6119c580d8f5d448769dec1764bf796ef2" -dependencies = [ - "native-tls", - "tokio", -] - -[[package]] -name = "tokio-tungstenite" -version = "0.20.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "212d5dcb2a1ce06d81107c3d0ffa3121fe974b73f068c8282cb1c32328113b6c" -dependencies = [ - "futures-util", - "log", - "native-tls", - "tokio", - "tokio-native-tls", - "tungstenite", -] - -[[package]] -name = "tokio-util" -version = "0.7.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5419f34732d9eb6ee4c3578b7989078579b7f039cbbb9ca2c4da015749371e15" -dependencies = [ - "bytes", - "futures-core", - "futures-sink", - "pin-project-lite", - "tokio", - "tracing", -] - -[[package]] -name = "tower-service" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6bc1c9ce2b5135ac7f93c72918fc37feb872bdc6a5533a8b85eb4b86bfdae52" - -[[package]] -name = "tracing" -version = "0.1.40" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3523ab5a71916ccf420eebdf5521fcef02141234bbc0b8a49f2fdc4544364ef" -dependencies = [ - "pin-project-lite", - "tracing-attributes", - "tracing-core", -] - -[[package]] -name = "tracing-attributes" -version = "0.1.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34704c8d6ebcbc939824180af020566b01a7c01f80641264eba0999f6c2b6be7" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "tracing-core" -version = "0.1.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c06d3da6113f116aaee68e4d601191614c9053067f9ab7f6edbcb161237daa54" -dependencies = [ - "once_cell", - "valuable", -] - -[[package]] -name = "tracing-log" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" -dependencies = [ - "log", - "once_cell", - "tracing-core", -] - -[[package]] -name = "tracing-subscriber" -version = "0.3.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad0f048c97dbd9faa9b7df56362b8ebcaa52adb06b498c050d2f4e32f90a7a8b" -dependencies = [ - "nu-ansi-term", - "sharded-slab", - "smallvec", - "thread_local", - "tracing-core", - "tracing-log", -] - -[[package]] -name = "try-lock" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3528ecfd12c466c6f163363caf2d02a71161dd5e1cc6ae7b34207ea2d42d81ed" - -[[package]] -name = "tungstenite" -version = "0.20.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e3dac10fd62eaf6617d3a904ae222845979aec67c615d1c842b4002c7666fb9" -dependencies = [ - "byteorder", - "bytes", - "data-encoding", - "http", - "httparse", - "log", - "native-tls", - "rand", - "sha1", - "thiserror", - "url", - "utf-8", -] - -[[package]] -name = "typenum" -version = "1.17.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42ff0bf0c66b8238c6f3b578df37d0b7848e55df8577b3f74f92a69acceeb825" - -[[package]] -name = "unicode-bidi" -version = "0.3.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92888ba5573ff080736b3648696b70cafad7d250551175acbaa4e0385b3e1460" - -[[package]] -name = "unicode-ident" -version = "1.0.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" - -[[package]] -name = "unicode-normalization" -version = "0.1.22" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c5713f0fc4b5db668a2ac63cdb7bb4469d8c9fed047b1d0292cc7b0ce2ba921" -dependencies = [ - "tinyvec", -] - -[[package]] -name = "url" -version = "2.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "31e6302e3bb753d46e83516cae55ae196fc0c309407cf11ab35cc51a4c2a4633" -dependencies = [ - "form_urlencoded", - "idna", - "percent-encoding", -] - -[[package]] -name = "utf-8" -version = "0.7.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9" - -[[package]] -name = "valuable" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "830b7e5d4d90034032940e4ace0d9a9a057e7a45cd94e6c007832e39edb82f6d" - -[[package]] -name = "vcpkg" -version = "0.2.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" - -[[package]] -name = "version_check" -version = "0.9.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" - -[[package]] -name = "want" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" -dependencies = [ - "try-lock", -] - -[[package]] -name = "wasi" -version = "0.11.0+wasi-snapshot-preview1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" - -[[package]] -name = "wasm-bindgen" -version = "0.2.88" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7daec296f25a1bae309c0cd5c29c4b260e510e6d813c286b19eaadf409d40fce" -dependencies = [ - "cfg-if", - "wasm-bindgen-macro", -] - -[[package]] -name = "wasm-bindgen-backend" -version = "0.2.88" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e397f4664c0e4e428e8313a469aaa58310d302159845980fd23b0f22a847f217" -dependencies = [ - "bumpalo", - "log", - "once_cell", - "proc-macro2", - "quote", - "syn", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-futures" -version = "0.4.38" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9afec9963e3d0994cac82455b2b3502b81a7f40f9a0d32181f7528d9f4b43e02" -dependencies = [ - "cfg-if", - "js-sys", - "wasm-bindgen", - "web-sys", -] - -[[package]] -name = "wasm-bindgen-macro" -version = "0.2.88" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5961017b3b08ad5f3fe39f1e79877f8ee7c23c5e5fd5eb80de95abc41f1f16b2" -dependencies = [ - "quote", - "wasm-bindgen-macro-support", -] - -[[package]] -name = "wasm-bindgen-macro-support" -version = "0.2.88" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c5353b8dab669f5e10f5bd76df26a9360c748f054f862ff5f3f8aae0c7fb3907" -dependencies = [ - "proc-macro2", - "quote", - "syn", - "wasm-bindgen-backend", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-shared" -version = "0.2.88" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d046c5d029ba91a1ed14da14dca44b68bf2f124cfbaf741c54151fdb3e0750b" - -[[package]] -name = "web-sys" -version = "0.3.65" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5db499c5f66323272151db0e666cd34f78617522fb0c1604d31a27c50c206a85" -dependencies = [ - "js-sys", - "wasm-bindgen", -] - -[[package]] -name = "winapi" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" -dependencies = [ - "winapi-i686-pc-windows-gnu", - "winapi-x86_64-pc-windows-gnu", -] - -[[package]] -name = "winapi-i686-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" - -[[package]] -name = "winapi-x86_64-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" - -[[package]] -name = "windows-core" -version = "0.51.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1f8cf84f35d2db49a46868f947758c7a1138116f7fac3bc844f43ade1292e64" -dependencies = [ - "windows-targets", -] - -[[package]] -name = "windows-sys" -version = "0.48.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" -dependencies = [ - "windows-targets", -] - -[[package]] -name = "windows-targets" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" -dependencies = [ - "windows_aarch64_gnullvm", - "windows_aarch64_msvc", - "windows_i686_gnu", - "windows_i686_msvc", - "windows_x86_64_gnu", - "windows_x86_64_gnullvm", - "windows_x86_64_msvc", -] - -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" - -[[package]] -name = "windows_aarch64_msvc" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" - -[[package]] -name = "windows_i686_gnu" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" - -[[package]] -name = "windows_i686_msvc" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" - -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" - -[[package]] -name = "winreg" -version = "0.50.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "524e57b2c537c0f9b1e69f1965311ec12182b4122e45035b1508cd24d2adadb1" -dependencies = [ - "cfg-if", - "windows-sys", -] diff --git a/price-adapter/Cargo.toml b/price-adapter/Cargo.toml index 054b7f16..0ca7b6c5 100644 --- a/price-adapter/Cargo.toml +++ b/price-adapter/Cargo.toml @@ -15,3 +15,4 @@ tokio-tungstenite = { version = "0.20.1", features = ["native-tls"] } futures-util = "0.3.29" tokio-util = "0.7.10" async-trait = "0.1.74" +tracing = "0.1.40" diff --git a/price-adapter/src/services/interval.rs b/price-adapter/src/services/interval.rs index b92b0f48..e802bda1 100644 --- a/price-adapter/src/services/interval.rs +++ b/price-adapter/src/services/interval.rs @@ -30,7 +30,7 @@ impl IntervalService { impl Service for IntervalService { /// Starts the service, fetching prices at regular intervals and caching them. async fn start(&mut self, symbols: &[&str]) -> Result<(), Error> { - if self.started() { + if self.is_started().await { return Err(Error::AlreadyStarted); } @@ -71,7 +71,7 @@ impl Service for IntervalService { } /// Stops the service, cancelling the interval fetching. - fn stop(&mut self) { + async fn stop(&mut self) { if let Some(token) = &self.cancellation_token { token.cancel(); } @@ -79,7 +79,7 @@ impl Service for IntervalService { } // To check if the service is started. - fn started(&self) -> bool { + async fn is_started(&self) -> bool { self.cancellation_token.is_some() } } diff --git a/price-adapter/src/services/websocket.rs b/price-adapter/src/services/websocket.rs index 62a1cbab..56538072 100644 --- a/price-adapter/src/services/websocket.rs +++ b/price-adapter/src/services/websocket.rs @@ -28,12 +28,12 @@ impl WebsocketService { impl Service for WebsocketService { /// Starts the service, connecting to the WebSocket and subscribing to symbols. async fn start(&mut self, symbols: &[&str]) -> Result<(), Error> { - if self.started() { + if self.is_started().await { return Err(Error::AlreadyStarted); } let mut locked_socket = self.socket.lock().await; - if !locked_socket.is_connected() { + if !locked_socket.is_connected().await { locked_socket.connect().await?; locked_socket.subscribe(symbols).await?; } @@ -62,8 +62,11 @@ impl Service for WebsocketService { locked_cached_prices.insert(price_info.symbol.to_string(), price_info); } Some(Ok(WebsocketMessage::SettingResponse(_response))) => {} - Some(Err(_)) => {} + Some(Err(err)) => { + tracing::trace!("cannot get price: {}", err); + } None => { + tracing::trace!("cannot get price: stream ended"); break; } } @@ -76,7 +79,7 @@ impl Service for WebsocketService { } /// Stops the service, cancelling the WebSocket subscription. - fn stop(&mut self) { + async fn stop(&mut self) { if let Some(token) = &self.cancellation_token { token.cancel(); } @@ -84,7 +87,7 @@ impl Service for WebsocketService { } // To check if the service is started. - fn started(&self) -> bool { + async fn is_started(&self) -> bool { self.cancellation_token.is_some() } } diff --git a/price-adapter/src/sources/binance/websocket.rs b/price-adapter/src/sources/binance/websocket.rs index 525b6357..e11faafb 100644 --- a/price-adapter/src/sources/binance/websocket.rs +++ b/price-adapter/src/sources/binance/websocket.rs @@ -25,7 +25,7 @@ pub struct BinanceWebsocket { usdt_interval: Duration, usdt_price: Arc>>, - raw: Option>>, + raw: Arc>, mapping_back: HashMap, ended: bool, } @@ -38,7 +38,9 @@ impl BinanceWebsocket { usdt_source: Arc::new(usdt_source), usdt_interval, usdt_price: Arc::new(Mutex::new(None)), - raw: None, + raw: Arc::new(Mutex::new(BinanceWebsocketRaw::new( + "wss://stream.binance.com:9443", + ))), mapping_back: HashMap::new(), ended: false, } @@ -50,18 +52,12 @@ impl BinanceWebsocket { impl WebSocketSource for BinanceWebsocket { /// Asynchronous function to connect to the WebSocket. async fn connect(&mut self) -> Result<(), Error> { - let raw = Arc::new(Mutex::new(BinanceWebsocketRaw::new( - "wss://stream.binance.com:9443", - ))); - - let mut locked_raw = raw.lock().await; + let mut locked_raw = self.raw.lock().await; if !locked_raw.is_connected() { locked_raw.connect().await?; } drop(locked_raw); - self.raw = Some(raw); - let cloned_usdt_source = Arc::clone(&self.usdt_source); let cloned_usdt_price = Arc::clone(&self.usdt_price); let cloned_usdt_interval = self.usdt_interval; @@ -106,9 +102,7 @@ impl WebSocketSource for BinanceWebsocket { return Err(Error::UnsupportedSymbol); } - let raw = self.raw.as_mut().ok_or(Error::Unknown)?; - let mut locked_raw = raw.lock().await; - + let mut locked_raw = self.raw.lock().await; locked_raw .subscribe(ids.as_slice()) .await @@ -127,8 +121,7 @@ impl WebSocketSource for BinanceWebsocket { return Err(Error::UnsupportedSymbol); } - let raw = self.raw.as_mut().ok_or(Error::Unknown)?; - let mut locked_raw = raw.lock().await; + let mut locked_raw = self.raw.lock().await; locked_raw .unsubscribe(ids.as_slice()) .await @@ -136,8 +129,9 @@ impl WebSocketSource for BinanceWebsocket { } /// Check if the WebSocket is connected. - fn is_connected(&self) -> bool { - self.raw.is_some() + async fn is_connected(&self) -> bool { + let locked_raw = self.raw.lock().await; + locked_raw.is_connected() } } @@ -160,11 +154,7 @@ impl Stream for BinanceWebsocket { return Poll::Ready(None); } - let Some(raw) = &self.raw else { - return Poll::Ready(None); - }; - - let Ok(mut locked_raw) = raw.try_lock() else { + let Ok(mut locked_raw) = self.raw.try_lock() else { cx.waker().wake_by_ref(); return Poll::Pending; }; diff --git a/price-adapter/src/types.rs b/price-adapter/src/types.rs index cef5e767..12172512 100644 --- a/price-adapter/src/types.rs +++ b/price-adapter/src/types.rs @@ -2,10 +2,8 @@ mod mapper; mod response; mod service; mod source; -mod stable; pub use mapper::*; pub use response::*; pub use service::*; pub use source::*; -pub use stable::*; diff --git a/price-adapter/src/types/service.rs b/price-adapter/src/types/service.rs index b1cef1a3..8259468d 100644 --- a/price-adapter/src/types/service.rs +++ b/price-adapter/src/types/service.rs @@ -4,6 +4,6 @@ use crate::types::Source; #[async_trait::async_trait] pub trait Service: Source { async fn start(&mut self, symbols: &[&str]) -> Result<(), Error>; - fn stop(&mut self); - fn started(&self) -> bool; + async fn stop(&mut self); + async fn is_started(&self) -> bool; } diff --git a/price-adapter/src/types/source.rs b/price-adapter/src/types/source.rs index 96a61f9b..a4c59d02 100644 --- a/price-adapter/src/types/source.rs +++ b/price-adapter/src/types/source.rs @@ -44,5 +44,5 @@ pub trait WebSocketSource: async fn unsubscribe(&mut self, symbols: &[&str]) -> Result; /// Checks whether the WebSocket is currently connected. - fn is_connected(&self) -> bool; + async fn is_connected(&self) -> bool; } diff --git a/price-adapter/src/types/stable.rs b/price-adapter/src/types/stable.rs deleted file mode 100644 index 86f59f12..00000000 --- a/price-adapter/src/types/stable.rs +++ /dev/null @@ -1,13 +0,0 @@ -use crate::error::Error; - -/// Trait for interacting with stable coins and retrieving their prices. -/// -/// This trait defines a method for obtaining the price of a stable coin for a given symbol. -pub trait StableCoin: Send + Sync + Sized + Unpin + 'static { - /// Gets the price of the stable coin for the specified symbol. - /// - /// This method takes a symbol representing a stable coin and returns a `Result`, - /// where the `f64` is the price of the stable coin and `Error` represents any error that - /// may occur during the operation. - fn get_price(&self, symbol: String) -> Result; -} From 463faf492dff319a3407cfa3f77920c8116e21c9 Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Mon, 15 Jan 2024 17:59:12 +0700 Subject: [PATCH 39/46] add log --- .../src/binance_websocket/websocket.rs | 2 +- price-adapter/src/sources/binance/websocket.rs | 15 ++++++++++----- 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/price-adapter-raw/src/binance_websocket/websocket.rs b/price-adapter-raw/src/binance_websocket/websocket.rs index 38206b04..1b48d983 100644 --- a/price-adapter-raw/src/binance_websocket/websocket.rs +++ b/price-adapter-raw/src/binance_websocket/websocket.rs @@ -143,7 +143,7 @@ impl Stream for BinanceWebsocket { match socket.poll_next_unpin(cx) { Poll::Ready(Some(message)) => match message { Ok(Message::Text(text)) => { - tracing::info!("received text message: {}", text); + tracing::trace!("received text message: {}", text); match parse_message(text) { Ok(info) => Poll::Ready(Some(Ok(info))), Err(err) => { diff --git a/price-adapter/src/sources/binance/websocket.rs b/price-adapter/src/sources/binance/websocket.rs index e11faafb..421bcd80 100644 --- a/price-adapter/src/sources/binance/websocket.rs +++ b/price-adapter/src/sources/binance/websocket.rs @@ -173,6 +173,7 @@ impl Stream for BinanceWebsocket { match locked_raw.poll_next_unpin(cx) { Poll::Ready(Some(message)) => match message { Ok(WebsocketMessageRaw::PriceInfo(price_info_raw)) => { + tracing::trace!("received price info raw: {}", price_info_raw); if let Some(symbol) = self.mapping_back.get(&price_info_raw.id) { Poll::Ready(Some(Ok(WebsocketMessage::PriceInfo(PriceInfo { symbol: symbol.to_string(), @@ -181,15 +182,19 @@ impl Stream for BinanceWebsocket { })))) } else { // If symbol not found, wake up the waker and return Pending. + tracing::trace!("received symbol doesn't match"); cx.waker().wake_by_ref(); Poll::Pending } } - Ok(WebsocketMessageRaw::SettingResponse(response)) => Poll::Ready(Some(Ok( - WebsocketMessage::SettingResponse(SettingResponse { - data: response.data, - }), - ))), + Ok(WebsocketMessageRaw::SettingResponse(response)) => { + tracing::trace!("received setting response raw: {:?}", response); + return Poll::Ready(Some(Ok(WebsocketMessage::SettingResponse( + SettingResponse { + data: response.data, + }, + )))); + } Err(err) => Poll::Ready(Some(Err(err.into()))), }, Poll::Ready(None) => { From a9c5470eb8fc75938269e4948b8c4e8c92db1ebf Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Mon, 15 Jan 2024 18:01:00 +0700 Subject: [PATCH 40/46] fix --- price-adapter/src/sources/binance/websocket.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/price-adapter/src/sources/binance/websocket.rs b/price-adapter/src/sources/binance/websocket.rs index 421bcd80..9833659a 100644 --- a/price-adapter/src/sources/binance/websocket.rs +++ b/price-adapter/src/sources/binance/websocket.rs @@ -18,7 +18,7 @@ use tokio::time::sleep; pub type DefaultBinanceWebsocket = BinanceWebsocket; -/// A generic struct `BinanceWebsocket` parameterized over `Mapper` and `StableCoin` types. +/// A generic struct `BinanceWebsocket` parameterized over `Mapper` and `Source` types. pub struct BinanceWebsocket { mapper: M, usdt_source: Arc, @@ -189,11 +189,11 @@ impl Stream for BinanceWebsocket { } Ok(WebsocketMessageRaw::SettingResponse(response)) => { tracing::trace!("received setting response raw: {:?}", response); - return Poll::Ready(Some(Ok(WebsocketMessage::SettingResponse( + Poll::Ready(Some(Ok(WebsocketMessage::SettingResponse( SettingResponse { data: response.data, }, - )))); + )))) } Err(err) => Poll::Ready(Some(Err(err.into()))), }, From 544d0a7354caa8ef432830fc8151b9e875ccf58a Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Tue, 16 Jan 2024 14:07:40 +0700 Subject: [PATCH 41/46] add license, readme, issue_template --- .github/ISSUE_TEMPLATE/bug_report.md | 33 ++ .github/ISSUE_TEMPLATE/feature_request.md | 20 + .github/PULL_REQUEST_TEMPLATE.md | 22 + CONTRIBUTING.md | 23 + LICENSE | 674 ++++++++++++++++++++++ README.md | 22 +- price-adapter-raw/CHANGELOG.md | 6 + price-adapter-raw/README.md | 69 +++ price-adapter-raw/src/lib.rs | 7 +- price-adapter/CHANGELOG.md | 7 + price-adapter/README.md | 37 +- 11 files changed, 912 insertions(+), 8 deletions(-) create mode 100644 .github/ISSUE_TEMPLATE/bug_report.md create mode 100644 .github/ISSUE_TEMPLATE/feature_request.md create mode 100644 .github/PULL_REQUEST_TEMPLATE.md create mode 100644 CONTRIBUTING.md create mode 100644 LICENSE create mode 100644 price-adapter-raw/CHANGELOG.md create mode 100644 price-adapter-raw/README.md create mode 100644 price-adapter/CHANGELOG.md diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 00000000..3827ff5d --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,33 @@ +--- +name: Bug report +about: Create a report to help us improve +title: '' +labels: bug +assignees: '' + +--- + +**Describe the bug** +A clear and concise description of what the bug is. + +**Version** +vX.X.X + +**To Reproduce** +Steps to reproduce the behavior: +1. Go to '...' +2. Run '....' +4. See error + +**Expected behavior** +A clear and concise description of what you expected to happen. + +**Screenshots** +If applicable, add screenshots to help explain your problem. + +**Desktop (please complete the following information):** + - OS: [e.g. Linux, Windows] + - Version [e.g. 10] + +**Additional context** +Add any other context about the problem here. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 00000000..11fc491e --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,20 @@ +--- +name: Feature request +about: Suggest an idea for this project +title: '' +labels: enhancement +assignees: '' + +--- + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context or screenshots about the feature request here. diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 00000000..65cc7310 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,22 @@ + + + + +## Implementation details +- Do 1 +- Do 2 + +## Please ensure the following requirements are met before submitting a pull request: + +- [ ] The pull request is targeted against the correct target branch +- [ ] The pull request is linked to an issue with appropriate discussion and an accepted design OR is linked to a spec that describes the work. +- [ ] The pull request includes a description of the implementation/work done in detail. +- [ ] The pull request includes any appropriate unit/integration tests +- [ ] You have added a relevant changelog entry to `CHANGELOG.md` +- [ ] You have re-reviewed the files affected by the pull request (e.g. using the `Files changed` tab in the GitHub PR explorer) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 00000000..b97cdf04 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,23 @@ +# Contributing + +Thank you for your interest in contributing! You can contribute to `band-price-adapter` in many ways. + +1. **Issues** + + If you find any bug/issues with the `band-price-adapter` from any perspective (document/function/usage), you can always open the [issue](https://github.com/bandprotocol/band-price-adapter/issues/new/choose) in GitHub to tell us. + +2. **Discussion** + + If you have any idea on how to improve and want to discuss your idea with our community. We also open [a discussion board](https://github.com/bandprotocol/band-price-adapter/discussions) for it. + +3. **Pull requests** + + In case, you want to add more features that you think will improve developer experiences. You can open the [pull request](https://github.com/bandprotocol/band-price-adapter/pulls) to our main branch. + +4. **Forking** + + We also welcome you to fork our repository to either do a pull request or create your version. + +5. **Star** + + If you like or use our work, you can also give a star to our repository. diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..f288702d --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md index 0a1d7234..e16d4b3d 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,21 @@ -# Band-Price-Adapter +# Band Price Adapter +`Band-Price-Adapter` is a Rust library designed to facilitate the retrieval of price information for various cryptocurrencies and assets from diverse sources. -TBD. +## Packages +This project comprises two distinct packages: + +### price-adapter +This package offers unified interfaces for seamless interaction with various sources. It includes utility functions that enhance the ease of integration into user applications. + +For more details about this package, refer to the documentation [here](./price-adapter/README.md), and the changelog is accessible [here](./price-adapter/CHANGELOG.md). + +### price-adapter-raw +This package serves as a wrapper for each data source, enabling direct querying of prices from the respective sources. + +For more details about this package, refer to the documentation [here](./price-adapter-raw/README.md), and the changelog is accessible [here](./price-adapter-raw/CHANGELOG.md). + +## Contributing +We welcome contributions from the community! Before submitting a pull request, please review our [contributing guidelines](CONTRIBUTING.md). + +## License +Band Price Adapter is released under the GPL-3.0 license. Your use of this library is subject to the terms outlined in the [LICENSE](LICENSE.md) file. diff --git a/price-adapter-raw/CHANGELOG.md b/price-adapter-raw/CHANGELOG.md new file mode 100644 index 00000000..4101e4ab --- /dev/null +++ b/price-adapter-raw/CHANGELOG.md @@ -0,0 +1,6 @@ +# CHANGELOG + +## Unreleased + +- Support CoinGecko sources +- Support Binance Websocket source diff --git a/price-adapter-raw/README.md b/price-adapter-raw/README.md new file mode 100644 index 00000000..4779afe0 --- /dev/null +++ b/price-adapter-raw/README.md @@ -0,0 +1,69 @@ +# price-adapter-raw + +`price-adapter-raw` is a price query adapter for crypto exchanges and price aggregators. + +Currently, it supports the following exchanges and price aggregators: + +- Binance +- CoinGecko + +## Usage + +### Coingecko + +To use coingecko API, you need to create a `CoingeckoPro` instance and set the api key. + +```rust +use price_adapter_raw::CoinGecko; + +#[tokio::main] +async fn main() { + let coingecko = CoinGecko::new_with_api_key("$API_KEY".into()); + let queries = vec!["ethereum"]; + let prices = coingecko.get_prices(&queries).await; + println!("prices: {:?}", prices); +} +``` + +### Binance Websocket + +To use binance websocket API, you need to create a `BinanceWebsocket` instance and set the query symbols. + +```rust +use price_adapter_raw::BinanceWebsocket; +use futures_util::StreamExt; + +#[tokio::main] +async fn main() { + let mut binance_ws = BinanceWebsocket::new("wss://stream.binance.com:9443"); + binance_ws.connect().await.unwrap(); + binance_ws.subscribe(&["ethbtc", "btcusdt"]).await; + let data = binance_ws.next().await.unwrap(); + match data { + Ok(price) => { + println!("price: {:?}", price); + } + Err(e) => { + eprintln!("Error: {}", e); + } + } +} +``` + +Or use `BinanceWebsocketService` to query price data. + +```rust +use price_adapter_raw::{BinanceWebsocket, BinanceWebsocketService}; +use std::time::Duration; + +#[tokio::main] +async fn main() { + let mut binance_ws = BinanceWebsocket::new("wss://stream.binance.com:9443"); + let mut service = BinanceWebsocketService::new(binance_ws); + service.start(&["ethbtc", "btcusdt"]).await.unwrap(); + tokio::time::sleep(Duration::from_secs(1)).await; + + let price = service.get_prices(&["btcusdt"]).await; + println!("price: {:?}", price); +} +``` diff --git a/price-adapter-raw/src/lib.rs b/price-adapter-raw/src/lib.rs index 6e7ff191..0d2c6d6f 100644 --- a/price-adapter-raw/src/lib.rs +++ b/price-adapter-raw/src/lib.rs @@ -1,8 +1,7 @@ -//! # price-explorer -//! price-explorer is a price query adapter for crypto exchanges and price aggregators. +//! # price-adapter-raw +//! price-adapter-raw is a price query adapter for crypto exchanges and price aggregators. //! -//! It provides a unified interface for querying price data from different exchanges and -//! price aggregators. Currently, it supports the following exchanges and price aggregators: +//! Currently, it supports the following exchanges and price aggregators: //! - Binance //! - CoinGecko diff --git a/price-adapter/CHANGELOG.md b/price-adapter/CHANGELOG.md new file mode 100644 index 00000000..1332a7b3 --- /dev/null +++ b/price-adapter/CHANGELOG.md @@ -0,0 +1,7 @@ +# CHANGELOG + +## Unreleased + +- Support CoinGecko sources +- Support Binance Websocket source +- Create Interval and Websocket service to manage sources diff --git a/price-adapter/README.md b/price-adapter/README.md index 0e4e00d0..92f95cae 100644 --- a/price-adapter/README.md +++ b/price-adapter/README.md @@ -1,3 +1,36 @@ -# Price adapter +# price-adapter -The primary purpose of the price adapter library is to provide a versatile tool for retrieving the current price of a wide range of supported financial symbols from various data sources, all standardized in terms of the United States Dollar (USD) unit. This library offers a comprehensive and efficient solution for seamlessly accessing and integrating real-time or historical pricing information for a multitude of financial instruments, ensuring that users can effortlessly obtain accurate pricing data in USD for their respective symbols, regardless of the specific data source they choose to utilize. +`price-adapter` is a Rust library that provides different services for fetching price information for various cryptocurrencies and assets. It includes sources for popular data providers such as CoinGecko and Binance, and offers both HTTP-based and WebSocket-based interfaces for retrieving prices. + +## Features + +* **Multiple data sources:** `price-adapter` supports multiple sources for obtaining cryptocurrency prices, including: + * CoinGecko + * Binance + * BandStableCoin +* **HTTP and WebSocket interfaces:** You can fetch prices either through HTTP requests or WebSocket connections, depending on your application's requirements. +* **Caching and interval-based updating:** The library features caching and interval-based updating of prices to optimize performance and reduce API calls. +* **Extensibility:** It's easy to add new data sources or implement custom mapping rules to adapt the library to your specific needs. + +## Getting Started + +To use `price-adapter`, add the following to your Cargo.toml file: + +```toml +[dependencies] +price-adapter = "0.1.0" +``` + +## Services + +`price-adapter` offers two types of services: + +1. **IntervalService:** This service fetches prices from a specified source at regular intervals and caches them. This is a convenient option if you need to access prices frequently and don't want to make API calls every time. + +2. **WebsocketService:** This service establishes a WebSocket connection to a source and subscribes to specific symbols. It then streams price updates over the WebSocket connection, allowing you to receive real-time price changes. + +Both services implement the `Service` trait, which defines the common interface for starting, stopping, and checking the status of the service. + +## Examples + +The `examples` directory contains several example scripts demonstrating how to use `price-adapter`. These examples cover scenarios such as using the HTTP and WebSocket interfaces, creating a custom mapper, and employing the interval and Websocket services. From aed22b80d910247ae30711def114e224ab774e68 Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Tue, 16 Jan 2024 14:09:32 +0700 Subject: [PATCH 42/46] adjust link --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e16d4b3d..49085e5b 100644 --- a/README.md +++ b/README.md @@ -18,4 +18,4 @@ For more details about this package, refer to the documentation [here](./price-a We welcome contributions from the community! Before submitting a pull request, please review our [contributing guidelines](CONTRIBUTING.md). ## License -Band Price Adapter is released under the GPL-3.0 license. Your use of this library is subject to the terms outlined in the [LICENSE](LICENSE.md) file. +Band Price Adapter is released under the GPL-3.0 license. Your use of this library is subject to the terms outlined in the [LICENSE](LICENSE) file. From 0595ee371c5d5652a3a12cb4a55404449c751a3b Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Tue, 16 Jan 2024 14:13:00 +0700 Subject: [PATCH 43/46] change wording --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 49085e5b..b7f20fb1 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ # Band Price Adapter -`Band-Price-Adapter` is a Rust library designed to facilitate the retrieval of price information for various cryptocurrencies and assets from diverse sources. +`band-price-adapter` is a Rust library designed to facilitate the retrieval of price information for various cryptocurrencies and assets from diverse sources. ## Packages This project comprises two distinct packages: From 9dbe92326988b60c8b0e4fe31a8b8395c94e6b5a Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Tue, 16 Jan 2024 14:25:19 +0700 Subject: [PATCH 44/46] update license --- LICENSE | 674 ------------------------------------------------- LICENSE-APACHE | 176 +++++++++++++ LICENSE-MIT | 19 ++ README.md | 6 +- 4 files changed, 200 insertions(+), 675 deletions(-) delete mode 100644 LICENSE create mode 100644 LICENSE-APACHE create mode 100644 LICENSE-MIT diff --git a/LICENSE b/LICENSE deleted file mode 100644 index f288702d..00000000 --- a/LICENSE +++ /dev/null @@ -1,674 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. diff --git a/LICENSE-APACHE b/LICENSE-APACHE new file mode 100644 index 00000000..1b5ec8b7 --- /dev/null +++ b/LICENSE-APACHE @@ -0,0 +1,176 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS diff --git a/LICENSE-MIT b/LICENSE-MIT new file mode 100644 index 00000000..9cf10627 --- /dev/null +++ b/LICENSE-MIT @@ -0,0 +1,19 @@ +MIT License + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index b7f20fb1..0fac8e0b 100644 --- a/README.md +++ b/README.md @@ -18,4 +18,8 @@ For more details about this package, refer to the documentation [here](./price-a We welcome contributions from the community! Before submitting a pull request, please review our [contributing guidelines](CONTRIBUTING.md). ## License -Band Price Adapter is released under the GPL-3.0 license. Your use of this library is subject to the terms outlined in the [LICENSE](LICENSE) file. + +Licensed under either of + +- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://apache.org/licenses/LICENSE-2.0) +- MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) From aeb010f4c1e7c8925d7de3e26d13adb93337117b Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Wed, 17 Jan 2024 00:27:42 +0700 Subject: [PATCH 45/46] add tracing_subscriber --- price-adapter/Cargo.toml | 1 + price-adapter/examples/binance-websocket-service.rs | 1 + price-adapter/examples/binance-websocket.rs | 1 + price-adapter/examples/coingecko-basic.rs | 1 + price-adapter/examples/coingecko-interval-service.rs | 1 + 5 files changed, 5 insertions(+) diff --git a/price-adapter/Cargo.toml b/price-adapter/Cargo.toml index 0ca7b6c5..16fe47e3 100644 --- a/price-adapter/Cargo.toml +++ b/price-adapter/Cargo.toml @@ -16,3 +16,4 @@ futures-util = "0.3.29" tokio-util = "0.7.10" async-trait = "0.1.74" tracing = "0.1.40" +tracing-subscriber = "0.3.18" diff --git a/price-adapter/examples/binance-websocket-service.rs b/price-adapter/examples/binance-websocket-service.rs index e79425c1..43400ffb 100644 --- a/price-adapter/examples/binance-websocket-service.rs +++ b/price-adapter/examples/binance-websocket-service.rs @@ -5,6 +5,7 @@ use std::time::Duration; #[tokio::main] async fn main() { + tracing_subscriber::fmt::init(); let binance_websocket = BinanceWebsocket::new_with_default().unwrap(); let mut service = WebsocketService::new(binance_websocket); service.start(vec!["BTC"].as_slice()).await.unwrap(); diff --git a/price-adapter/examples/binance-websocket.rs b/price-adapter/examples/binance-websocket.rs index e6596e07..0bba4632 100644 --- a/price-adapter/examples/binance-websocket.rs +++ b/price-adapter/examples/binance-websocket.rs @@ -4,6 +4,7 @@ use price_adapter::types::WebSocketSource; #[tokio::main] async fn main() { + tracing_subscriber::fmt::init(); let mut binance_websocket = BinanceWebsocket::new_with_default().unwrap(); let symbols = vec!["ETH", "BTC"]; diff --git a/price-adapter/examples/coingecko-basic.rs b/price-adapter/examples/coingecko-basic.rs index 143fe39b..6018ebf1 100644 --- a/price-adapter/examples/coingecko-basic.rs +++ b/price-adapter/examples/coingecko-basic.rs @@ -3,6 +3,7 @@ use price_adapter::types::Source; #[tokio::main] async fn main() { + tracing_subscriber::fmt::init(); let coingecko = CoinGecko::new_with_default(None).unwrap(); let queries = vec!["ETH", "BAND"]; let prices = coingecko.get_prices(&queries).await; diff --git a/price-adapter/examples/coingecko-interval-service.rs b/price-adapter/examples/coingecko-interval-service.rs index 5b1e6748..37b7ea67 100644 --- a/price-adapter/examples/coingecko-interval-service.rs +++ b/price-adapter/examples/coingecko-interval-service.rs @@ -5,6 +5,7 @@ use std::time::Duration; #[tokio::main] async fn main() { + tracing_subscriber::fmt::init(); let coingecko = CoinGecko::new_with_default(None).unwrap(); let mut service = IntervalService::new(coingecko, Duration::from_secs(20)); service.start(vec!["BTC"].as_slice()).await.unwrap(); From 3c0207ae9ff096559666f68836c4404d18018c61 Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Thu, 18 Jan 2024 00:32:27 +0700 Subject: [PATCH 46/46] bump --- price-adapter/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/price-adapter/Cargo.toml b/price-adapter/Cargo.toml index 16fe47e3..39214a1d 100644 --- a/price-adapter/Cargo.toml +++ b/price-adapter/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "price-adapter" description = "price-adapter" -version = "0.1.7" +version = "0.1.8" edition = "2021" license = "MIT OR Apache-2.0"