-
Notifications
You must be signed in to change notification settings - Fork 46
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 exchange-oracle crate and implement get_exchange_rate for coinGecko #442
Merged
Merged
Changes from 12 commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
2c6a5bf
parent bca26ab344950ebea55db2df3cbf66277b79d6a3
9f35074
Rebase
ee419e9
cargo clippy and catch error in execute_update_market to prevent that…
ef6de92
settings for demo
5f09ed5
update CI because this branch will not be merged in master, but in ex…
c53bd1f
changes from review
d80b262
changes from review
44dfd04
Remove reference to light client for oracle
90ec724
Set update interval for exchange range to 24h
1ef911a
Changes review
ff00d44
Changes review
49cbba0
Cargo clippy
af1cc24
Changes from review: improve variable names
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
[package] | ||
name = "ita-exchange-oracle" | ||
version = "0.8.0" | ||
authors = ["Integritee AG <[email protected]>"] | ||
edition = "2018" | ||
|
||
[features] | ||
default = ["std"] | ||
std = [ | ||
"itc-rest-client/std", | ||
"log/std", | ||
"serde/std", | ||
"serde_json/std", | ||
"thiserror", | ||
"url", | ||
] | ||
sgx = [ | ||
"itc-rest-client/sgx", | ||
"sgx_tstd", | ||
"thiserror_sgx", | ||
"url_sgx", | ||
] | ||
|
||
[dependencies] | ||
|
||
# std dependencies | ||
thiserror = { version = "1.0.26", optional = true } | ||
url = { version = "2.0.0", optional = true } | ||
|
||
# sgx dependencies | ||
sgx_tstd = { rev = "v1.1.3", git = "https://github.com/apache/teaclave-sgx-sdk.git", optional = true} | ||
thiserror_sgx = { package = "thiserror", git = "https://github.com/mesalock-linux/thiserror-sgx", tag = "sgx_1.1.3", optional = true } | ||
url_sgx = { package = "url", git = "https://github.com/mesalock-linux/rust-url-sgx", tag = "sgx_1.1.3", optional = true } | ||
|
||
# no_std dependencies | ||
haerdib marked this conversation as resolved.
Show resolved
Hide resolved
|
||
log = { version = "0.4", default-features = false } | ||
serde = { version = "1.0", default-features = false, features = ["derive", "alloc"] } | ||
serde_json = { version = "1.0", default-features = false, features = ["alloc"] } | ||
|
||
# internal dependencies | ||
itc-rest-client = { path = "../../core/rest-client", default-features = false } | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,131 @@ | ||
/* | ||
Copyright 2021 Integritee AG and Supercomputing Systems AG | ||
|
||
Licensed under the Apache License, Version 2.0 (the "License"); | ||
you may not use this file except in compliance with the License. | ||
You may obtain a copy of the License at | ||
|
||
http://www.apache.org/licenses/LICENSE-2.0 | ||
|
||
Unless required by applicable law or agreed to in writing, software | ||
distributed under the License is distributed on an "AS IS" BASIS, | ||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
See the License for the specific language governing permissions and | ||
limitations under the License. | ||
|
||
*/ | ||
#[cfg(all(not(feature = "std"), feature = "sgx"))] | ||
use crate::sgx_reexport_prelude::*; | ||
murerfel marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
use crate::{error::Error, GetExchangeRate}; | ||
use itc_rest_client::{http_client::HttpClient, rest_client::RestClient, RestGet, RestPath}; | ||
use log::*; | ||
use serde::{Deserialize, Serialize}; | ||
use std::{ | ||
string::{String, ToString}, | ||
time::Duration, | ||
vec::Vec, | ||
}; | ||
use url::Url; | ||
|
||
const COINGECKO_URL: &str = "https://api.coingecko.com"; | ||
const COINGECKO_PARAM_CURRENCY: &str = "vs_currency"; | ||
const COINGECKO_PARAM_COIN: &str = "ids"; | ||
const COINGECKO_PATH: &str = "api/v3/coins/markets"; | ||
const COINGECKO_TIMEOUT: Duration = Duration::from_secs(3u64); | ||
|
||
/// REST client to make requests to CoinGecko. | ||
pub struct CoinGeckoClient { | ||
client: RestClient<HttpClient>, | ||
} | ||
impl CoinGeckoClient { | ||
pub fn new(baseurl: Url) -> Self { | ||
let http_client = HttpClient::new(true, Some(COINGECKO_TIMEOUT), None, None); | ||
let rest_client = RestClient::new(http_client, baseurl); | ||
CoinGeckoClient { client: rest_client } | ||
} | ||
pub fn base_url() -> Result<Url, Error> { | ||
Url::parse(COINGECKO_URL).map_err(|e| Error::Other(format!("{:?}", e).into())) | ||
} | ||
} | ||
|
||
#[derive(Serialize, Deserialize, Debug)] | ||
pub struct CoinGeckoMarketStruct { | ||
id: String, | ||
symbol: String, | ||
name: String, | ||
current_price: Option<f32>, | ||
last_updated: Option<String>, | ||
} | ||
|
||
#[derive(Serialize, Deserialize, Debug)] | ||
pub struct CoinGeckoMarket(pub Vec<CoinGeckoMarketStruct>); | ||
|
||
impl RestPath<String> for CoinGeckoMarket { | ||
fn get_path(path: String) -> Result<String, itc_rest_client::error::Error> { | ||
Ok(path) | ||
} | ||
} | ||
|
||
impl GetExchangeRate for CoinGeckoClient { | ||
fn get_exchange_rate(&mut self, coin: &str, currency: &str) -> Result<f32, Error> { | ||
let response = self | ||
.client | ||
.get_with::<String, CoinGeckoMarket>( | ||
COINGECKO_PATH.to_string(), | ||
&[(COINGECKO_PARAM_CURRENCY, currency), (COINGECKO_PARAM_COIN, coin)], | ||
) | ||
.map_err(Error::RestClient)?; | ||
let list = response.0; | ||
if list.is_empty() { | ||
error!("Got no market data from coinGecko. Check params {},{}", currency, coin); | ||
return Err(Error::NoValidData) | ||
} | ||
match list[0].current_price { | ||
Some(r) => Ok(r), | ||
None => { | ||
error!("Failed to get the exchange rate of {} to {}", currency, coin); | ||
Err(Error::EmptyExchangeRate) | ||
}, | ||
} | ||
} | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
use super::*; | ||
|
||
#[test] | ||
fn get_exchange_rate_for_undefined_coins_fails() { | ||
let url = CoinGeckoClient::base_url().unwrap(); | ||
let mut coingecko_client = CoinGeckoClient::new(url); | ||
let result = coingecko_client.get_exchange_rate("invalid_coin", "usd"); | ||
assert_matches!(result, Err(Error::NoValidData)); | ||
} | ||
|
||
#[test] | ||
fn get_exchange_rate_for_undefined_currency_fails() { | ||
let url = CoinGeckoClient::base_url().unwrap(); | ||
let mut coingecko_client = CoinGeckoClient::new(url); | ||
let result = coingecko_client.get_exchange_rate("polkadot", "ch"); | ||
assert_matches!(result, Err(Error::RestClient(_))); | ||
} | ||
|
||
#[test] | ||
fn get_exchange_rate_from_coingecko_works() { | ||
let url = CoinGeckoClient::base_url().unwrap(); | ||
let mut coingecko_client = CoinGeckoClient::new(url); | ||
let dot_usd = coingecko_client.get_exchange_rate("polkadot", "usd").unwrap(); | ||
assert!(dot_usd > 0f32); | ||
let bit_usd = coingecko_client.get_exchange_rate("bitcoin", "usd").unwrap(); | ||
assert!(bit_usd > 0f32); | ||
let dot_chf = coingecko_client.get_exchange_rate("polkadot", "chf").unwrap(); | ||
assert!(dot_chf > 0f32); | ||
let bit_chf = coingecko_client.get_exchange_rate("bitcoin", "chf").unwrap(); | ||
assert!(bit_chf > 0f32); | ||
assert_eq!( | ||
(dot_usd * 100000. / bit_usd).round() / 100000., | ||
(dot_chf * 100000. / bit_chf).round() / 100000. | ||
); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
/* | ||
Copyright 2021 Integritee AG and Supercomputing Systems AG | ||
|
||
Licensed under the Apache License, Version 2.0 (the "License"); | ||
you may not use this file except in compliance with the License. | ||
You may obtain a copy of the License at | ||
|
||
http://www.apache.org/licenses/LICENSE-2.0 | ||
|
||
Unless required by applicable law or agreed to in writing, software | ||
distributed under the License is distributed on an "AS IS" BASIS, | ||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
See the License for the specific language governing permissions and | ||
limitations under the License. | ||
|
||
*/ | ||
#[cfg(all(not(feature = "std"), feature = "sgx"))] | ||
use crate::sgx_reexport_prelude::*; | ||
use std::boxed::Box; | ||
|
||
/// Exchange rate error | ||
#[derive(Debug, thiserror::Error)] | ||
pub enum Error { | ||
#[error("Rest client error")] | ||
RestClient(itc_rest_client::error::Error), | ||
#[error("Other error")] | ||
Other(Box<dyn std::error::Error>), | ||
#[error("Could not retrieve any data")] | ||
NoValidData, | ||
#[error("Value for exchange rate is null")] | ||
EmptyExchangeRate, | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
/* | ||
Copyright 2021 Integritee AG and Supercomputing Systems AG | ||
|
||
Licensed under the Apache License, Version 2.0 (the "License"); | ||
you may not use this file except in compliance with the License. | ||
You may obtain a copy of the License at | ||
|
||
http://www.apache.org/licenses/LICENSE-2.0 | ||
|
||
Unless required by applicable law or agreed to in writing, software | ||
distributed under the License is distributed on an "AS IS" BASIS, | ||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
See the License for the specific language governing permissions and | ||
limitations under the License. | ||
|
||
*/ | ||
|
||
#![cfg_attr(not(feature = "std"), no_std)] | ||
#![cfg_attr(test, feature(assert_matches))] | ||
|
||
#[cfg(all(feature = "std", feature = "sgx"))] | ||
compile_error!("feature \"std\" and feature \"sgx\" cannot be enabled at the same time"); | ||
|
||
#[cfg(all(not(feature = "std"), feature = "sgx"))] | ||
#[macro_use] | ||
extern crate sgx_tstd as std; | ||
|
||
// re-export module to properly feature gate sgx and regular std environment | ||
#[cfg(all(not(feature = "std"), feature = "sgx"))] | ||
pub mod sgx_reexport_prelude { | ||
pub use thiserror_sgx as thiserror; | ||
pub use url_sgx as url; | ||
} | ||
|
||
use crate::error::Error; | ||
|
||
pub mod coingecko; | ||
pub mod error; | ||
|
||
pub trait GetExchangeRate { | ||
/// Get the cryptocurrency/fiat_currency exchange rate | ||
fn get_exchange_rate( | ||
&mut self, | ||
cryptocurrency: &str, | ||
fiat_currency: &str, | ||
) -> Result<f32, Error>; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
pub const TEERACLE: &str = "Teeracle"; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We seem to have two versions of substrate-fixed here.