rebuild code

This commit is contained in:
William
2025-02-21 20:47:28 +08:00
parent a7c94838df
commit f4f3c0fb37
12 changed files with 1441 additions and 883 deletions
+264
View File
@@ -0,0 +1,264 @@
use anyhow::anyhow;
use solana_client::{rpc_client::RpcClient, rpc_config::RpcSimulateTransactionConfig};
use solana_sdk::{
commitment_config::CommitmentConfig, compute_budget::ComputeBudgetInstruction, instruction::Instruction, native_token::sol_to_lamports, pubkey::Pubkey, signature::{Keypair, Signature}, signer::Signer, system_instruction, transaction::Transaction
};
use spl_associated_token_account::{
get_associated_token_address,
instruction::create_associated_token_account,
};
use std::time::Instant;
use crate::{constants::{self, trade::{DEFAULT_COMPUTE_UNIT_PRICE, DEFAULT_SLIPPAGE, JITO_TIP_AMOUNT}}, instruction, jito::JitoClient};
use super::common::{calculate_with_slippage_buy, get_bonding_curve_account, get_global_account, get_initial_buy_price, PriorityFee};
pub async fn buy(
rpc: &RpcClient,
payer: &Keypair,
mint: &Pubkey,
amount_sol: u64,
slippage_basis_points: Option<u64>,
priority_fee: Option<PriorityFee>,
) -> Result<Signature, anyhow::Error> {
let transaction = build_buy_transaction(rpc, payer, mint, amount_sol, slippage_basis_points, priority_fee).await?;
let signature = rpc.send_transaction(&transaction)?;
Ok(signature)
}
/// Buy tokens using Jito
pub async fn buy_with_jito(
rpc: &RpcClient,
jito_client: &JitoClient,
payer: &Keypair,
mint: &Pubkey,
amount_sol: u64,
slippage_basis_points: Option<u64>,
jito_fee: Option<f64>,
) -> Result<String, anyhow::Error> {
let start_time = Instant::now();
let transaction = build_buy_transaction_with_jito(rpc, jito_client, payer, mint, amount_sol, slippage_basis_points, jito_fee).await?;
let signature = jito_client.send_transaction(&transaction).await?;
println!("Total Jito buy operation time: {:?}ms", start_time.elapsed().as_millis());
Ok(signature)
}
pub async fn buy_list_with_jito(
rpc: &RpcClient,
jito_client: &JitoClient,
payers: Vec<&Keypair>,
mint: &Pubkey,
amount_sols: Vec<u64>,
slippage_basis_points: Option<u64>,
jito_fee: Option<f64>,
) -> Result<String, anyhow::Error> {
let start_time = Instant::now();
let mut transactions = vec![];
for (i, payer) in payers.iter().enumerate() {
let transaction = build_buy_transaction_with_jito(rpc, jito_client, payer, mint, amount_sols[i], slippage_basis_points, jito_fee).await?;
transactions.push(transaction);
}
let signature = jito_client.send_transactions(&transactions).await?;
println!("Total Jito buy operation time: {:?}ms", start_time.elapsed().as_millis());
Ok(signature)
}
pub async fn build_buy_transaction(
rpc: &RpcClient,
payer: &Keypair,
mint: &Pubkey,
amount_sol: u64,
slippage_basis_points: Option<u64>,
priority_fee: Option<PriorityFee>,
) -> Result<Transaction, anyhow::Error> {
let instructions = build_buy_instructions(rpc, payer, mint, amount_sol, slippage_basis_points, priority_fee).await?;
let recent_blockhash = rpc.get_latest_blockhash()?;
let transaction = Transaction::new_signed_with_payer(
&instructions,
Some(&payer.pubkey()),
&[payer],
recent_blockhash,
);
Ok(transaction)
}
pub async fn build_buy_transaction_with_jito(
rpc: &RpcClient,
jito_client: &JitoClient,
payer: &Keypair,
mint: &Pubkey,
amount_sol: u64,
slippage_basis_points: Option<u64>,
jito_fee: Option<f64>,
) -> Result<Transaction, anyhow::Error> {
let instructions = build_buy_instructions_with_jito(rpc, jito_client, payer, mint, amount_sol, slippage_basis_points, jito_fee).await?;
let recent_blockhash = rpc.get_latest_blockhash()?;
let transaction = Transaction::new_signed_with_payer(
&instructions,
Some(&payer.pubkey()),
&[payer],
recent_blockhash,
);
Ok(transaction)
}
pub async fn build_buy_instructions(
rpc: &RpcClient,
payer: &Keypair,
mint: &Pubkey,
amount_sol: u64,
slippage_basis_points: Option<u64>,
priority_fee: Option<PriorityFee>,
) -> Result<Vec<Instruction>, anyhow::Error> {
if amount_sol == 0 {
return Err(anyhow!("Amount cannot be zero"));
}
let global_account = get_global_account(rpc).await?;
let bonding_curve_account = get_bonding_curve_account(rpc, mint).await?;
let buy_amount = bonding_curve_account
.get_buy_price(amount_sol)
.map_err(|e| anyhow!(e))?;
let buy_amount_with_slippage = calculate_with_slippage_buy(amount_sol, slippage_basis_points.unwrap_or(DEFAULT_SLIPPAGE));
let mut instructions = vec![
ComputeBudgetInstruction::set_compute_unit_limit(1_400_000),
ComputeBudgetInstruction::set_compute_unit_price(0),
];
let ata = get_associated_token_address(&payer.pubkey(), mint);
if rpc.get_account(&ata).is_err() {
instructions.push(create_associated_token_account(
&payer.pubkey(),
&payer.pubkey(),
mint,
&constants::accounts::TOKEN_PROGRAM,
));
}
instructions.push(instruction::buy(
payer,
mint,
&global_account.fee_recipient,
instruction::Buy {
_amount: buy_amount,
_max_sol_cost: buy_amount_with_slippage,
},
));
let commitment_config = CommitmentConfig::confirmed();
let recent_blockhash = rpc.get_latest_blockhash_with_commitment(commitment_config)?
.0;
let simulate_tx = Transaction::new_signed_with_payer(
&instructions,
Some(&payer.pubkey()),
&[payer],
recent_blockhash,
);
let config = RpcSimulateTransactionConfig {
sig_verify: true,
commitment: Some(commitment_config),
..RpcSimulateTransactionConfig::default()
};
let result = 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 = rpc.get_recent_prioritization_fees(&[])?;
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
};
let unit_price = match priority_fee {
None => average_fees,
Some(pf) => pf.price.unwrap_or(DEFAULT_COMPUTE_UNIT_PRICE)
};
let unit_price = if unit_price == 0 { DEFAULT_COMPUTE_UNIT_PRICE } else { unit_price };
instructions[0] = ComputeBudgetInstruction::set_compute_unit_limit(result_cu as u32);
instructions[1] = ComputeBudgetInstruction::set_compute_unit_price(unit_price);
Ok(instructions)
}
pub async fn build_buy_instructions_with_jito(
rpc: &RpcClient,
jito_client: &JitoClient,
payer: &Keypair,
mint: &Pubkey,
amount_sol: u64,
slippage_basis_points: Option<u64>,
jito_fee: Option<f64>,
) -> Result<Vec<Instruction>, anyhow::Error> {
if amount_sol == 0 {
return Err(anyhow!("Amount cannot be zero"));
}
let global_account = get_global_account(rpc).await?;
let buy_amount = match get_bonding_curve_account(rpc, mint).await {
Ok(account) => account.get_buy_price(amount_sol).map_err(|e| anyhow!(e))?,
Err(_e) => {
let initial_buy_amount = get_initial_buy_price(&global_account, amount_sol).await?;
initial_buy_amount * 80 / 100
}
};
let buy_amount_with_slippage = calculate_with_slippage_buy(amount_sol, slippage_basis_points.unwrap_or(DEFAULT_SLIPPAGE));
let mut instructions = vec![];
let ata = get_associated_token_address(&payer.pubkey(), mint);
if rpc.get_account(&ata).is_err() {
instructions.push(create_associated_token_account(
&payer.pubkey(),
&payer.pubkey(),
mint,
&constants::accounts::TOKEN_PROGRAM,
));
}
instructions.push(instruction::buy(
payer,
mint,
&global_account.fee_recipient,
instruction::Buy {
_amount: buy_amount,
_max_sol_cost: buy_amount_with_slippage,
},
));
let tip_account = jito_client.get_tip_account().await.map_err(|e| anyhow!(e))?;
let jito_fee = jito_fee.unwrap_or(JITO_TIP_AMOUNT);
instructions.push(
system_instruction::transfer(
&payer.pubkey(),
&tip_account,
sol_to_lamports(jito_fee),
),
);
Ok(instructions)
}
+199
View File
@@ -0,0 +1,199 @@
use anyhow::anyhow;
use tokio::sync::RwLock;
use std::{collections::HashMap, sync::Arc};
use solana_client::rpc_client::RpcClient;
use solana_sdk::{
compute_budget::ComputeBudgetInstruction, instruction::Instruction, pubkey::Pubkey, signature::Keypair, signer::Signer, system_instruction, transaction::Transaction
};
use spl_associated_token_account::get_associated_token_address;
use crate::{accounts, common::logs_data::TradeInfo, constants::{self, trade::{DEFAULT_COMPUTE_UNIT_LIMIT, DEFAULT_COMPUTE_UNIT_PRICE, DEFAULT_SLIPPAGE}}};
use borsh::BorshDeserialize;
lazy_static::lazy_static! {
static ref ACCOUNT_CACHE: RwLock<HashMap<Pubkey, Arc<accounts::GlobalAccount>>> = RwLock::new(HashMap::new());
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PriorityFee {
pub limit: Option<u32>,
pub price: Option<u64>,
}
impl Default for PriorityFee {
fn default() -> Self {
Self { limit: Some(DEFAULT_COMPUTE_UNIT_LIMIT), price: Some(DEFAULT_COMPUTE_UNIT_PRICE) }
}
}
pub async fn transfer_sol(rpc: &RpcClient, payer: &Keypair, receive_wallet: &Pubkey, amount: u64) -> Result<(), anyhow::Error> {
if amount == 0 {
return Err(anyhow!("Amount cannot be zero"));
}
let balance = get_sol_balance(rpc, &payer.pubkey())?;
if balance < amount {
return Err(anyhow!("Insufficient balance"));
}
let transfer_instruction = system_instruction::transfer(
&payer.pubkey(),
receive_wallet,
amount,
);
let recent_blockhash = rpc.get_latest_blockhash()?;
let transaction = Transaction::new_signed_with_payer(
&[transfer_instruction],
Some(&payer.pubkey()),
&[payer],
recent_blockhash,
);
rpc.send_and_confirm_transaction(&transaction)?;
Ok(())
}
#[inline]
pub fn create_priority_fee_instructions(priority_fee: Option<PriorityFee>) -> Vec<Instruction> {
let mut instructions = Vec::with_capacity(2);
let fee = priority_fee.unwrap_or(PriorityFee::default());
if let Some(limit) = fee.limit {
instructions.push(ComputeBudgetInstruction::set_compute_unit_limit(limit));
}
if let Some(price) = fee.price {
instructions.push(ComputeBudgetInstruction::set_compute_unit_price(price));
}
instructions
}
pub fn get_token_balance(rpc: &RpcClient, account: &Pubkey, mint: &Pubkey) -> Result<u64, anyhow::Error> {
let ata = get_associated_token_address(account, mint);
if rpc.get_account(&ata).is_err() {
return Ok(0);
}
let balance = rpc.get_token_account_balance(&ata)?;
balance.amount.parse::<u64>()
.map_err(|_| anyhow!("Failed to parse token balance"))
}
pub fn get_sol_balance(rpc: &RpcClient, account: &Pubkey) -> Result<u64, anyhow::Error> {
rpc.get_balance(account).map_err(|_| anyhow!("Failed to get SOL balance"))
}
#[inline]
pub fn get_global_pda() -> Pubkey {
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
}
#[inline]
pub fn get_mint_authority_pda() -> Pubkey {
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
}
#[inline]
pub fn get_bonding_curve_pda(mint: &Pubkey) -> Option<Pubkey> {
let seeds: &[&[u8]; 2] = &[constants::seeds::BONDING_CURVE_SEED, mint.as_ref()];
let program_id: &Pubkey = &constants::accounts::PUMPFUN;
let pda: Option<(Pubkey, u8)> = Pubkey::try_find_program_address(seeds, program_id);
pda.map(|pubkey| pubkey.0)
}
#[inline]
pub fn get_metadata_pda(mint: &Pubkey) -> Pubkey {
Pubkey::find_program_address(
&[
constants::seeds::METADATA_SEED,
constants::accounts::MPL_TOKEN_METADATA.as_ref(),
mint.as_ref(),
],
&constants::accounts::MPL_TOKEN_METADATA
).0
}
#[inline]
pub async fn get_global_account(rpc: &RpcClient) -> Result<Arc<accounts::GlobalAccount>, anyhow::Error> {
let global = get_global_pda();
// Try cache first
if let Some(account) = ACCOUNT_CACHE.read().await.get(&global) {
return Ok(account.clone());
}
// Cache miss, fetch from RPC
let account = rpc.get_account(&global)?;
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)
}
#[inline]
pub async fn get_initial_buy_price(global_account: &Arc<accounts::GlobalAccount>, amount_sol: u64) -> Result<u64, anyhow::Error> {
let buy_amount = global_account.get_initial_buy_price(amount_sol);
Ok(buy_amount)
}
#[inline]
pub async fn get_bonding_curve_account(
rpc: &RpcClient,
mint: &Pubkey,
) -> Result<Arc<accounts::BondingCurveAccount>, anyhow::Error> {
let bonding_curve_pda = get_bonding_curve_pda(mint)
.ok_or(anyhow!("Bonding curve not found"))?;
if rpc.get_account(&bonding_curve_pda).is_err() {
return Err(anyhow!("Bonding curve not found"));
}
let account = rpc.get_account(&bonding_curve_pda)?;
let bonding_curve = Arc::new(accounts::BondingCurveAccount::try_from_slice(&account.data)?);
Ok(bonding_curve)
}
#[inline]
pub fn get_buy_amount_with_slippage(amount_sol: u64, slippage_basis_points: Option<u64>) -> u64 {
let slippage = slippage_basis_points.unwrap_or(DEFAULT_SLIPPAGE);
amount_sol + (amount_sol * slippage / 10000)
}
pub fn get_token_price(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;
v_sol / v_tokens
}
pub fn get_buy_price(amount: u64, trade_info: &TradeInfo) -> u64 {
if amount == 0 {
return 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;
s_u64.min(trade_info.real_token_reserves)
}
#[inline]
pub fn calculate_with_slippage_buy(amount: u64, basis_points: u64) -> u64 {
amount + (amount * basis_points) / 10000
}
#[inline]
pub fn calculate_with_slippage_sell(amount: u64, basis_points: u64) -> u64 {
amount - (amount * basis_points) / 10000
}
+326
View File
@@ -0,0 +1,326 @@
use std::time::Instant;
use anyhow::anyhow;
use solana_client::{rpc_client::RpcClient, rpc_config::RpcSimulateTransactionConfig};
use solana_sdk::{
commitment_config::CommitmentConfig, compute_budget::ComputeBudgetInstruction, instruction::Instruction, native_token::sol_to_lamports, signature::{Keypair, Signature}, signer::Signer, system_instruction, transaction::Transaction
};
use spl_associated_token_account::{
get_associated_token_address,
instruction::create_associated_token_account,
};
use crate::{constants::{self, trade::{DEFAULT_COMPUTE_UNIT_PRICE, JITO_TIP_AMOUNT}}, instruction, ipfs::TokenMetadataIPFS, jito::JitoClient, trade::buy::build_buy_transaction_with_jito};
use super::common::{create_priority_fee_instructions, get_buy_amount_with_slippage, get_global_account, PriorityFee};
/// Create a new token
pub async fn create(
rpc: &RpcClient,
payer: &Keypair,
mint: &Keypair,
ipfs: TokenMetadataIPFS,
priority_fee: Option<PriorityFee>,
) -> Result<Signature, anyhow::Error> {
let mut instructions = create_priority_fee_instructions(priority_fee);
instructions.push(instruction::create(
payer,
mint,
instruction::Create {
_name: ipfs.metadata.name,
_symbol: ipfs.metadata.symbol,
_uri: ipfs.metadata_uri,
},
));
let recent_blockhash = rpc.get_latest_blockhash()?;
let transaction = Transaction::new_signed_with_payer(
&instructions,
Some(&payer.pubkey()),
&[payer, mint],
recent_blockhash,
);
let signature = rpc.send_and_confirm_transaction(&transaction)?;
Ok(signature)
}
/// Create and buy tokens in one transaction
pub async fn create_and_buy(
rpc: &RpcClient,
payer: &Keypair,
mint: &Keypair,
ipfs: TokenMetadataIPFS,
amount_sol: u64,
slippage_basis_points: Option<u64>,
priority_fee: Option<PriorityFee>,
) -> Result<Signature, anyhow::Error> {
if amount_sol == 0 {
return Err(anyhow!("Amount cannot be zero"));
}
let transaction = build_create_and_buy_transaction(rpc, payer, mint, ipfs, amount_sol, slippage_basis_points, priority_fee).await?;
let signature = rpc.send_and_confirm_transaction(&transaction)?;
Ok(signature)
}
pub async fn create_and_buy_list_with_jito(
rpc: &RpcClient,
jito_client: &JitoClient,
payers: Vec<&Keypair>,
mint: &Keypair,
ipfs: TokenMetadataIPFS,
amount_sols: Vec<u64>,
slippage_basis_points: Option<u64>,
jito_fee: Option<f64>,
) -> Result<String, anyhow::Error> {
let start_time = Instant::now();
let mut transactions = Vec::new();
let transaction = build_create_and_buy_transaction_with_jito(rpc, jito_client, payers[0], mint, ipfs, amount_sols[0], slippage_basis_points, jito_fee).await?;
transactions.push(transaction);
for (i, payer) in payers.iter().skip(1).enumerate() {
println!("Creating and buying token index: {}", i);
let buy_transaction = build_buy_transaction_with_jito(rpc, jito_client, payer, &mint.pubkey(), amount_sols[i], slippage_basis_points, jito_fee).await?;
transactions.push(buy_transaction);
}
let signatures = jito_client.send_transactions(&transactions).await?;
println!("Total Jito create and buy operation time: {:?}ms", start_time.elapsed().as_millis());
Ok(signatures)
}
pub async fn create_and_buy_with_jito(
rpc: &RpcClient,
jito_client: &JitoClient,
payer: &Keypair,
mint: &Keypair,
ipfs: TokenMetadataIPFS,
amount_sol: u64,
slippage_basis_points: Option<u64>,
jito_fee: Option<f64>,
) -> Result<String, anyhow::Error> {
let start_time = Instant::now();
let transaction = build_create_and_buy_transaction_with_jito(rpc, jito_client, payer, mint, ipfs, amount_sol, slippage_basis_points, jito_fee).await?;
let signature = jito_client.send_transaction(&transaction).await?;
println!("Total Jito create and buy operation time: {:?}ms, signature: {}", start_time.elapsed().as_millis(), signature);
Ok(signature)
}
pub async fn build_create_and_buy_transaction(
rpc: &RpcClient,
payer: &Keypair,
mint: &Keypair,
ipfs: TokenMetadataIPFS,
amount_sol: u64,
slippage_basis_points: Option<u64>,
priority_fee: Option<PriorityFee>,
) -> Result<Transaction, anyhow::Error> {
let instructions = build_create_and_buy_instructions(rpc, payer, mint, ipfs, amount_sol, slippage_basis_points, priority_fee).await?;
let recent_blockhash = rpc.get_latest_blockhash()?;
let transaction = Transaction::new_signed_with_payer(
&instructions,
Some(&payer.pubkey()),
&[payer, mint],
recent_blockhash,
);
Ok(transaction)
}
pub async fn build_create_and_buy_transaction_with_jito(
rpc: &RpcClient,
jito_client: &JitoClient,
payer: &Keypair,
mint: &Keypair,
ipfs: TokenMetadataIPFS,
amount_sol: u64,
slippage_basis_points: Option<u64>,
jito_fee: Option<f64>,
) -> Result<Transaction, anyhow::Error> {
let instructions = build_create_and_buy_instructions_with_jito(rpc, jito_client, payer, mint, ipfs, amount_sol, slippage_basis_points, jito_fee).await?;
let recent_blockhash = rpc.get_latest_blockhash()?;
let transaction = Transaction::new_signed_with_payer(
&instructions,
Some(&payer.pubkey()),
&[payer, mint],
recent_blockhash,
);
Ok(transaction)
}
pub async fn build_create_and_buy_instructions(
rpc: &RpcClient,
payer: &Keypair,
mint: &Keypair,
ipfs: TokenMetadataIPFS,
amount_sol: u64,
slippage_basis_points: Option<u64>,
priority_fee: Option<PriorityFee>,
) -> Result<Vec<Instruction>, anyhow::Error> {
if amount_sol == 0 {
return Err(anyhow!("Amount cannot be zero"));
}
let global_account = get_global_account(rpc).await?;
let buy_amount = global_account.get_initial_buy_price(amount_sol);
let buy_amount_with_slippage =
get_buy_amount_with_slippage(amount_sol, slippage_basis_points);
let mut instructions = vec![
ComputeBudgetInstruction::set_compute_unit_limit(1_400_000),
ComputeBudgetInstruction::set_compute_unit_price(0),
];
instructions.push(instruction::create(
payer,
mint,
instruction::Create {
_name: ipfs.metadata.name,
_symbol: ipfs.metadata.symbol,
_uri: ipfs.metadata_uri,
},
));
let ata = get_associated_token_address(&payer.pubkey(), &mint.pubkey());
if rpc.get_account(&ata).is_err() {
instructions.push(create_associated_token_account(
&payer.pubkey(),
&payer.pubkey(),
&mint.pubkey(),
&constants::accounts::TOKEN_PROGRAM,
));
}
instructions.push(instruction::buy(
payer,
&mint.pubkey(),
&global_account.fee_recipient,
instruction::Buy {
_amount: buy_amount,
_max_sol_cost: buy_amount_with_slippage,
},
));
let commitment_config = CommitmentConfig::confirmed();
let recent_blockhash = rpc.get_latest_blockhash_with_commitment(commitment_config)?
.0;
let simulate_tx = Transaction::new_signed_with_payer(
&instructions,
Some(&payer.pubkey()),
&[payer, mint],
recent_blockhash,
);
let config = RpcSimulateTransactionConfig {
sig_verify: true,
commitment: Some(commitment_config),
..RpcSimulateTransactionConfig::default()
};
let result = 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 = rpc.get_recent_prioritization_fees(&[])?;
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
};
let unit_price = match priority_fee {
None => average_fees,
Some(pf) => pf.price.unwrap_or(DEFAULT_COMPUTE_UNIT_PRICE)
};
let unit_price = if unit_price == 0 { DEFAULT_COMPUTE_UNIT_PRICE } else { unit_price };
instructions[0] = ComputeBudgetInstruction::set_compute_unit_limit(result_cu as u32);
instructions[1] = ComputeBudgetInstruction::set_compute_unit_price(unit_price);
Ok(instructions)
}
pub async fn build_create_and_buy_instructions_with_jito(
rpc: &RpcClient,
jito_client: &JitoClient,
payer: &Keypair,
mint: &Keypair,
ipfs: TokenMetadataIPFS,
amount_sol: u64,
slippage_basis_points: Option<u64>,
jito_fee: Option<f64>,
) -> Result<Vec<Instruction>, anyhow::Error> {
if amount_sol == 0 {
return Err(anyhow!("Amount cannot be zero"));
}
let global_account = get_global_account(rpc).await?;
let buy_amount = global_account.get_initial_buy_price(amount_sol);
let buy_amount_with_slippage =
get_buy_amount_with_slippage(amount_sol, slippage_basis_points);
let mut instructions = vec![];
instructions.push(instruction::create(
payer,
mint,
instruction::Create {
_name: ipfs.metadata.name,
_symbol: ipfs.metadata.symbol,
_uri: ipfs.metadata_uri,
},
));
let ata = get_associated_token_address(&payer.pubkey(), &mint.pubkey());
if rpc.get_account(&ata).is_err() {
instructions.push(create_associated_token_account(
&payer.pubkey(),
&payer.pubkey(),
&mint.pubkey(),
&constants::accounts::TOKEN_PROGRAM,
));
}
instructions.push(instruction::buy(
payer,
&mint.pubkey(),
&global_account.fee_recipient,
instruction::Buy {
_amount: buy_amount,
_max_sol_cost: buy_amount_with_slippage,
},
));
let tip_account = jito_client.get_tip_account().await.map_err(|e| anyhow!(e))?;
let jito_fee = jito_fee.unwrap_or(JITO_TIP_AMOUNT);
instructions.push(
system_instruction::transfer(
&payer.pubkey(),
&tip_account,
sol_to_lamports(jito_fee * 2.0),
),
);
Ok(instructions)
}
+4
View File
@@ -0,0 +1,4 @@
pub mod buy;
pub mod create;
pub mod sell;
pub mod common;
+291
View File
@@ -0,0 +1,291 @@
use anyhow::anyhow;
use solana_client::{rpc_client::RpcClient, rpc_config::RpcSimulateTransactionConfig};
use solana_sdk::{
commitment_config::CommitmentConfig, compute_budget::ComputeBudgetInstruction, instruction::Instruction, native_token::sol_to_lamports, pubkey::Pubkey, signature::{Keypair, Signature}, signer::Signer, system_instruction, transaction::Transaction
};
use spl_associated_token_account::get_associated_token_address;
use spl_token::instruction::close_account;
use std::time::Instant;
use crate::{constants::trade::{DEFAULT_COMPUTE_UNIT_PRICE, DEFAULT_SLIPPAGE, JITO_TIP_AMOUNT}, instruction, jito::JitoClient};
use super::common::{calculate_with_slippage_sell, get_bonding_curve_account, get_global_account, PriorityFee};
async fn get_token_balance(rpc: &RpcClient, payer: &Keypair, mint: &Pubkey) -> Result<(u64, Pubkey), anyhow::Error> {
let ata = get_associated_token_address(&payer.pubkey(), mint);
let balance = rpc.get_token_account_balance(&ata)?;
let balance_u64 = balance.amount.parse::<u64>()
.map_err(|_| anyhow!("Failed to parse token balance"))?;
if balance_u64 == 0 {
return Err(anyhow!("Balance is 0"));
}
Ok((balance_u64, ata))
}
pub async fn sell(
rpc: &RpcClient,
payer: &Keypair,
mint: &Pubkey,
amount_token: Option<u64>,
slippage_basis_points: Option<u64>,
priority_fee: Option<PriorityFee>,
) -> Result<Signature, anyhow::Error> {
let transaction = build_sell_transaction(rpc, payer, mint, amount_token, slippage_basis_points, priority_fee).await?;
let signature = rpc.send_and_confirm_transaction(&transaction)?;
Ok(signature)
}
/// Sell tokens by percentage
pub async fn sell_by_percent(
rpc: &RpcClient,
payer: &Keypair,
mint: &Pubkey,
percent: u64,
slippage_basis_points: Option<u64>,
priority_fee: Option<PriorityFee>,
) -> Result<Signature, anyhow::Error> {
if percent == 0 || percent > 100 {
return Err(anyhow!("Percentage must be between 1 and 100"));
}
let (balance_u64, _) = get_token_balance(rpc, payer, mint).await?;
let amount = balance_u64 * percent / 100;
sell(rpc, payer, mint, Some(amount), slippage_basis_points, priority_fee).await
}
pub async fn sell_by_percent_with_jito(
rpc: &RpcClient,
payer: &Keypair,
jito_client: &JitoClient,
mint: &Pubkey,
percent: u64,
slippage_basis_points: Option<u64>,
jito_fee: Option<f64>,
) -> Result<String, anyhow::Error> {
if percent == 0 || percent > 100 {
return Err(anyhow!("Percentage must be between 1 and 100"));
}
let (balance_u64, _) = get_token_balance(rpc, payer, mint).await?;
let amount = balance_u64 * percent / 100;
sell_with_jito(rpc, payer, jito_client, mint, Some(amount), slippage_basis_points, jito_fee).await
}
/// Sell tokens using Jito
pub async fn sell_with_jito(
rpc: &RpcClient,
payer: &Keypair,
jito_client: &JitoClient,
mint: &Pubkey,
amount_token: Option<u64>,
slippage_basis_points: Option<u64>,
jito_fee: Option<f64>,
) -> Result<String, anyhow::Error> {
let start_time = Instant::now();
let transaction = build_sell_transaction_with_jito(rpc, jito_client, payer, mint, amount_token, slippage_basis_points, jito_fee).await?;
let signature = jito_client.send_transaction(&transaction).await?;
println!("Total Jito sell operation time: {:?}ms, signature: {}", start_time.elapsed().as_millis(), signature);
Ok(signature)
}
pub async fn build_sell_transaction(
rpc: &RpcClient,
payer: &Keypair,
mint: &Pubkey,
amount_token: Option<u64>,
slippage_basis_points: Option<u64>,
priority_fee: Option<PriorityFee>,
) -> Result<Transaction, anyhow::Error> {
let instructions = build_sell_instructions(rpc, payer, mint, amount_token, slippage_basis_points, priority_fee).await?;
let recent_blockhash = rpc.get_latest_blockhash()?;
let transaction = Transaction::new_signed_with_payer(
&instructions,
Some(&payer.pubkey()),
&[payer],
recent_blockhash,
);
Ok(transaction)
}
pub async fn build_sell_transaction_with_jito(
rpc: &RpcClient,
jito_client: &JitoClient,
payer: &Keypair,
mint: &Pubkey,
amount_token: Option<u64>,
slippage_basis_points: Option<u64>,
jito_fee: Option<f64>,
) -> Result<Transaction, anyhow::Error> {
let instructions = build_sell_instructions_with_jito(rpc, jito_client, payer, mint, amount_token, slippage_basis_points, jito_fee).await?;
let recent_blockhash = rpc.get_latest_blockhash()?;
let transaction = Transaction::new_signed_with_payer(
&instructions,
Some(&payer.pubkey()),
&[payer],
recent_blockhash,
);
Ok(transaction)
}
pub async fn build_sell_instructions(
rpc: &RpcClient,
payer: &Keypair,
mint: &Pubkey,
amount_token: Option<u64>,
slippage_basis_points: Option<u64>,
priority_fee: Option<PriorityFee>,
) -> Result<Vec<Instruction>, anyhow::Error> {
let (balance_u64, ata) = get_token_balance(rpc, payer, mint).await?;
let amount = amount_token.unwrap_or(balance_u64);
if amount == 0 {
return Err(anyhow!("Amount cannot be zero"));
}
let global_account = get_global_account(rpc).await?;
let bonding_curve_account = get_bonding_curve_account(rpc, mint).await?;
let min_sol_output = bonding_curve_account
.get_sell_price(amount, global_account.fee_basis_points)
.map_err(|e| anyhow!(e))?;
let min_sol_output_with_slippage = calculate_with_slippage_sell(
min_sol_output,
slippage_basis_points.unwrap_or(DEFAULT_SLIPPAGE),
);
let mut instructions = vec![
ComputeBudgetInstruction::set_compute_unit_limit(1_400_000),
ComputeBudgetInstruction::set_compute_unit_price(0),
];
instructions.push(instruction::sell(
payer,
mint,
&global_account.fee_recipient,
instruction::Sell {
_amount: amount,
_min_sol_output: min_sol_output_with_slippage,
},
));
instructions.push(close_account(
&spl_token::ID,
&ata,
&payer.pubkey(),
&payer.pubkey(),
&[&payer.pubkey()],
)?);
let commitment_config = CommitmentConfig::confirmed();
let recent_blockhash = rpc.get_latest_blockhash_with_commitment(commitment_config)?
.0;
let simulate_tx = Transaction::new_signed_with_payer(
&instructions,
Some(&payer.pubkey()),
&[payer],
recent_blockhash,
);
let config = RpcSimulateTransactionConfig {
sig_verify: true,
commitment: Some(commitment_config),
..RpcSimulateTransactionConfig::default()
};
let result = 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 = rpc.get_recent_prioritization_fees(&[])?;
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
};
let unit_price = match priority_fee {
None => average_fees,
Some(pf) => pf.price.unwrap_or(DEFAULT_COMPUTE_UNIT_PRICE)
};
let unit_price = if unit_price == 0 { DEFAULT_COMPUTE_UNIT_PRICE } else { unit_price };
instructions[0] = ComputeBudgetInstruction::set_compute_unit_limit(result_cu as u32);
instructions[1] = ComputeBudgetInstruction::set_compute_unit_price(unit_price);
Ok(instructions)
}
pub async fn build_sell_instructions_with_jito(
rpc: &RpcClient,
jito_client: &JitoClient,
payer: &Keypair,
mint: &Pubkey,
amount_token: Option<u64>,
slippage_basis_points: Option<u64>,
jito_fee: Option<f64>,
) -> Result<Vec<Instruction>, anyhow::Error> {
let (balance_u64, ata) = get_token_balance(rpc, payer, mint).await?;
let amount = amount_token.unwrap_or(balance_u64);
if amount == 0 {
return Err(anyhow!("Amount cannot be zero"));
}
let global_account = get_global_account(rpc).await?;
let bonding_curve_account = get_bonding_curve_account(rpc, mint).await?;
let min_sol_output = bonding_curve_account
.get_sell_price(amount, global_account.fee_basis_points)
.map_err(|e| anyhow!(e))?;
let min_sol_output_with_slippage = calculate_with_slippage_sell(
min_sol_output,
slippage_basis_points.unwrap_or(DEFAULT_SLIPPAGE),
);
let mut instructions = vec![];
instructions.push(instruction::sell(
payer,
mint,
&global_account.fee_recipient,
instruction::Sell {
_amount: amount,
_min_sol_output: min_sol_output_with_slippage,
},
));
instructions.push(close_account(
&spl_token::ID,
&ata,
&payer.pubkey(),
&payer.pubkey(),
&[&payer.pubkey()],
)?);
let tip_account = jito_client.get_tip_account().await.map_err(|e| anyhow!(e))?;
let jito_fee = jito_fee.unwrap_or(JITO_TIP_AMOUNT);
instructions.push(
system_instruction::transfer(
&payer.pubkey(),
&tip_account,
sol_to_lamports(jito_fee),
),
);
Ok(instructions)
}