use crate::{Result, ToolkitError};
use serde::{Deserialize, Serialize};
use solana_client::nonblocking::rpc_client::RpcClient;
use solana_sdk::{
commitment_config::CommitmentConfig,
signature::{Keypair, Signature},
signer::Signer,
transaction::VersionedTransaction,
};
pub const JUPITER_API_URL: &str = "https://quote-api.jup.ag/v6";
pub mod mints {
use solana_sdk::pubkey::Pubkey;
use std::str::FromStr;
lazy_static::lazy_static! {
pub static ref SOL: Pubkey = Pubkey::from_str("So11111111111111111111111111111111111111112").unwrap();
pub static ref USDC: Pubkey = Pubkey::from_str("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v").unwrap();
pub static ref USDT: Pubkey = Pubkey::from_str("Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB").unwrap();
pub static ref BONK: Pubkey = Pubkey::from_str("DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263").unwrap();
pub static ref JUP: Pubkey = Pubkey::from_str("JUPyiwrYJFskUPiHa7hkeR8VUtAeFoSYbKedZNsDvCN").unwrap();
pub static ref RAY: Pubkey = Pubkey::from_str("4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R").unwrap();
}
}
pub struct JupiterClient {
rpc_client: RpcClient,
api_url: String,
http_client: reqwest::Client,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct QuoteResponse {
pub input_mint: String,
#[serde(deserialize_with = "deserialize_string_to_u64")]
pub in_amount: u64,
pub output_mint: String,
#[serde(deserialize_with = "deserialize_string_to_u64")]
pub out_amount: u64,
#[serde(deserialize_with = "deserialize_string_to_u64")]
pub other_amount_threshold: u64,
pub swap_mode: String,
pub slippage_bps: u16,
pub price_impact_pct: String,
pub route_plan: Vec<RoutePlanStep>,
#[serde(default)]
pub context_slot: Option<u64>,
#[serde(default)]
pub time_taken: Option<f64>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RoutePlanStep {
pub swap_info: SwapInfo,
pub percent: u8,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SwapInfo {
pub amm_key: String,
pub label: Option<String>,
pub input_mint: String,
pub output_mint: String,
#[serde(deserialize_with = "deserialize_string_to_u64")]
pub in_amount: u64,
#[serde(deserialize_with = "deserialize_string_to_u64")]
pub out_amount: u64,
#[serde(deserialize_with = "deserialize_string_to_u64")]
pub fee_amount: u64,
pub fee_mint: String,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SwapRequest {
pub user_public_key: String,
pub quote_response: QuoteResponse,
#[serde(skip_serializing_if = "Option::is_none")]
pub wrap_and_unwrap_sol: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub use_shared_accounts: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub fee_account: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub compute_unit_price_micro_lamports: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub use_token_ledger: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub destination_token_account: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub dynamic_compute_unit_limit: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub skip_user_accounts_rpc_calls: Option<bool>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SwapResponse {
pub swap_transaction: String,
pub last_valid_block_height: u64,
#[serde(default)]
pub priority_fee: Option<String>,
}
#[derive(Debug, Clone)]
pub struct SwapConfig {
pub slippage_bps: u16,
pub priority_fee_micro_lamports: Option<u64>,
pub wrap_unwrap_sol: bool,
pub use_shared_accounts: bool,
pub dynamic_compute_unit_limit: bool,
}
impl Default for SwapConfig {
fn default() -> Self {
Self {
slippage_bps: 50, priority_fee_micro_lamports: None,
wrap_unwrap_sol: true,
use_shared_accounts: true,
dynamic_compute_unit_limit: true,
}
}
}
impl SwapConfig {
pub fn with_slippage(slippage_bps: u16) -> Self {
Self {
slippage_bps,
..Default::default()
}
}
pub fn with_priority_fee(mut self, micro_lamports: u64) -> Self {
self.priority_fee_micro_lamports = Some(micro_lamports);
self
}
}
impl JupiterClient {
pub const SOL_MINT: &'static str = "So11111111111111111111111111111111111111112";
pub const USDC_MINT: &'static str = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";
pub const USDT_MINT: &'static str = "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB";
pub fn new(rpc_url: &str) -> Self {
Self::with_api_url(rpc_url, JUPITER_API_URL)
}
pub fn with_api_url(rpc_url: &str, api_url: &str) -> Self {
Self {
rpc_client: RpcClient::new_with_commitment(
rpc_url.to_string(),
CommitmentConfig::confirmed(),
),
api_url: api_url.to_string(),
http_client: reqwest::Client::new(),
}
}
pub async fn get_quote(
&self,
input_mint: &str,
output_mint: &str,
amount: u64,
slippage_bps: u16,
) -> Result<QuoteResponse> {
let url = format!(
"{}/quote?inputMint={}&outputMint={}&amount={}&slippageBps={}",
self.api_url, input_mint, output_mint, amount, slippage_bps
);
let response = self
.http_client
.get(&url)
.send()
.await
.map_err(|e| ToolkitError::NetworkError(e.to_string()))?;
if !response.status().is_success() {
let error_text = response.text().await.unwrap_or_default();
return Err(ToolkitError::JupiterError(format!(
"Quote request failed: {}",
error_text
)));
}
let quote: QuoteResponse = response
.json()
.await
.map_err(|e| ToolkitError::ParseError(e.to_string()))?;
Ok(quote)
}
pub async fn get_quote_exact_out(
&self,
input_mint: &str,
output_mint: &str,
amount: u64,
slippage_bps: u16,
) -> Result<QuoteResponse> {
let url = format!(
"{}/quote?inputMint={}&outputMint={}&amount={}&slippageBps={}&swapMode=ExactOut",
self.api_url, input_mint, output_mint, amount, slippage_bps
);
let response = self
.http_client
.get(&url)
.send()
.await
.map_err(|e| ToolkitError::NetworkError(e.to_string()))?;
if !response.status().is_success() {
let error_text = response.text().await.unwrap_or_default();
return Err(ToolkitError::JupiterError(format!(
"Quote request failed: {}",
error_text
)));
}
let quote: QuoteResponse = response
.json()
.await
.map_err(|e| ToolkitError::ParseError(e.to_string()))?;
Ok(quote)
}
pub async fn swap(&self, wallet: &Keypair, quote: QuoteResponse) -> Result<Signature> {
self.swap_with_config(wallet, quote, SwapConfig::default())
.await
}
pub async fn swap_with_config(
&self,
wallet: &Keypair,
quote: QuoteResponse,
config: SwapConfig,
) -> Result<Signature> {
let swap_request = SwapRequest {
user_public_key: wallet.pubkey().to_string(),
quote_response: quote,
wrap_and_unwrap_sol: Some(config.wrap_unwrap_sol),
use_shared_accounts: Some(config.use_shared_accounts),
fee_account: None,
compute_unit_price_micro_lamports: config.priority_fee_micro_lamports,
use_token_ledger: None,
destination_token_account: None,
dynamic_compute_unit_limit: Some(config.dynamic_compute_unit_limit),
skip_user_accounts_rpc_calls: None,
};
let url = format!("{}/swap", self.api_url);
let response = self
.http_client
.post(&url)
.json(&swap_request)
.send()
.await
.map_err(|e| ToolkitError::NetworkError(e.to_string()))?;
if !response.status().is_success() {
let error_text = response.text().await.unwrap_or_default();
return Err(ToolkitError::JupiterError(format!(
"Swap request failed: {}",
error_text
)));
}
let swap_response: SwapResponse = response
.json()
.await
.map_err(|e| ToolkitError::ParseError(e.to_string()))?;
let tx_bytes = base64::Engine::decode(
&base64::engine::general_purpose::STANDARD,
&swap_response.swap_transaction,
)
.map_err(|e| ToolkitError::ParseError(format!("Failed to decode transaction: {}", e)))?;
let mut versioned_tx: VersionedTransaction = bincode::deserialize(&tx_bytes)
.map_err(|e| ToolkitError::ParseError(format!("Failed to deserialize tx: {}", e)))?;
let recent_blockhash = self
.rpc_client
.get_latest_blockhash()
.await
.map_err(|e| ToolkitError::RpcError(e.to_string()))?;
versioned_tx
.message
.set_recent_blockhash(recent_blockhash);
let signed_tx = VersionedTransaction::try_new(versioned_tx.message, &[wallet])
.map_err(|e| ToolkitError::SigningError(e.to_string()))?;
let signature = self
.rpc_client
.send_and_confirm_transaction(&signed_tx)
.await
.map_err(|e| ToolkitError::TransactionError(e.to_string()))?;
Ok(signature)
}
pub async fn simple_swap(
&self,
wallet: &Keypair,
input_mint: &str,
output_mint: &str,
amount: u64,
slippage_bps: u16,
) -> Result<Signature> {
let quote = self
.get_quote(input_mint, output_mint, amount, slippage_bps)
.await?;
self.swap(wallet, quote).await
}
pub async fn get_price(
&self,
input_mint: &str,
output_mint: &str,
amount: u64,
) -> Result<u64> {
let quote = self.get_quote(input_mint, output_mint, amount, 50).await?;
Ok(quote.out_amount)
}
pub async fn get_price_impact(
&self,
input_mint: &str,
output_mint: &str,
amount: u64,
) -> Result<String> {
let quote = self.get_quote(input_mint, output_mint, amount, 50).await?;
Ok(quote.price_impact_pct)
}
pub async fn get_route_labels(
&self,
input_mint: &str,
output_mint: &str,
amount: u64,
) -> Result<Vec<String>> {
let quote = self.get_quote(input_mint, output_mint, amount, 50).await?;
Ok(quote
.route_plan
.iter()
.filter_map(|step| step.swap_info.label.clone())
.collect())
}
}
fn deserialize_string_to_u64<'de, D>(deserializer: D) -> std::result::Result<u64, D::Error>
where
D: serde::Deserializer<'de>,
{
let s: String = Deserialize::deserialize(deserializer)?;
s.parse::<u64>().map_err(serde::de::Error::custom)
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn test_get_quote() {
let jupiter = JupiterClient::new("https://api.mainnet-beta.solana.com");
let result = jupiter
.get_quote(
JupiterClient::USDC_MINT,
JupiterClient::SOL_MINT,
1_000_000, 50,
)
.await;
if let Ok(quote) = result {
assert!(!quote.input_mint.is_empty());
assert!(!quote.output_mint.is_empty());
assert!(quote.out_amount > 0);
}
}
#[test]
fn test_swap_config_default() {
let config = SwapConfig::default();
assert_eq!(config.slippage_bps, 50);
assert!(config.wrap_unwrap_sol);
assert!(config.use_shared_accounts);
}
#[test]
fn test_swap_config_builder() {
let config = SwapConfig::with_slippage(100).with_priority_fee(5000);
assert_eq!(config.slippage_bps, 100);
assert_eq!(config.priority_fee_micro_lamports, Some(5000));
}
}