Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ERG/BTC Datapoint Sources #304

Merged
merged 3 commits into from
Jul 24, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions core/src/datapoint_source.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ mod bitpanda;
mod coincap;
mod coingecko;
mod custom_ext_script;
mod erg_btc;
mod erg_usd;
mod erg_xau;
mod predef;
Expand Down
16 changes: 16 additions & 0 deletions core/src/datapoint_source/assets_exchange_rate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,13 @@ pub struct Erg {}
#[derive(Debug, Clone, Copy)]
pub struct Usd {}

#[derive(Debug, Clone, Copy)]
pub struct Btc {}

impl Asset for Erg {}
impl Asset for NanoErg {}
impl Asset for Usd {}
impl Asset for Btc {}

impl Erg {
pub fn to_nanoerg(erg: f64) -> f64 {
Expand All @@ -32,3 +36,15 @@ pub struct AssetsExchangeRate<PER1: Asset, GET: Asset> {
pub get: GET,
pub rate: f64,
}

// Calculates an Exchange Rate of GET/PER2 based on GET/PER1 and PER1/PER2
pub fn convert_rate<GET: Asset, PER1: Asset, PER2: Asset>(
a: AssetsExchangeRate<PER1, GET>,
b: AssetsExchangeRate<PER2, PER1>,
) -> AssetsExchangeRate<PER2, GET> {
AssetsExchangeRate {
per1: b.per1,
get: a.get,
rate: a.rate * b.rate,
}
}
33 changes: 33 additions & 0 deletions core/src/datapoint_source/bitpanda.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use super::assets_exchange_rate::AssetsExchangeRate;
use super::assets_exchange_rate::Btc;
use super::assets_exchange_rate::Usd;
use super::erg_xau::KgAu;
use super::DataPointSourceError;
Expand Down Expand Up @@ -33,6 +34,33 @@ pub async fn get_kgau_usd() -> Result<AssetsExchangeRate<KgAu, Usd>, DataPointSo
}
}

// Get USD/BTC. Can be used as a redundant source for ERG/BTC through ERG/USD and USD/BTC
pub(crate) async fn get_btc_usd() -> Result<AssetsExchangeRate<Btc, Usd>, DataPointSourceError> {
let url = "https://api.bitpanda.com/v1/ticker";
let resp = reqwest::get(url).await?;
let json = json::parse(&resp.text().await?)?;
if let Some(p) = json["BTC"]["USD"].as_str() {
// USD price of BTC
let usd_per_btc = p
.parse::<f64>()
.map_err(|_| DataPointSourceError::JsonMissingField {
field: "BTC.USD as f64".to_string(),
json: json.dump(),
})?;
let rate = AssetsExchangeRate {
per1: Btc {},
get: Usd {},
rate: usd_per_btc,
};
Ok(rate)
} else {
Err(DataPointSourceError::JsonMissingField {
field: "BTC.USD".to_string(),
json: json.dump(),
})
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand All @@ -42,4 +70,9 @@ mod tests {
let pair: AssetsExchangeRate<KgAu, Usd> = tokio_test::block_on(get_kgau_usd()).unwrap();
assert!(pair.rate > 0.0);
}
#[test]
fn test_btc_usd_price() {
let pair: AssetsExchangeRate<Btc, Usd> = tokio_test::block_on(get_btc_usd()).unwrap();
assert!(pair.rate > 0.0);
}
}
41 changes: 41 additions & 0 deletions core/src/datapoint_source/coincap.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use super::assets_exchange_rate::AssetsExchangeRate;
use super::assets_exchange_rate::Btc;
use super::assets_exchange_rate::NanoErg;
use super::assets_exchange_rate::Usd;
use super::DataPointSourceError;
Expand Down Expand Up @@ -33,8 +34,36 @@ pub async fn get_usd_nanoerg() -> Result<AssetsExchangeRate<Usd, NanoErg>, DataP
}
}

