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

762 lines
25 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;
2025-01-23 17:48:10 +08:00
2025-02-12 20:12:14 +08:00
use anyhow::anyhow;
2025-02-15 18:53:17 +08:00
use solana_client::{
rpc_client::RpcClient,
rpc_config::RpcSimulateTransactionConfig
};
2025-01-23 17:48:10 +08:00
use solana_sdk::{
2025-02-15 18:53:17 +08:00
commitment_config::CommitmentConfig, compute_budget::ComputeBudgetInstruction, instruction::Instruction, native_token::sol_to_lamports, pubkey::Pubkey, signature::{Keypair, Signature}, signer::Signer, system_instruction, 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
use std::sync::Arc;
use std::time::Instant;
2025-02-15 18:53:17 +08:00
use std::collections::HashMap;
use tokio::sync::RwLock;
2025-01-03 14:43:26 +08:00
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;
2025-02-13 15:59:14 +08:00
const DEFAULT_COMPUTE_UNIT_PRICE: u64 = 500000;
2025-02-15 18:53:17 +08:00
const JITO_TIP_AMOUNT: f64 = 0.00006;
// Cache
lazy_static::lazy_static! {
static ref ACCOUNT_CACHE: RwLock<HashMap<Pubkey, Arc<accounts::GlobalAccount>>> = RwLock::new(HashMap::new());
static ref BONDING_CURVE_CACHE: RwLock<HashMap<Pubkey, Arc<accounts::BondingCurveAccount>>> = RwLock::new(HashMap::new());
}
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-02-15 18:53:17 +08:00
#[inline]
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-15 18:53:17 +08:00
.map_err(|e| anyhow!("Failed to upload metadata: {}", e))?;
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-02-15 18:53:17 +08:00
if amount_sol == 0 {
return Err(anyhow!("Amount cannot be zero"));
}
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-15 18:53:17 +08:00
.map_err(|e| anyhow!("Failed to upload metadata: {}", e))?;
2024-12-31 16:51:58 +08:00
2025-02-15 18:53:17 +08:00
let global_account = self.get_global_account().await?;
2024-12-31 16:51:58 +08:00
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> {
2025-02-15 18:53:17 +08:00
if amount_sol == 0 {
return Err(anyhow!("Amount cannot be zero"));
}
let global_account = self.get_global_account().await?;
let bonding_curve_account = self.get_bonding_curve_account(mint).await?;
2024-12-31 16:51:58 +08:00
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-02-15 18:53:17 +08:00
jito_fee: Option<f64>,
2025-02-12 22:46:09 +08:00
) -> Result<String, anyhow::Error> {
2025-02-15 18:53:17 +08:00
if buy_token_amount == 0 || max_sol_cost == 0 {
return Err(anyhow!("Amount cannot be zero"));
}
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
2025-02-15 18:53:17 +08:00
let global_account = self.get_global_account().await?;
2025-01-03 14:43:26 +08:00
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-15 18:53:17 +08:00
let tip_account = jito_client.get_tip_account().await.map_err(|e| anyhow!(e))?;
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-02-15 18:53:17 +08:00
sol_to_lamports(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-15 18:53:17 +08:00
return Err(anyhow!("Amount cannot be zero"));
2025-01-07 13:18:31 +08:00
}
2025-02-15 18:53:17 +08:00
let global_account = self.get_global_account().await?;
let bonding_curve_account = self.get_bonding_curve_account(mint).await?;
2025-01-07 13:18:31 +08:00
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()],
2025-02-15 18:53:17 +08:00
)?);
2025-01-25 01:04:45 +08:00
2025-02-13 15:22:35 +08:00
let commitment_config = CommitmentConfig::confirmed();
2025-02-15 18:53:17 +08:00
let recent_blockhash = self.rpc.get_latest_blockhash_with_commitment(commitment_config)?
2025-02-13 15:22:35 +08:00
.0;
let simulate_tx = Transaction::new_signed_with_payer(
2025-01-09 00:12:43 +08:00
&instructions,
Some(&self.payer.pubkey()),
&[&self.payer.clone()],
recent_blockhash,
);
2025-02-13 15:22:35 +08:00
let config = RpcSimulateTransactionConfig {
sig_verify: true,
commitment: Some(commitment_config),
..RpcSimulateTransactionConfig::default()
};
let result = self.rpc.simulate_transaction_with_config(&simulate_tx, config)?
.value;
2025-01-07 13:18:31 +08:00
2025-02-13 15:22:35 +08:00
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(&[])?;
2025-02-15 18:53:17 +08:00
let average_fees = if fees.is_empty() {
DEFAULT_COMPUTE_UNIT_PRICE
} else {
fees.iter()
.map(|fee| fee.prioritization_fee)
.sum::<u64>() / fees.len() as u64
};
2025-02-13 15:22:35 +08:00
let unit_price = match priority_fee {
None => average_fees,
Some(pf) => pf.price.unwrap_or(DEFAULT_COMPUTE_UNIT_PRICE)
};
2025-02-13 15:59:14 +08:00
let unit_price = if unit_price == 0 { DEFAULT_COMPUTE_UNIT_PRICE } else { unit_price };
2025-02-13 15:22:35 +08:00
instructions[0] = ComputeBudgetInstruction::set_compute_unit_limit(result_cu as u32);
instructions[1] = ComputeBudgetInstruction::set_compute_unit_price(unit_price);
let transaction = Transaction::new_signed_with_payer(
&instructions,
Some(&self.payer.pubkey()),
&[&self.payer.clone()],
recent_blockhash,
);
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-02-15 18:53:17 +08:00
if percent == 0 || percent > 100 {
return Err(anyhow!("Percentage must be between 1 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-15 18:53:17 +08:00
jito_fee: Option<f64>,
2025-02-12 22:46:09 +08:00
) -> Result<String, anyhow::Error> {
2025-02-15 18:53:17 +08:00
if percent == 0 || percent > 100 {
return Err(anyhow!("Percentage must be between 1 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-15 18:53:17 +08:00
jito_fee: Option<f64>,
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-02-15 18:53:17 +08:00
let global_account = self.get_global_account().await?;
let bonding_curve_account = self.get_bonding_curve_account(mint).await?;
2025-01-03 14:43:26 +08:00
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()],
2025-02-15 18:53:17 +08:00
)?);
2025-01-25 01:04:45 +08:00
2025-02-15 18:53:17 +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-02-15 18:53:17 +08:00
sol_to_lamports(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 sell operation time: {:?}ms", start_time.elapsed().as_millis());
Ok(signature)
}
2025-02-15 18:53:17 +08:00
pub async fn transfer_sol(&self, receive_wallet: &Pubkey, amount: u64) -> Result<(), anyhow::Error> {
if amount == 0 {
return Err(anyhow!("Amount cannot be zero"));
}
let balance = self.get_payer_sol_balance()?;
if balance < amount {
return Err(anyhow!("Insufficient balance"));
}
let transfer_instruction = system_instruction::transfer(
&self.payer.pubkey(),
receive_wallet,
amount,
);
let recent_blockhash = self.rpc.get_latest_blockhash()?;
let transaction = Transaction::new_signed_with_payer(
&[transfer_instruction],
Some(&self.payer.pubkey()),
&[&self.payer.clone()],
recent_blockhash,
);
self.rpc.send_and_confirm_transaction(&transaction)?;
Ok(())
}
2025-01-09 00:12:43 +08:00
// Helper methods
2025-02-15 18:53:17 +08:00
#[inline]
2025-01-09 00:12:43 +08:00
fn create_priority_fee_instructions(&self, priority_fee: Option<PriorityFee>) -> Vec<Instruction> {
2025-02-15 18:53:17 +08:00
let mut instructions = Vec::with_capacity(2);
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-09 00:12:43 +08:00
instructions
2025-01-08 16:33:43 +08:00
}
2025-02-15 18:53:17 +08:00
#[inline]
pub fn get_rpc(&self) -> &RpcClient {
&self.rpc
}
#[inline]
2025-01-07 13:18:31 +08:00
pub fn get_payer_pubkey(&self) -> Pubkey {
self.payer.pubkey()
}
2025-02-15 18:53:17 +08:00
#[inline]
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-08 16:33:43 +08:00
}
2025-02-15 18:53:17 +08:00
#[inline]
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-15 18:53:17 +08:00
#[inline]
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-01-07 13:18:31 +08:00
}
2025-02-15 18:53:17 +08:00
#[inline]
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-02-15 18:53:17 +08:00
#[inline]
2024-12-31 16:51:58 +08:00
pub fn get_global_pda() -> Pubkey {
2025-02-15 18:53:17 +08:00
static GLOBAL_PDA: once_cell::sync::Lazy<Pubkey> = once_cell::sync::Lazy::new(|| {
Pubkey::find_program_address(&[constants::seeds::GLOBAL_SEED], &constants::accounts::PUMPFUN).0
});
*GLOBAL_PDA
2024-12-31 16:51:58 +08:00
}
2025-02-15 18:53:17 +08:00
#[inline]
2024-12-31 16:51:58 +08:00
pub fn get_mint_authority_pda() -> Pubkey {
2025-02-15 18:53:17 +08:00
static MINT_AUTHORITY_PDA: once_cell::sync::Lazy<Pubkey> = once_cell::sync::Lazy::new(|| {
Pubkey::find_program_address(&[constants::seeds::MINT_AUTHORITY_SEED], &constants::accounts::PUMPFUN).0
});
*MINT_AUTHORITY_PDA
2024-12-31 16:51:58 +08:00
}
2025-02-15 18:53:17 +08:00
#[inline]
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
}
2025-02-15 18:53:17 +08:00
#[inline]
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-02-15 18:53:17 +08:00
#[inline]
pub async fn get_global_account(&self) -> Result<Arc<accounts::GlobalAccount>, anyhow::Error> {
2025-01-08 16:33:43 +08:00
let global = Self::get_global_pda();
2025-02-15 18:53:17 +08:00
// Try cache first
if let Some(account) = ACCOUNT_CACHE.read().await.get(&global) {
return Ok(account.clone());
}
// Cache miss, fetch from RPC
2025-01-09 00:12:43 +08:00
let account = self.rpc.get_account(&global)?;
2025-02-15 18:53:17 +08:00
let global_account = Arc::new(accounts::GlobalAccount::try_from_slice(&account.data)?);
// Update cache
ACCOUNT_CACHE.write().await.insert(global, global_account.clone());
Ok(global_account)
2024-12-31 16:51:58 +08:00
}
2025-02-15 18:53:17 +08:00
#[inline]
pub async fn get_bonding_curve_account(
2024-12-31 16:51:58 +08:00
&self,
mint: &Pubkey,
2025-02-15 18:53:17 +08:00
) -> Result<Arc<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-02-15 18:53:17 +08:00
// Try cache first
if let Some(account) = BONDING_CURVE_CACHE.read().await.get(&bonding_curve_pda) {
return Ok(account.clone());
}
// Cache miss, fetch from RPC
2025-01-09 00:12:43 +08:00
let account = self.rpc.get_account(&bonding_curve_pda)?;
2025-02-15 18:53:17 +08:00
let bonding_curve = Arc::new(accounts::BondingCurveAccount::try_from_slice(&account.data)?);
// Update cache
BONDING_CURVE_CACHE.write().await.insert(bonding_curve_pda, bonding_curve.clone());
Ok(bonding_curve)
2024-12-31 16:51:58 +08:00
}
2025-01-07 13:18:31 +08:00
2025-02-15 18:53:17 +08:00
#[inline]
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
}
2025-02-15 18:53:17 +08:00
#[inline]
2025-01-07 13:18:31 +08:00
pub async fn stop_subscription(&self, subscription_handle: SubscriptionHandle) {
subscription_handle.shutdown().await;
}
2025-01-09 01:21:20 +08:00
2025-02-15 18:53:17 +08:00
#[inline]
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
2025-02-15 18:53:17 +08:00
#[inline]
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;
2025-02-15 18:53:17 +08:00
v_sol / v_tokens
2025-01-13 18:42:21 +08:00
}
2025-02-15 18:53:17 +08:00
#[inline]
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);
}
let n: u128 = (trade_info.virtual_sol_reserves as u128) * (trade_info.virtual_token_reserves as u128);
let i: u128 = (trade_info.virtual_sol_reserves as u128) + (amount as u128);
let r: u128 = n / i + 1;
let s: u128 = (trade_info.virtual_token_reserves as u128) - r;
let s_u64 = s as u64;
2025-01-13 18:42:21 +08:00
2025-02-15 18:53:17 +08:00
Ok(s_u64.min(trade_info.real_token_reserves))
2024-12-31 16:51:58 +08:00
}
}