Files
sol-trade-sdk/src/lib.rs
T

757 lines
26 KiB
Rust
Raw Normal View History

2024-12-31 16:51:58 +08:00
pub mod accounts;
pub mod constants;
pub mod error;
pub mod instruction;
pub mod utils;
2025-01-03 14:43:26 +08:00
pub mod jito;
2025-01-23 17:48:10 +08:00
pub mod grpc;
2025-01-23 21:15:55 +08:00
pub mod common;
2024-12-31 16:51:58 +08:00
2025-02-12 20:12:14 +08:00
use anyhow::anyhow;
2025-02-13 15:22:35 +08:00
use solana_client::{connection_cache::ConnectionCache, rpc_client::RpcClient, rpc_config::{RpcSendTransactionConfig, RpcSimulateTransactionConfig}, send_and_confirm_transactions_in_parallel::{send_and_confirm_transactions_in_parallel, SendAndConfirmConfig}, tpu_client::{TpuClient, TpuClientConfig}};
2025-01-23 17:48:10 +08:00
use solana_sdk::{
commitment_config::CommitmentConfig,
pubkey::Pubkey,
signature::{Keypair, Signature},
signer::Signer,
instruction::Instruction,
system_instruction,
compute_budget::ComputeBudgetInstruction,
transaction::Transaction,
2024-12-31 16:51:58 +08:00
};
2025-01-23 17:48:10 +08:00
use spl_associated_token_account::{
2024-12-31 16:51:58 +08:00
get_associated_token_address,
2025-01-25 01:04:45 +08:00
instruction::create_associated_token_account,
2024-12-31 16:51:58 +08:00
};
2025-01-14 19:18:48 +08:00
2025-01-25 17:16:52 +08:00
use common::{logs_data::TradeInfo, logs_events::PumpfunEvent, logs_subscribe};
2025-01-23 21:15:55 +08:00
use common::logs_subscribe::SubscriptionHandle;
2025-01-25 01:04:45 +08:00
use spl_token::instruction::close_account;
2025-01-03 14:43:26 +08:00
2024-12-31 16:51:58 +08:00
use std::sync::Arc;
2025-01-03 14:43:26 +08:00
use std::time::Instant;
use crate::jito::JitoClient;
2025-01-23 17:48:10 +08:00
use borsh::BorshDeserialize;
2025-01-09 00:12:43 +08:00
// Constants
2025-01-13 18:42:21 +08:00
const DEFAULT_SLIPPAGE: u64 = 1000; // 10%
2025-01-27 11:25:24 +08:00
const DEFAULT_COMPUTE_UNIT_LIMIT: u32 = 78000;
const DEFAULT_COMPUTE_UNIT_PRICE: u64 = 3_500_000;
2025-02-10 15:20:33 +08:00
const JITO_TIP_AMOUNT: u64 = 5644005;
2025-02-13 15:22:35 +08:00
const WS_URL: &str = "ws://127.0.0.1:8900";
2024-12-31 16:51:58 +08:00
2025-01-09 00:12:43 +08:00
/// Priority fee configuration
2024-12-31 16:51:58 +08:00
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PriorityFee {
pub limit: Option<u32>,
pub price: Option<u64>,
}
2025-01-09 16:59:05 +08:00
impl Default for PriorityFee {
fn default() -> Self {
Self { limit: Some(DEFAULT_COMPUTE_UNIT_LIMIT), price: Some(DEFAULT_COMPUTE_UNIT_PRICE) }
}
}
2024-12-31 16:51:58 +08:00
pub struct PumpFun {
pub rpc: RpcClient,
pub payer: Arc<Keypair>,
2025-01-08 16:33:43 +08:00
pub jito_client: Option<JitoClient>,
2025-01-09 00:12:43 +08:00
}
impl Clone for PumpFun {
fn clone(&self) -> Self {
Self {
rpc: RpcClient::new_with_commitment(
self.rpc.url().to_string(),
self.rpc.commitment()
),
payer: self.payer.clone(),
jito_client: self.jito_client.clone(),
}
}
2024-12-31 16:51:58 +08:00
}
impl PumpFun {
2025-01-09 00:12:43 +08:00
/// Create a new PumpFun client instance
2024-12-31 16:51:58 +08:00
pub fn new(
2025-01-23 17:48:10 +08:00
rpc_url: String,
2025-01-09 00:12:43 +08:00
commitment: Option<CommitmentConfig>,
2024-12-31 16:51:58 +08:00
payer: Arc<Keypair>,
2025-01-09 00:12:43 +08:00
jito_url: Option<String>,
2024-12-31 16:51:58 +08:00
) -> Self {
2025-01-09 00:12:43 +08:00
let rpc = RpcClient::new_with_commitment(
2025-01-23 17:48:10 +08:00
rpc_url,
2025-01-25 16:31:11 +08:00
commitment.unwrap_or(CommitmentConfig::processed())
2025-01-09 15:43:21 +08:00
);
2024-12-31 16:51:58 +08:00
2025-01-14 19:18:48 +08:00
let jito_client = jito_url.map(|url| JitoClient::new(&url, None));
2025-01-03 14:43:26 +08:00
2024-12-31 16:51:58 +08:00
Self {
rpc,
payer,
2025-01-03 14:43:26 +08:00
jito_client,
2024-12-31 16:51:58 +08:00
}
}
2025-01-09 00:12:43 +08:00
/// Create a new token
2024-12-31 16:51:58 +08:00
pub async fn create(
&self,
mint: &Keypair,
metadata: utils::CreateTokenMetadata,
priority_fee: Option<PriorityFee>,
2025-02-12 22:46:09 +08:00
) -> Result<Signature, anyhow::Error> {
2025-01-08 16:33:43 +08:00
let ipfs = utils::create_token_metadata(metadata)
2024-12-31 16:51:58 +08:00
.await
2025-02-12 22:46:09 +08:00
.map_err(|_| anyhow!("Failed to upload metadata"))?;
2024-12-31 16:51:58 +08:00
2025-01-09 00:12:43 +08:00
let mut instructions = self.create_priority_fee_instructions(priority_fee);
2024-12-31 16:51:58 +08:00
2025-01-09 00:12:43 +08:00
instructions.push(instruction::create(
2025-01-09 01:21:20 +08:00
&self.payer.clone(),
2024-12-31 16:51:58 +08:00
mint,
2025-01-23 17:48:10 +08:00
instruction::Create {
2024-12-31 16:51:58 +08:00
_name: ipfs.metadata.name,
_symbol: ipfs.metadata.symbol,
_uri: ipfs.metadata.image,
},
));
2025-01-09 00:12:43 +08:00
let recent_blockhash = self.rpc.get_latest_blockhash()?;
let transaction = Transaction::new_signed_with_payer(
&instructions,
Some(&self.payer.pubkey()),
&[&self.payer.clone(), mint],
recent_blockhash,
);
2024-12-31 16:51:58 +08:00
2025-01-09 00:12:43 +08:00
let signature = self.rpc.send_and_confirm_transaction(&transaction)?;
2024-12-31 16:51:58 +08:00
Ok(signature)
}
2025-01-09 00:12:43 +08:00
/// Create and buy tokens in one transaction
2024-12-31 16:51:58 +08:00
pub async fn create_and_buy(
&self,
mint: &Keypair,
metadata: utils::CreateTokenMetadata,
amount_sol: u64,
slippage_basis_points: Option<u64>,
priority_fee: Option<PriorityFee>,
2025-02-12 22:46:09 +08:00
) -> Result<Signature, anyhow::Error> {
2025-01-08 16:33:43 +08:00
let ipfs = utils::create_token_metadata(metadata)
2024-12-31 16:51:58 +08:00
.await
2025-02-12 22:46:09 +08:00
.map_err(|e| anyhow!(e.to_string()))?;
2024-12-31 16:51:58 +08:00
let global_account = self.get_global_account()?;
let buy_amount = global_account.get_initial_buy_price(amount_sol);
let buy_amount_with_slippage =
2025-01-08 16:33:43 +08:00
utils::calculate_with_slippage_buy(amount_sol, slippage_basis_points.unwrap_or(DEFAULT_SLIPPAGE));
2024-12-31 16:51:58 +08:00
2025-01-09 00:12:43 +08:00
let mut instructions = self.create_priority_fee_instructions(priority_fee);
2024-12-31 16:51:58 +08:00
2025-01-09 00:12:43 +08:00
instructions.push(instruction::create(
2025-01-09 01:21:20 +08:00
&self.payer.clone(),
2024-12-31 16:51:58 +08:00
mint,
2025-01-23 17:48:10 +08:00
instruction::Create {
2024-12-31 16:51:58 +08:00
_name: ipfs.metadata.name,
_symbol: ipfs.metadata.symbol,
_uri: ipfs.metadata.image,
},
));
2025-01-08 16:33:43 +08:00
let ata = get_associated_token_address(&self.payer.pubkey(), &mint.pubkey());
2024-12-31 16:51:58 +08:00
if self.rpc.get_account(&ata).is_err() {
2025-01-09 00:12:43 +08:00
instructions.push(create_associated_token_account(
2024-12-31 16:51:58 +08:00
&self.payer.pubkey(),
&self.payer.pubkey(),
&mint.pubkey(),
2025-01-25 01:04:45 +08:00
&constants::accounts::TOKEN_PROGRAM,
2024-12-31 16:51:58 +08:00
));
}
2025-01-09 00:12:43 +08:00
instructions.push(instruction::buy(
2025-01-09 01:21:20 +08:00
&self.payer.clone(),
2024-12-31 16:51:58 +08:00
&mint.pubkey(),
&global_account.fee_recipient,
2025-01-23 17:48:10 +08:00
instruction::Buy {
2024-12-31 16:51:58 +08:00
_amount: buy_amount,
_max_sol_cost: buy_amount_with_slippage,
},
));
2025-01-09 00:12:43 +08:00
let recent_blockhash = self.rpc.get_latest_blockhash()?;
let transaction = Transaction::new_signed_with_payer(
&instructions,
Some(&self.payer.pubkey()),
&[&self.payer.clone(), mint],
recent_blockhash,
);
let signature = self.rpc.send_and_confirm_transaction(&transaction)?;
2024-12-31 16:51:58 +08:00
Ok(signature)
}
2025-01-09 00:12:43 +08:00
/// Buy tokens
2024-12-31 16:51:58 +08:00
pub async fn buy(
&self,
mint: &Pubkey,
amount_sol: u64,
slippage_basis_points: Option<u64>,
priority_fee: Option<PriorityFee>,
2025-02-12 22:46:09 +08:00
) -> Result<Signature, anyhow::Error> {
2024-12-31 16:51:58 +08:00
let global_account = self.get_global_account()?;
let bonding_curve_account = self.get_bonding_curve_account(mint)?;
let buy_amount = bonding_curve_account
.get_buy_price(amount_sol)
2025-02-12 22:46:09 +08:00
.map_err(|e| anyhow!(e))?;
2024-12-31 16:51:58 +08:00
let buy_amount_with_slippage =
2025-01-08 16:33:43 +08:00
utils::calculate_with_slippage_buy(amount_sol, slippage_basis_points.unwrap_or(DEFAULT_SLIPPAGE));
2024-12-31 16:51:58 +08:00
2025-01-09 00:12:43 +08:00
let mut instructions = self.create_priority_fee_instructions(priority_fee);
2024-12-31 16:51:58 +08:00
2025-01-08 16:33:43 +08:00
let ata = get_associated_token_address(&self.payer.pubkey(), mint);
2024-12-31 16:51:58 +08:00
if self.rpc.get_account(&ata).is_err() {
2025-01-09 00:12:43 +08:00
instructions.push(create_associated_token_account(
2024-12-31 16:51:58 +08:00
&self.payer.pubkey(),
&self.payer.pubkey(),
mint,
2025-01-25 01:04:45 +08:00
&constants::accounts::TOKEN_PROGRAM,
2024-12-31 16:51:58 +08:00
));
}
2025-01-09 00:12:43 +08:00
instructions.push(instruction::buy(
&self.payer.clone(),
2024-12-31 16:51:58 +08:00
mint,
&global_account.fee_recipient,
2025-01-23 17:48:10 +08:00
instruction::Buy {
2024-12-31 16:51:58 +08:00
_amount: buy_amount,
_max_sol_cost: buy_amount_with_slippage,
},
));
2025-01-09 00:12:43 +08:00
let recent_blockhash = self.rpc.get_latest_blockhash()?;
let transaction = Transaction::new_signed_with_payer(
&instructions,
Some(&self.payer.pubkey()),
&[&self.payer.clone()],
recent_blockhash,
);
let signature = self.rpc.send_transaction(&transaction)?;
2024-12-31 16:51:58 +08:00
Ok(signature)
}
2025-01-09 00:12:43 +08:00
/// Buy tokens using Jito
2025-01-03 14:43:26 +08:00
pub async fn buy_with_jito(
&self,
mint: &Pubkey,
2025-01-25 17:16:52 +08:00
buy_token_amount: u64,
max_sol_cost: u64,
2025-01-03 14:43:26 +08:00
slippage_basis_points: Option<u64>,
2025-01-25 19:45:18 +08:00
jito_fee: Option<u64>,
2025-02-12 22:46:09 +08:00
) -> Result<String, anyhow::Error> {
2025-01-03 14:43:26 +08:00
let start_time = Instant::now();
2025-01-09 00:12:43 +08:00
let jito_client = self.jito_client.as_ref()
2025-02-12 22:46:09 +08:00
.ok_or_else(|| anyhow!("Jito client not found"))?;
2025-01-03 14:43:26 +08:00
let global_account = self.get_global_account()?;
let buy_amount_with_slippage =
2025-01-25 17:16:52 +08:00
utils::calculate_with_slippage_buy(max_sol_cost, slippage_basis_points.unwrap_or(DEFAULT_SLIPPAGE));
2025-01-03 14:43:26 +08:00
2025-02-13 00:08:14 +08:00
let mut instructions = self.create_priority_fee_instructions(None);
2025-02-12 20:12:14 +08:00
let tip_account = jito_client.get_tip_account().await.map_err(|e| anyhow!(e)).unwrap();
2025-01-08 16:33:43 +08:00
let ata = get_associated_token_address(&self.payer.pubkey(), mint);
2025-01-03 14:43:26 +08:00
if self.rpc.get_account(&ata).is_err() {
instructions.push(create_associated_token_account(
&self.payer.pubkey(),
&self.payer.pubkey(),
mint,
2025-01-25 01:04:45 +08:00
&constants::accounts::TOKEN_PROGRAM,
2025-01-03 14:43:26 +08:00
));
}
instructions.push(instruction::buy(
2025-01-25 15:36:09 +08:00
&self.payer.clone(),
2025-01-03 14:43:26 +08:00
mint,
&global_account.fee_recipient,
2025-01-23 17:48:10 +08:00
instruction::Buy {
2025-01-25 17:16:52 +08:00
_amount: buy_token_amount,
2025-01-03 14:43:26 +08:00
_max_sol_cost: buy_amount_with_slippage,
},
));
2025-01-25 19:45:18 +08:00
let jito_fee = jito_fee.unwrap_or(JITO_TIP_AMOUNT);
2025-01-03 14:43:26 +08:00
instructions.push(
system_instruction::transfer(
&self.payer.pubkey(),
&tip_account,
2025-01-25 19:45:18 +08:00
jito_fee,
2025-01-03 14:43:26 +08:00
),
);
let recent_blockhash = self.rpc.get_latest_blockhash()?;
let transaction = Transaction::new_signed_with_payer(
&instructions,
Some(&self.payer.pubkey()),
&[&self.payer.clone()],
recent_blockhash,
);
2025-01-08 16:33:43 +08:00
let signature = jito_client.send_transaction(&transaction).await?;
2025-01-03 14:43:26 +08:00
println!("Total Jito buy operation time: {:?}ms", start_time.elapsed().as_millis());
Ok(signature)
}
2025-01-09 00:12:43 +08:00
/// Sell tokens
2024-12-31 16:51:58 +08:00
pub async fn sell(
&self,
mint: &Pubkey,
amount_token: Option<u64>,
slippage_basis_points: Option<u64>,
priority_fee: Option<PriorityFee>,
2025-02-13 15:22:35 +08:00
) -> Result<(), anyhow::Error> {
// 获取代币账户余额
2025-01-08 16:33:43 +08:00
let ata = get_associated_token_address(&self.payer.pubkey(), mint);
let balance = self.rpc.get_token_account_balance(&ata)?;
2025-01-09 00:12:43 +08:00
let balance_u64 = balance.amount.parse::<u64>()
2025-02-12 22:46:09 +08:00
.map_err(|_| anyhow!("Failed to parse token balance"))?;
2025-01-08 16:33:43 +08:00
let amount = amount_token.unwrap_or(balance_u64);
if amount == 0 {
2025-02-12 22:46:09 +08:00
return Err(anyhow!("Balance is 0"));
2025-01-07 13:18:31 +08:00
}
2025-02-13 15:22:35 +08:00
// 计算最小SOL输出
2025-01-07 13:18:31 +08:00
let global_account = self.get_global_account()?;
let bonding_curve_account = self.get_bonding_curve_account(mint)?;
let min_sol_output = bonding_curve_account
2025-01-08 16:33:43 +08:00
.get_sell_price(amount, global_account.fee_basis_points)
2025-02-12 22:46:09 +08:00
.map_err(|e| anyhow!(e))?;
2025-01-08 16:33:43 +08:00
let min_sol_output_with_slippage = utils::calculate_with_slippage_sell(
2025-01-07 13:18:31 +08:00
min_sol_output,
2025-01-08 16:33:43 +08:00
slippage_basis_points.unwrap_or(DEFAULT_SLIPPAGE),
2025-01-07 13:18:31 +08:00
);
2025-02-13 15:22:35 +08:00
// 构建指令
let mut instructions = vec![
ComputeBudgetInstruction::set_compute_unit_limit(1_400_000),
ComputeBudgetInstruction::set_compute_unit_price(0),
];
2025-01-07 13:18:31 +08:00
2025-01-09 00:12:43 +08:00
instructions.push(instruction::sell(
2025-01-09 01:21:20 +08:00
&self.payer.clone(),
2025-01-07 13:18:31 +08:00
mint,
&global_account.fee_recipient,
2025-01-23 17:48:10 +08:00
instruction::Sell {
2025-01-08 16:33:43 +08:00
_amount: amount,
_min_sol_output: min_sol_output_with_slippage,
2025-01-07 13:18:31 +08:00
},
));
2025-01-25 01:04:45 +08:00
instructions.push(close_account(
&spl_token::ID,
&ata,
&self.payer.pubkey(),
&self.payer.pubkey(),
&[&self.payer.pubkey()],
).unwrap());
2025-02-13 15:22:35 +08:00
// 获取最新区块哈希
let commitment_config = CommitmentConfig::confirmed();
let recent_blockhash = self.rpc.get_latest_blockhash_with_commitment(commitment_config)
.map_err(|_| anyhow!("Failed to get latest blockhash"))?
.0;
let simulate_tx = Transaction::new_signed_with_payer(
&instructions,
Some(&self.payer.pubkey()),
&[&self.payer.clone()],
recent_blockhash,
);
// 模拟交易
let config = RpcSimulateTransactionConfig {
sig_verify: true,
commitment: Some(commitment_config),
..RpcSimulateTransactionConfig::default()
};
let result = self.rpc.simulate_transaction_with_config(&simulate_tx, config)?
.value;
if result.logs.as_ref().map_or(true, |logs| logs.is_empty()) {
return Err(anyhow!("Simulation failed: {:?}", result.err));
}
// 更新计算单元和优先费用
let result_cu = result.units_consumed.ok_or_else(|| anyhow!("No compute units consumed"))?;
let fees = self.rpc.get_recent_prioritization_fees(&[])?;
let average_fees = fees.iter()
.map(|fee| fee.prioritization_fee)
.sum::<u64>() / fees.len() as u64;
let unit_price = match priority_fee {
None => average_fees,
Some(pf) => pf.price.unwrap_or(DEFAULT_COMPUTE_UNIT_PRICE)
};
instructions[0] = ComputeBudgetInstruction::set_compute_unit_limit(result_cu as u32);
instructions[1] = ComputeBudgetInstruction::set_compute_unit_price(unit_price);
2025-01-09 00:12:43 +08:00
let transaction = Transaction::new_signed_with_payer(
&instructions,
Some(&self.payer.pubkey()),
&[&self.payer.clone()],
recent_blockhash,
);
2025-02-13 15:22:35 +08:00
// 发送交易
self.rpc.send_and_confirm_transaction(&transaction)?;
Ok(())
2025-01-07 13:18:31 +08:00
}
2025-01-09 00:12:43 +08:00
/// Sell tokens by percentage
2025-01-07 13:18:31 +08:00
pub async fn sell_by_percent(
&self,
mint: &Pubkey,
percent: u64,
slippage_basis_points: Option<u64>,
priority_fee: Option<PriorityFee>,
2025-02-13 15:22:35 +08:00
) -> Result<(), anyhow::Error> {
2025-01-09 00:12:43 +08:00
if percent > 100 {
2025-02-12 22:46:09 +08:00
return Err(anyhow!("Percentage must be between 0 and 100"));
2025-01-09 00:12:43 +08:00
}
2025-01-08 16:33:43 +08:00
let ata = get_associated_token_address(&self.payer.pubkey(), mint);
let balance = self.rpc.get_token_account_balance(&ata)?;
2025-01-09 00:12:43 +08:00
let balance_u64 = balance.amount.parse::<u64>()
2025-02-12 22:46:09 +08:00
.map_err(|_| anyhow!("Failed to parse token balance"))?;
2025-01-08 16:33:43 +08:00
2025-01-07 13:18:31 +08:00
if balance_u64 == 0 {
2025-02-12 22:46:09 +08:00
return Err(anyhow!("Balance is 0"));
2025-01-07 13:18:31 +08:00
}
2025-01-08 16:33:43 +08:00
let amount = balance_u64 * percent / 100;
self.sell(mint, Some(amount), slippage_basis_points, priority_fee).await
2024-12-31 16:51:58 +08:00
}
2025-01-14 19:18:48 +08:00
pub async fn sell_by_percent_with_jito(
&self,
mint: &Pubkey,
percent: u64,
slippage_basis_points: Option<u64>,
2025-02-10 15:20:33 +08:00
jito_fee: Option<u64>,
2025-02-12 22:46:09 +08:00
) -> Result<String, anyhow::Error> {
2025-01-14 19:18:48 +08:00
if percent > 100 {
2025-02-12 22:46:09 +08:00
return Err(anyhow!("Percentage must be between 0 and 100"));
2025-01-14 19:18:48 +08:00
}
let ata = get_associated_token_address(&self.payer.pubkey(), mint);
let balance = self.rpc.get_token_account_balance(&ata)?;
let balance_u64 = balance.amount.parse::<u64>()
2025-02-12 22:46:09 +08:00
.map_err(|_| anyhow!("Failed to parse token balance"))?;
2025-01-14 19:18:48 +08:00
if balance_u64 == 0 {
2025-02-12 22:46:09 +08:00
return Err(anyhow!("Balance is 0"));
2025-01-14 19:18:48 +08:00
}
let amount = balance_u64 * percent / 100;
2025-02-10 15:20:33 +08:00
self.sell_with_jito(mint, Some(amount), slippage_basis_points, jito_fee).await
2025-01-14 19:18:48 +08:00
}
2025-01-09 00:12:43 +08:00
/// Sell tokens using Jito
2025-01-03 14:43:26 +08:00
pub async fn sell_with_jito(
&self,
mint: &Pubkey,
amount_token: Option<u64>,
slippage_basis_points: Option<u64>,
2025-02-10 15:20:33 +08:00
jito_fee: Option<u64>,
2025-02-12 22:46:09 +08:00
) -> Result<String, anyhow::Error> {
2025-01-03 14:43:26 +08:00
let start_time = Instant::now();
2025-01-09 00:12:43 +08:00
let jito_client = self.jito_client.as_ref()
2025-02-12 22:46:09 +08:00
.ok_or_else(|| anyhow!("Jito client not found"))?;
2025-01-08 16:33:43 +08:00
let ata = get_associated_token_address(&self.payer.pubkey(), mint);
let balance = self.rpc.get_token_account_balance(&ata)?;
2025-01-09 00:12:43 +08:00
let balance_u64 = balance.amount.parse::<u64>()
2025-02-12 22:46:09 +08:00
.map_err(|_| anyhow!("Failed to parse token balance"))?;
2025-01-08 16:33:43 +08:00
let amount = amount_token.unwrap_or(balance_u64);
2025-01-03 14:43:26 +08:00
2025-01-09 00:12:43 +08:00
if amount == 0 {
2025-02-12 22:46:09 +08:00
return Err(anyhow!("Amount cannot be zero"));
2025-01-09 00:12:43 +08:00
}
2025-01-03 14:43:26 +08:00
let global_account = self.get_global_account()?;
let bonding_curve_account = self.get_bonding_curve_account(mint)?;
let min_sol_output = bonding_curve_account
2025-01-08 16:33:43 +08:00
.get_sell_price(amount, global_account.fee_basis_points)
2025-02-12 22:46:09 +08:00
.map_err(|e| anyhow!(e))?;
2025-01-08 16:33:43 +08:00
let min_sol_output_with_slippage = utils::calculate_with_slippage_sell(
2025-01-03 14:43:26 +08:00
min_sol_output,
2025-01-08 16:33:43 +08:00
slippage_basis_points.unwrap_or(DEFAULT_SLIPPAGE),
2025-01-03 14:43:26 +08:00
);
2025-02-13 00:08:14 +08:00
let mut instructions = self.create_priority_fee_instructions(None);
2025-02-12 22:46:09 +08:00
let tip_account = jito_client.get_tip_account().await.map_err(|e| anyhow!(e))?;
2025-01-03 14:43:26 +08:00
instructions.push(instruction::sell(
2025-01-09 01:21:20 +08:00
&self.payer.clone(),
2025-01-03 14:43:26 +08:00
mint,
&global_account.fee_recipient,
2025-01-23 17:48:10 +08:00
instruction::Sell {
2025-01-08 16:33:43 +08:00
_amount: amount,
_min_sol_output: min_sol_output_with_slippage,
2025-01-03 14:43:26 +08:00
},
));
2025-01-25 01:04:45 +08:00
instructions.push(close_account(
&spl_token::ID,
&ata,
&self.payer.pubkey(),
&self.payer.pubkey(),
&[&self.payer.pubkey()],
).unwrap());
2025-01-03 14:43:26 +08:00
instructions.push(
system_instruction::transfer(
&self.payer.pubkey(),
&tip_account,
2025-02-10 19:58:12 +08:00
jito_fee.unwrap_or(JITO_TIP_AMOUNT/10),
2025-01-03 14:43:26 +08:00
),
);
let recent_blockhash = self.rpc.get_latest_blockhash()?;
let transaction = Transaction::new_signed_with_payer(
&instructions,
Some(&self.payer.pubkey()),
&[&self.payer.clone()],
recent_blockhash,
);
2025-01-08 16:33:43 +08:00
let signature = jito_client.send_transaction(&transaction).await?;
2025-01-03 14:43:26 +08:00
println!("Total Jito sell operation time: {:?}ms", start_time.elapsed().as_millis());
Ok(signature)
}
2025-01-09 00:12:43 +08:00
// Helper methods
2025-01-08 16:33:43 +08:00
fn create_priority_fee_instructions(&self, priority_fee: Option<PriorityFee>) -> Vec<Instruction> {
let mut instructions = Vec::new();
2025-01-09 16:59:05 +08:00
let fee = priority_fee.unwrap_or(PriorityFee::default());
if let Some(limit) = fee.limit {
instructions.push(ComputeBudgetInstruction::set_compute_unit_limit(limit));
2025-01-08 16:33:43 +08:00
}
2025-01-09 16:59:05 +08:00
if let Some(price) = fee.price {
instructions.push(ComputeBudgetInstruction::set_compute_unit_price(price));
}
2025-01-08 16:33:43 +08:00
instructions
}
2025-01-09 00:12:43 +08:00
// Public interface methods
2025-01-07 13:18:31 +08:00
pub fn get_payer_pubkey(&self) -> Pubkey {
self.payer.pubkey()
}
2025-02-12 22:46:09 +08:00
pub fn get_token_balance(&self, account: &Pubkey, mint: &Pubkey) -> Result<u64, anyhow::Error> {
2025-01-08 16:33:43 +08:00
let ata = get_associated_token_address(account, mint);
2025-01-14 19:18:48 +08:00
if self.rpc.get_account(&ata).is_err() {
return Ok(0);
}
2025-01-08 16:33:43 +08:00
let balance = self.rpc.get_token_account_balance(&ata)?;
2025-01-09 00:12:43 +08:00
balance.amount.parse::<u64>()
2025-02-12 22:46:09 +08:00
.map_err(|_| anyhow!("Failed to parse token balance"))
2025-01-07 13:18:31 +08:00
}
2025-02-12 22:46:09 +08:00
pub fn get_sol_balance(&self, account: &Pubkey) -> Result<u64, anyhow::Error> {
self.rpc.get_balance(account).map_err(|_| anyhow!("Failed to get SOL balance"))
2025-01-08 16:33:43 +08:00
}
2025-02-12 22:46:09 +08:00
pub fn get_payer_token_balance(&self, mint: &Pubkey) -> Result<u64, anyhow::Error> {
2025-01-08 16:33:43 +08:00
self.get_token_balance(&self.payer.pubkey(), mint)
}
2025-02-12 22:46:09 +08:00
pub fn get_payer_sol_balance(&self) -> Result<u64, anyhow::Error> {
2025-01-08 16:33:43 +08:00
self.get_sol_balance(&self.payer.pubkey())
}
2025-01-09 00:12:43 +08:00
// PDA related methods
2024-12-31 16:51:58 +08:00
pub fn get_global_pda() -> Pubkey {
2025-01-23 17:48:10 +08:00
Pubkey::find_program_address(&[constants::seeds::GLOBAL_SEED], &constants::accounts::PUMPFUN).0
2024-12-31 16:51:58 +08:00
}
pub fn get_mint_authority_pda() -> Pubkey {
2025-01-23 17:48:10 +08:00
Pubkey::find_program_address(&[constants::seeds::MINT_AUTHORITY_SEED], &constants::accounts::PUMPFUN).0
2024-12-31 16:51:58 +08:00
}
pub fn get_bonding_curve_pda(mint: &Pubkey) -> Option<Pubkey> {
2025-01-08 16:33:43 +08:00
Pubkey::try_find_program_address(
&[constants::seeds::BONDING_CURVE_SEED, mint.as_ref()],
2025-01-23 17:48:10 +08:00
&constants::accounts::PUMPFUN
2025-01-08 16:33:43 +08:00
).map(|(pubkey, _)| pubkey)
2024-12-31 16:51:58 +08:00
}
pub fn get_metadata_pda(mint: &Pubkey) -> Pubkey {
2025-01-08 16:33:43 +08:00
Pubkey::find_program_address(
&[
constants::seeds::METADATA_SEED,
constants::accounts::MPL_TOKEN_METADATA.as_ref(),
mint.as_ref(),
],
&constants::accounts::MPL_TOKEN_METADATA
).0
2024-12-31 16:51:58 +08:00
}
2025-01-09 00:12:43 +08:00
// Account related methods
2025-02-12 22:46:09 +08:00
pub fn get_global_account(&self) -> Result<accounts::GlobalAccount, anyhow::Error> {
2025-01-08 16:33:43 +08:00
let global = Self::get_global_pda();
2025-01-09 00:12:43 +08:00
let account = self.rpc.get_account(&global)?;
2024-12-31 16:51:58 +08:00
accounts::GlobalAccount::try_from_slice(&account.data)
2025-02-12 22:46:09 +08:00
.map_err(|e| anyhow!(e))
2024-12-31 16:51:58 +08:00
}
pub fn get_bonding_curve_account(
&self,
mint: &Pubkey,
2025-02-12 22:46:09 +08:00
) -> Result<accounts::BondingCurveAccount, anyhow::Error> {
2025-01-08 16:33:43 +08:00
let bonding_curve_pda = Self::get_bonding_curve_pda(mint)
2025-02-12 22:46:09 +08:00
.ok_or(anyhow!("Bonding curve not found"))?;
2025-01-09 00:12:43 +08:00
let account = self.rpc.get_account(&bonding_curve_pda)?;
2024-12-31 16:51:58 +08:00
accounts::BondingCurveAccount::try_from_slice(&account.data)
2025-02-12 22:46:09 +08:00
.map_err(|e| anyhow!(e))
2024-12-31 16:51:58 +08:00
}
2025-01-07 13:18:31 +08:00
2025-01-09 00:12:43 +08:00
// Subscription related methods
2025-01-07 13:18:31 +08:00
pub async fn tokens_subscription<F>(
&self,
ws_url: &str,
commitment: CommitmentConfig,
callback: F,
bot_wallet: Option<Pubkey>,
) -> Result<SubscriptionHandle, Box<dyn std::error::Error>>
where
2025-01-25 16:01:16 +08:00
F: Fn(PumpfunEvent) + Send + Sync + 'static,
2025-01-07 13:18:31 +08:00
{
logs_subscribe::tokens_subscription(ws_url, commitment, callback, bot_wallet).await
}
pub async fn stop_subscription(&self, subscription_handle: SubscriptionHandle) {
subscription_handle.shutdown().await;
}
2025-01-09 01:21:20 +08:00
pub fn get_buy_amount_with_slippage(&self, amount_sol: u64, slippage_basis_points: Option<u64>) -> u64 {
utils::calculate_with_slippage_buy(amount_sol, slippage_basis_points.unwrap_or(DEFAULT_SLIPPAGE))
}
2025-01-13 18:42:21 +08:00
pub fn get_token_price(&self, virtual_sol_reserves: u64, virtual_token_reserves: u64) -> f64 {
let v_sol = virtual_sol_reserves as f64 / 100_000_000.0;
let v_tokens = virtual_token_reserves as f64 / 100_000.0;
let token_price = v_sol / v_tokens;
token_price
}
2025-01-25 17:16:52 +08:00
pub fn get_buy_price(&self, amount: u64, trade_info: &TradeInfo) -> Result<u64, &'static str> {
if amount == 0 {
return Ok(0);
}
// Calculate the product of virtual reserves using u128 to avoid overflow
let n: u128 = (trade_info.virtual_sol_reserves as u128) * (trade_info.virtual_token_reserves as u128);
// Calculate the new virtual sol reserves after the purchase
let i: u128 = (trade_info.virtual_sol_reserves as u128) + (amount as u128);
// Calculate the new virtual token reserves after the purchase
let r: u128 = n / i + 1;
// Calculate the amount of tokens to be purchased
let s: u128 = (trade_info.virtual_token_reserves as u128) - r;
// Convert back to u64 and return the minimum of calculated tokens and real reserves
let s_u64 = s as u64;
Ok(if s_u64 < trade_info.real_token_reserves {
s_u64
} else {
trade_info.real_token_reserves
})
}
2025-02-12 22:46:09 +08:00
pub async fn get_token_price_in_usdc(&self, token_amount: f64) -> Result<f64, anyhow::Error> {
2025-01-13 18:42:21 +08:00
if token_amount == 0.0 {
return Ok(0.0);
}
let url = "https://api.jup.ag/price/v2?ids=So11111111111111111111111111111111111111112";
let response: serde_json::Value = reqwest::get(url)
.await
2025-02-12 22:46:09 +08:00
.map_err(|e: reqwest::Error| anyhow!(e))?
2025-01-13 18:42:21 +08:00
.json()
.await
2025-02-12 22:46:09 +08:00
.map_err(|e: reqwest::Error| anyhow!(e))?;
2025-01-13 18:42:21 +08:00
let sol_price_str = response["data"]["So11111111111111111111111111111111111111112"]["price"]
.as_str()
2025-02-12 22:46:09 +08:00
.ok_or(anyhow!("Failed to find SOL price as a string"))?;
2025-01-13 18:42:21 +08:00
let sol_price_in_usdc: f64 = sol_price_str
.parse()
2025-02-12 22:46:09 +08:00
.map_err(|e: std::num::ParseFloatError| anyhow!(e))?;
2025-01-13 18:42:21 +08:00
let token_price_in_usdc = sol_price_in_usdc * token_amount;
Ok(token_price_in_usdc)
}
2025-02-01 09:44:15 +08:00
2025-02-12 22:46:09 +08:00
pub async fn get_sol_price_in_usdc(&self) -> Result<f64, anyhow::Error> {
2025-02-01 09:44:15 +08:00
let url = "https://api.jup.ag/price/v2?ids=So11111111111111111111111111111111111111112";
let response: serde_json::Value = reqwest::get(url)
.await
2025-02-12 22:46:09 +08:00
.map_err(|_| anyhow!("Failed to install crypto provider"))?
2025-02-01 09:44:15 +08:00
.json()
.await
2025-02-12 22:46:09 +08:00
.map_err(|_| anyhow!("Failed to install crypto provider"))?;
2025-02-01 09:44:15 +08:00
let sol_price_str = response["data"]["So11111111111111111111111111111111111111112"]["price"]
.as_str()
2025-02-12 22:46:09 +08:00
.ok_or(anyhow!("Failed to find SOL price as a string"))?;
2025-02-01 09:44:15 +08:00
let sol_price_in_usdc: f64 = sol_price_str
.parse()
2025-02-12 22:46:09 +08:00
.map_err(|_| anyhow!("Failed to parse SOL price as a string"))?;
2025-02-01 09:44:15 +08:00
Ok(sol_price_in_usdc)
}
2024-12-31 16:51:58 +08:00
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_new_client() {
let payer = Arc::new(Keypair::new());
2025-01-09 00:12:43 +08:00
let client = PumpFun::new(Cluster::Devnet, None, Arc::clone(&payer), None);
2024-12-31 16:51:58 +08:00
assert_eq!(client.payer.pubkey(), payer.pubkey());
}
#[test]
fn test_get_pdas() {
let mint = Keypair::new();
let global_pda = PumpFun::get_global_pda();
let mint_authority_pda = PumpFun::get_mint_authority_pda();
let bonding_curve_pda = PumpFun::get_bonding_curve_pda(&mint.pubkey());
let metadata_pda = PumpFun::get_metadata_pda(&mint.pubkey());
assert!(global_pda != Pubkey::default());
assert!(mint_authority_pda != Pubkey::default());
assert!(bonding_curve_pda.is_some());
assert!(metadata_pda != Pubkey::default());
}
}