// Get USD/BTC. Can be used as a redundant source for ERG/BTC through ERG/USD and USD/BTC
pub async fn get_btc_usd() -> Result<AssetsExchangeRate<Btc, Usd>, DataPointSourceError> {
// see https://coincap.io/assets/ergo
let url = "https://api.coincap.io/v2/assets/bitcoin";
let resp = reqwest::get(url).await?;
let price_json = json::parse(&resp.text().await?)?;
if let Some(p) = price_json["data"]["priceUsd"].as_str() {
let usd_per_btc = p
.parse::<f64>()
.map_err(|_| DataPointSourceError::JsonMissingField {
field: "data.priceUsd as f64".to_string(),
json: price_json.dump(),
})?;
let rate = AssetsExchangeRate {
per1: Btc {},
get: Usd {},
rate: usd_per_btc,
};
Ok(rate)
} else {
Err(DataPointSourceError::JsonMissingField {
field: "btc.priceUsd as string".to_string(),
json: price_json.dump(),
})
}
}

#[cfg(test)]
mod tests {
use super::super::bitpanda;
use super::super::coingecko;
use super::*;

Expand All @@ -49,4 +78,16 @@ mod tests {
"up to 5% deviation is allowed"
);
}
#[test]
fn test_usd_btc_price() {
let pair = tokio_test::block_on(get_btc_usd()).unwrap();
let bitpanda = tokio_test::block_on(bitpanda::get_btc_usd()).unwrap();
assert!(pair.rate > 0.0);
dbg!(pair, bitpanda);
let deviation_from_bitpanda = (pair.rate - bitpanda.rate).abs() / bitpanda.rate;
assert!(
deviation_from_bitpanda < 0.05,
"up to 5% deviation is allowed"
);
}
}
28 changes: 28 additions & 0 deletions core/src/datapoint_source/coingecko.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use crate::datapoint_source::assets_exchange_rate::NanoErg;
use crate::datapoint_source::DataPointSourceError;

use super::ada_usd::Lovelace;
use super::assets_exchange_rate::Btc;
use super::assets_exchange_rate::Usd;
use super::erg_xau::KgAu;

Expand Down Expand Up @@ -70,6 +71,27 @@ pub async fn get_usd_lovelace() -> Result<AssetsExchangeRate<Usd, Lovelace>, Dat
}
}

pub async fn get_btc_nanoerg() -> Result<AssetsExchangeRate<Btc, NanoErg>, DataPointSourceError> {
let url = "https://api.coingecko.com/api/v3/simple/price?ids=ergo&vs_currencies=BTC";
let resp = reqwest::get(url).await?;
let price_json = json::parse(&resp.text().await?)?;
if let Some(p) = price_json["ergo"]["btc"].as_f64() {
// Convert from price BTC/ERG to nanoERG/BTC
let erg_per_usd = NanoErg::from_erg(1.0 / p);
let rate = AssetsExchangeRate {
per1: Btc {},
get: NanoErg {},
rate: erg_per_usd,
};
Ok(rate)
} else {
Err(DataPointSourceError::JsonMissingField {
field: "ergo.btc as f64".to_string(),
json: price_json.dump(),
})
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand All @@ -94,4 +116,10 @@ mod tests {
tokio_test::block_on(get_usd_lovelace()).unwrap();
assert!(pair.rate > 0.0);
}
#[test]
fn test_erg_btc_price() {
let pair: AssetsExchangeRate<Btc, NanoErg> =
tokio_test::block_on(get_btc_nanoerg()).unwrap();
assert!(pair.rate > 0.0);
}
}
65 changes: 65 additions & 0 deletions core/src/datapoint_source/erg_btc.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
use std::pin::Pin;

use futures::Future;

use super::{
assets_exchange_rate::{convert_rate, AssetsExchangeRate, Btc, NanoErg},
bitpanda, coincap, coingecko, DataPointSourceError,
};

#[allow(clippy::type_complexity)]
pub fn nanoerg_btc_sources() -> Vec<
Pin<Box<dyn Future<Output = Result<AssetsExchangeRate<Btc, NanoErg>, DataPointSourceError>>>>,
> {
vec![
Box::pin(coingecko::get_btc_nanoerg()),
Box::pin(get_btc_nanoerg_coincap()),
Box::pin(get_btc_nanoerg_bitpanda()),
]
}

// Calculate ERG/BTC through ERG/USD and USD/BTC
async fn get_btc_nanoerg_coincap() -> Result<AssetsExchangeRate<Btc, NanoErg>, DataPointSourceError>
{
Ok(convert_rate(
coincap::get_usd_nanoerg().await?,
coincap::get_btc_usd().await?,
))
}

async fn get_btc_nanoerg_bitpanda() -> Result<AssetsExchangeRate<Btc, NanoErg>, DataPointSourceError>
{
Ok(convert_rate(
coincap::get_usd_nanoerg().await?,
bitpanda::get_btc_usd().await?,
))
}

#[cfg(test)]
mod test {
use super::coingecko;
use super::get_btc_nanoerg_bitpanda;
use super::get_btc_nanoerg_coincap;
#[test]
fn test_btc_nanoerg_combined() {
let combined = tokio_test::block_on(get_btc_nanoerg_coincap()).unwrap();
let coingecko = tokio_test::block_on(coingecko::get_btc_nanoerg()).unwrap();
let bitpanda = tokio_test::block_on(get_btc_nanoerg_bitpanda()).unwrap();
let deviation_from_coingecko = (combined.rate - coingecko.rate).abs() / coingecko.rate;
assert!(
deviation_from_coingecko < 0.05,
"up to 5% deviation is allowed"
);
let bitpanda_deviation_from_coingecko =
(bitpanda.rate - coingecko.rate).abs() / coingecko.rate;
assert!(
bitpanda_deviation_from_coingecko < 0.05,
"up to 5% deviation is allowed"
);
let deviation_from_bitpanda = (bitpanda.rate - combined.rate).abs() / combined.rate;
assert!(
deviation_from_bitpanda < 0.05,
"up to 5% deviation is allowed"
);
}
}
8 changes: 2 additions & 6 deletions core/src/datapoint_source/erg_xau.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use std::pin::Pin;
use futures::Future;

use super::aggregator::fetch_aggregated;
use super::assets_exchange_rate::convert_rate;
use super::assets_exchange_rate::Asset;
use super::assets_exchange_rate::AssetsExchangeRate;
use super::assets_exchange_rate::NanoErg;
Expand Down Expand Up @@ -48,12 +49,7 @@ pub async fn combined_kgau_nanoerg(
) -> Result<AssetsExchangeRate<KgAu, NanoErg>, DataPointSourceError> {
let kgau_usd_rate = bitpanda::get_kgau_usd().await?;
let aggregated_usd_nanoerg_rate = fetch_aggregated(nanoerg_usd_sources()).await?;
let rate = kgau_usd_rate.rate * aggregated_usd_nanoerg_rate.rate;
Ok(AssetsExchangeRate {
per1: KgAu {},
get: NanoErg {},
rate,
})
Ok(convert_rate(aggregated_usd_nanoerg_rate, kgau_usd_rate))
}

#[cfg(test)]
Expand Down
4 changes: 4 additions & 0 deletions core/src/datapoint_source/predef.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use crate::oracle_types::Rate;

use super::ada_usd::usd_lovelace_sources;
use super::aggregator::fetch_aggregated;
use super::erg_btc::nanoerg_btc_sources;
use super::erg_usd::nanoerg_usd_sources;
use super::erg_xau::nanoerg_kgau_sources;
use super::DataPointSourceError;
Expand All @@ -28,6 +29,9 @@ async fn fetch_predef_source_aggregated(
PredefinedDataPointSource::NanoAdaUsd => {
fetch_aggregated(usd_lovelace_sources()).await?.rate
}
PredefinedDataPointSource::NanoErgBTC => {
fetch_aggregated(nanoerg_btc_sources()).await?.rate
}
};
Ok((rate_float as i64).into())
}
1 change: 1 addition & 0 deletions core/src/pool_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ pub enum PredefinedDataPointSource {
NanoErgUsd,
NanoErgXau,
NanoAdaUsd,
NanoErgBTC,
}

/// Holds the token ids of every important token used by the oracle pool.
Expand Down