coingecko_oracle/
coingecko_oracle.rs1use blockless_sdk::http::HttpClient;
2use blockless_sdk::memory::read_stdin;
3use serde_json::json;
4use std::collections::HashMap;
5
6#[derive(Debug, serde::Serialize)]
7struct CoinPrice {
8 id: String,
9 price: u64,
10 currency: String,
11}
12
13fn main() {
14 let mut buf = [0; 1024];
16 let len = read_stdin(&mut buf).unwrap();
17 let coin_id = std::str::from_utf8(&buf[..len as usize])
18 .unwrap_or_default()
19 .trim();
20
21 let client = HttpClient::new();
23 let url = format!(
24 "https://api.coingecko.com/api/v3/simple/price?ids={}&vs_currencies=usd",
25 coin_id
26 );
27 let response = client.get(&url).send().unwrap();
28 let body = response.bytes().to_vec(); let json: serde_json::Result<HashMap<String, HashMap<String, f64>>> =
34 serde_json::from_slice(&body);
35 let Ok(data) = json else {
36 eprintln!("Failed to parse JSON");
37 return;
38 };
39 let Some(coin_data) = data.get(coin_id) else {
40 eprintln!("Coin not found in response.");
41 return;
42 };
43 let Some(usd_price) = coin_data.get("usd") else {
44 eprintln!("USD price not found for {}.", coin_id);
45 return;
46 };
47
48 let coin_price = CoinPrice {
49 id: coin_id.to_string(),
50 price: (*usd_price * 1_000_000.0) as u64, currency: "usd".to_string(),
52 };
53 println!("{}", json!(coin_price));
54}