Skip to content

Instantly share code, notes, and snippets.

@jongan69
Created June 29, 2024 15:45
Show Gist options
  • Save jongan69/f816316cc7c9c2e36008932c61eb4721 to your computer and use it in GitHub Desktop.
Save jongan69/f816316cc7c9c2e36008932c61eb4721 to your computer and use it in GitHub Desktop.
Get the USD price of lockin
[package]
name = "raytest"
version = "0.1.0"
edition = "2021"
[dependencies]
anyhow = "1.0"
reqwest = { version = "0.11", features = ["blocking", "json"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
use anyhow::{format_err, Result};
use reqwest::blocking::Client;
use serde::Deserialize;
use std::collections::HashMap;
const SPL_TOKEN_ADDRESS: &str = "8Ki8DpuWNxu9VsS3kQbarsCWMcFGWkzzA8pUPto9zBd5";
const RAYDIUM_API_URL: &str = "https://api-v3.raydium.io";
#[derive(Debug, Deserialize)]
struct ApiResponse {
id: String,
success: bool,
data: HashMap<String, String>,
}
fn main() -> Result<()> {
let spl_token_mint = SPL_TOKEN_ADDRESS.to_string();
let price = fetch_token_price(&spl_token_mint)?;
println!("Price of {}: {}", spl_token_mint, price);
Ok(())
}
fn fetch_token_price(token_mint: &str) -> Result<f64> {
let client = Client::new();
let url = format!("{}/mint/price?mints={}", RAYDIUM_API_URL, token_mint);
let response = client
.get(&url)
.header("accept", "application/json")
.send()
.map_err(|e| format_err!("Failed to send request: {}", e))?;
if !response.status().is_success() {
return Err(format_err!("Failed to fetch price: HTTP {}", response.status()));
}
let response_json: ApiResponse = response
.json()
.map_err(|e| format_err!("Failed to parse JSON response: {}", e))?;
if let Some(price_str) = response_json.data.get(token_mint) {
let price: f64 = price_str.parse().map_err(|e| format_err!("Failed to parse price: {}", e))?;
Ok(price)
} else {
Err(format_err!("No price found for mint: {}", token_mint))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment