Skip to content

Instantly share code, notes, and snippets.

@jongan69
Created June 29, 2024 18:32
Show Gist options
  • Save jongan69/0448c55a25ab572633507cb6e7aa0d63 to your computer and use it in GitHub Desktop.
Save jongan69/0448c55a25ab572633507cb6e7aa0d63 to your computer and use it in GitHub Desktop.
hOW MUCH LOCKIN IS ONE SOL WORTH
// SOL to SPL token price
use anyhow::{format_err, Result};
use reqwest::Client;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;
use std::error::Error as StdError;
use std::time::{SystemTime, UNIX_EPOCH};
// Constants
const SPL_TOKEN_ADDRESS: &str = "8Ki8DpuWNxu9VsS3kQbarsCWMcFGWkzzA8pUPto9zBd5";
const RAYDIUM_API_URL: &str = "https://api-v3.raydium.io";
// Structs
#[derive(Debug, Deserialize, Serialize)]
struct ApiResponse {
id: String,
success: bool,
data: HashMap<String, String>,
}
// Function to get the current nonce
pub fn get_nonce() -> String {
let start = SystemTime::now();
let since_the_epoch = start
.duration_since(UNIX_EPOCH)
.expect("Time went backwards");
let in_ms = since_the_epoch.as_millis();
in_ms.to_string()
}
// Function to get asset trading value in USD from Kraken
pub async fn get_asset_value(asset: &str) -> Result<f64, Box<dyn StdError>> {
// Construct the trading pair (e.g., "XBTUSD")
let pair = format!("{}USD", asset);
// Define the Kraken API endpoint
let api_url = format!("https://api.kraken.com/0/public/Ticker?pair={}", pair);
// Create a reqwest client
let client = Client::new();
// Send the GET request
let response = client.get(&api_url).send().await?.text().await?;
// Parse the JSON response
let json: Value = serde_json::from_str(&response)?;
// Extract the trading value in USD
if let Some(price) = json["result"][&pair]["c"][0].as_str() {
let price: f64 = price.parse()?;
return Ok(price);
}
Err("Unable to get trading value".into())
}
// Function to fetch SPL token price from Raydium
pub async 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()
.await
.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()
.await
.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))
}
}
// Combined function to get the SOL to SPL token price
pub async fn get_sol_to_spl_token_price() -> Result<f64> {
// Get the SOL value in USD from Kraken
let sol_usd_price = get_asset_value("SOL").await;
// Get the SPL token price from Raydium
let spl_token_price = fetch_token_price(SPL_TOKEN_ADDRESS).await?;
// Calculate the SOL to SPL token price
let sol_to_spl_token_price = sol_usd_price.unwrap() / spl_token_price;
Ok(sol_to_spl_token_price)
}
#[tokio::main]
async fn main() -> Result<()> {
// dotenv().ok();
let sol_to_spl_price = get_sol_to_spl_token_price().await?;
println!("SOL to SPL token price: {}", sol_to_spl_price);
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment