solagent_plugin_jupiter/fetch_price.rs
1// Copyright 2025 zTgx
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#![allow(dead_code)]
16
17use crate::JUP_PRICE_V2;
18use serde::Deserialize;
19
20#[derive(Deserialize, Debug)]
21struct PriceResponse {
22 data: std::collections::HashMap<String, TokenData>,
23}
24
25#[derive(Deserialize, Debug)]
26struct TokenData {
27 id: Option<String>,
28
29 #[serde(rename = "type")]
30 typed: Option<String>,
31 price: Option<String>,
32}
33
34/// Fetches the price of a given token quoted in USDC using Jupiter API.
35///
36/// # Parameters
37///
38/// - `token_id`: The token mint address as a string.
39///
40/// # Returns
41///
42/// The price of the token quoted in USDC as a string.
43pub async fn fetch_price(token_id: &str) -> Result<String, Box<dyn std::error::Error>> {
44 let url = format!("{}{}", JUP_PRICE_V2, token_id);
45 let response = reqwest::get(&url).await?;
46 if !response.status().is_success() {
47 return Err(format!("Failed to fetch price: {}", response.status()).into());
48 }
49
50 let data: PriceResponse = response.json().await?;
51 // Get the price for the given token_id
52 if let Some(token_data) = data.data.get(token_id) {
53 if let Some(price) = &token_data.price {
54 return Ok(price.clone());
55 }
56 }
57
58 Err("Price data not available for the given token.".into())
59}