|
| 1 | +/// This Connector obtains the lovelace per 1 USD rate and submits it |
| 2 | +/// to an oracle core. It reads the `oracle-config.yaml` to find the port |
| 3 | +/// of the oracle core (via Connector-Lib) and submits it to the POST API |
| 4 | +/// server on the core. |
| 5 | +/// Note: The value that is posted on-chain is the number |
| 6 | +/// of lovelaces per 1 USD, not the rate per lovelace. |
| 7 | +use anyhow::{anyhow, Result}; |
| 8 | +use frontend_connector_lib::FrontendConnector; |
| 9 | + |
| 10 | +// Number of Lovelaces in a single Ada |
| 11 | +static LOVELACE_CONVERSION: f64 = 1000000.0; |
| 12 | + |
| 13 | +static CG_RATE_URL: &str = |
| 14 | + "https://api.coingecko.com/api/v3/simple/price?ids=cardano&vs_currencies=USD"; |
| 15 | + |
| 16 | +/// Get the Ada/USD price from the Lovelaces per 1 USD datapoint price |
| 17 | +pub fn generate_current_price(datapoint: u64) -> f64 { |
| 18 | + (1.0 / datapoint as f64) * LOVELACE_CONVERSION |
| 19 | +} |
| 20 | + |
| 21 | +/// Acquires the price of Ada in USD from CoinGecko, convert it |
| 22 | +/// into Lovelaces per 1 USD, and return it. |
| 23 | +fn get_lovelace_usd_price() -> Result<u64> { |
| 24 | + let resp = reqwest::blocking::Client::new().get(CG_RATE_URL).send()?; |
| 25 | + let price_json = json::parse(&resp.text()?)?; |
| 26 | + if let Some(p) = price_json["cardano"]["usd"].as_f64() { |
| 27 | + let lovelace_price = (1.0 / p) * LOVELACE_CONVERSION; |
| 28 | + return Ok(lovelace_price as u64); |
| 29 | + } else { |
| 30 | + Err(anyhow!("Failed to parse price from json.")) |
| 31 | + } |
| 32 | +} |
| 33 | + |
| 34 | +fn main() { |
| 35 | + // Create the FrontendConnector |
| 36 | + let connector = FrontendConnector::new_basic_connector( |
| 37 | + "ADA-USD", |
| 38 | + get_lovelace_usd_price, |
| 39 | + generate_current_price, |
| 40 | + ); |
| 41 | + |
| 42 | + // Start the FrontendConnector |
| 43 | + connector.run(); |
| 44 | +} |
0 commit comments