add nextblock, 0slot support
This commit is contained in:
Executable
+179
@@ -0,0 +1,179 @@
|
||||
use anyhow::anyhow;
|
||||
use solana_sdk::{
|
||||
compute_budget::ComputeBudgetInstruction, instruction::Instruction, message::{v0, VersionedMessage}, native_token::sol_to_lamports, pubkey::Pubkey, signature::Keypair, signer::Signer, system_instruction, transaction::{Transaction, VersionedTransaction}
|
||||
};
|
||||
use solana_hash::Hash;
|
||||
use spl_associated_token_account::instruction::create_associated_token_account;
|
||||
use tokio::task::JoinHandle;
|
||||
use std::{str::FromStr, time::Instant, sync::Arc};
|
||||
|
||||
use crate::{common::{PriorityFee, SolanaRpcClient}, constants::{self, trade::DEFAULT_SLIPPAGE}, instruction, jito::FeeClient};
|
||||
|
||||
const MAX_LOADED_ACCOUNTS_DATA_SIZE_LIMIT: u32 = 250000;
|
||||
|
||||
use super::common::{calculate_with_slippage_buy, get_bonding_curve_account, get_global_account, get_initial_buy_price};
|
||||
|
||||
pub async fn buy(
|
||||
rpc: Arc<SolanaRpcClient>,
|
||||
payer: Arc<Keypair>,
|
||||
mint: Pubkey,
|
||||
amount_sol: u64,
|
||||
slippage_basis_points: Option<u64>,
|
||||
priority_fee: PriorityFee,
|
||||
) -> Result<(), anyhow::Error> {
|
||||
let transaction = build_buy_transaction(rpc.clone(), payer.clone(), mint.clone(), amount_sol, slippage_basis_points, priority_fee.clone()).await?;
|
||||
rpc.send_and_confirm_transaction(&transaction).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Buy tokens using Jito
|
||||
pub async fn buy_with_tip(
|
||||
rpc: Arc<SolanaRpcClient>,
|
||||
fee_clients: Vec<Arc<FeeClient>>,
|
||||
payer: Arc<Keypair>,
|
||||
mint: Pubkey,
|
||||
amount_sol: u64,
|
||||
slippage_basis_points: Option<u64>,
|
||||
priority_fee: PriorityFee,
|
||||
) -> Result<(), anyhow::Error> {
|
||||
let start_time = Instant::now();
|
||||
|
||||
let mint = Arc::new(mint.clone());
|
||||
let instructions = build_buy_instructions(rpc.clone(), payer.clone(), mint.clone(), amount_sol, slippage_basis_points).await?;
|
||||
|
||||
let mut transactions = vec![];
|
||||
let recent_blockhash = rpc.get_latest_blockhash().await?;
|
||||
for fee_client in fee_clients.clone() {
|
||||
let payer = payer.clone();
|
||||
let priority_fee = priority_fee.clone();
|
||||
let tip_account = fee_client.get_tip_account().await.map_err(|e| anyhow!(e.to_string()))?;
|
||||
let tip_account = Arc::new(Pubkey::from_str(&tip_account).map_err(|e| anyhow!(e))?);
|
||||
|
||||
let transaction = build_buy_transaction_with_tip(tip_account, payer, priority_fee, instructions.clone(), recent_blockhash).await?;
|
||||
transactions.push(transaction);
|
||||
}
|
||||
|
||||
let mut handles: Vec<JoinHandle<Result<(), anyhow::Error>>> = vec![];
|
||||
for i in 0..fee_clients.len() {
|
||||
let fee_client = fee_clients[i].clone();
|
||||
let transactions = transactions.clone();
|
||||
let start_time = start_time.clone();
|
||||
let transaction = transactions[i].clone();
|
||||
let handle = tokio::spawn(async move {
|
||||
fee_client.send_transaction(&transaction).await?;
|
||||
println!("index: {}, Total Jito buy operation time: {:?}ms", i, start_time.elapsed().as_millis());
|
||||
Ok::<(), anyhow::Error>(())
|
||||
});
|
||||
|
||||
handles.push(handle);
|
||||
}
|
||||
|
||||
for handle in handles {
|
||||
match handle.await {
|
||||
Ok(Ok(_)) => (),
|
||||
Ok(Err(e)) => println!("Error in task: {}", e),
|
||||
Err(e) => println!("Task join error: {}", e),
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn build_buy_transaction(
|
||||
rpc: Arc<SolanaRpcClient>,
|
||||
payer: Arc<Keypair>,
|
||||
mint: Pubkey,
|
||||
amount_sol: u64,
|
||||
slippage_basis_points: Option<u64>,
|
||||
priority_fee: PriorityFee,
|
||||
) -> Result<Transaction, anyhow::Error> {
|
||||
let mut instructions = vec![
|
||||
ComputeBudgetInstruction::set_loaded_accounts_data_size_limit(MAX_LOADED_ACCOUNTS_DATA_SIZE_LIMIT),
|
||||
ComputeBudgetInstruction::set_compute_unit_price(priority_fee.unit_price),
|
||||
ComputeBudgetInstruction::set_compute_unit_limit(priority_fee.unit_limit),
|
||||
];
|
||||
|
||||
let build_instructions = build_buy_instructions(rpc.clone(), payer.clone(), Arc::new(mint), amount_sol, slippage_basis_points).await?;
|
||||
instructions.extend(build_instructions);
|
||||
|
||||
let recent_blockhash = rpc.get_latest_blockhash().await?;
|
||||
let transaction = Transaction::new_signed_with_payer(
|
||||
&instructions,
|
||||
Some(&payer.pubkey()),
|
||||
&[payer],
|
||||
recent_blockhash,
|
||||
);
|
||||
|
||||
Ok(transaction)
|
||||
}
|
||||
|
||||
pub async fn build_buy_transaction_with_tip(
|
||||
tip_account: Arc<Pubkey>,
|
||||
payer: Arc<Keypair>,
|
||||
priority_fee: PriorityFee,
|
||||
build_instructions: Vec<Instruction>,
|
||||
blockhash: Hash,
|
||||
) -> Result<VersionedTransaction, anyhow::Error> {
|
||||
let mut instructions = vec![
|
||||
ComputeBudgetInstruction::set_loaded_accounts_data_size_limit(MAX_LOADED_ACCOUNTS_DATA_SIZE_LIMIT),
|
||||
ComputeBudgetInstruction::set_compute_unit_price(priority_fee.unit_price),
|
||||
ComputeBudgetInstruction::set_compute_unit_limit(priority_fee.unit_limit),
|
||||
system_instruction::transfer(
|
||||
&payer.pubkey(),
|
||||
&tip_account,
|
||||
sol_to_lamports(priority_fee.buy_tip_fee),
|
||||
),
|
||||
];
|
||||
|
||||
instructions.extend(build_instructions);
|
||||
|
||||
let v0_message: v0::Message =
|
||||
v0::Message::try_compile(&payer.pubkey(), &instructions, &[], blockhash)?;
|
||||
let versioned_message: VersionedMessage = VersionedMessage::V0(v0_message);
|
||||
let transaction = VersionedTransaction::try_new(versioned_message, &[&payer])?;
|
||||
|
||||
Ok(transaction)
|
||||
}
|
||||
|
||||
pub async fn build_buy_instructions(
|
||||
rpc: Arc<SolanaRpcClient>,
|
||||
payer: Arc<Keypair>,
|
||||
mint: Arc<Pubkey>,
|
||||
amount_sol: u64,
|
||||
slippage_basis_points: Option<u64>,
|
||||
) -> Result<Vec<Instruction>, anyhow::Error> {
|
||||
if amount_sol == 0 {
|
||||
return Err(anyhow!("Amount cannot be zero"));
|
||||
}
|
||||
|
||||
let rpc = rpc.as_ref();
|
||||
let global_account = get_global_account(rpc).await?;
|
||||
let buy_amount = match get_bonding_curve_account(rpc, mint.as_ref()).await {
|
||||
Ok(account) => account.get_buy_price(amount_sol).map_err(|e| anyhow!(e))?,
|
||||
Err(_e) => {
|
||||
println!("Bonding curve account not found, using initial buy price: {}", _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![];
|
||||
instructions.push(create_associated_token_account(
|
||||
&payer.pubkey(),
|
||||
&payer.pubkey(),
|
||||
&mint,
|
||||
&constants::accounts::TOKEN_PROGRAM,
|
||||
));
|
||||
|
||||
instructions.push(instruction::buy(
|
||||
payer.as_ref(),
|
||||
&mint,
|
||||
&global_account.fee_recipient,
|
||||
instruction::Buy {
|
||||
_amount: buy_amount,
|
||||
_max_sol_cost: buy_amount_with_slippage,
|
||||
},
|
||||
));
|
||||
|
||||
Ok(instructions)
|
||||
}
|
||||
Executable
+207
@@ -0,0 +1,207 @@
|
||||
use anyhow::anyhow;
|
||||
use spl_token::state::Account;
|
||||
use tokio::sync::RwLock;
|
||||
use std::{collections::HashMap, sync::Arc};
|
||||
use solana_sdk::{
|
||||
commitment_config::CommitmentConfig, compute_budget::ComputeBudgetInstruction, instruction::Instruction, program_pack::Pack, 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, PriorityFee, SolanaRpcClient}, constants::{self, trade::DEFAULT_SLIPPAGE}};
|
||||
use borsh::BorshDeserialize;
|
||||
|
||||
lazy_static::lazy_static! {
|
||||
static ref ACCOUNT_CACHE: RwLock<HashMap<Pubkey, Arc<accounts::GlobalAccount>>> = RwLock::new(HashMap::new());
|
||||
}
|
||||
|
||||
pub async fn transfer_sol(rpc: &SolanaRpcClient, payer: &Keypair, receive_wallet: &Pubkey, amount: u64) -> Result<(), anyhow::Error> {
|
||||
if amount == 0 {
|
||||
return Err(anyhow!("transfer_sol: Amount cannot be zero"));
|
||||
}
|
||||
|
||||
let balance = get_sol_balance(rpc, &payer.pubkey()).await?;
|
||||
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().await?;
|
||||
|
||||
let transaction = Transaction::new_signed_with_payer(
|
||||
&[transfer_instruction],
|
||||
Some(&payer.pubkey()),
|
||||
&[payer],
|
||||
recent_blockhash,
|
||||
);
|
||||
|
||||
rpc.send_and_confirm_transaction(&transaction).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn create_priority_fee_instructions(priority_fee: PriorityFee) -> Vec<Instruction> {
|
||||
let mut instructions = Vec::with_capacity(2);
|
||||
instructions.push(ComputeBudgetInstruction::set_compute_unit_limit(priority_fee.unit_limit));
|
||||
instructions.push(ComputeBudgetInstruction::set_compute_unit_price(priority_fee.unit_price));
|
||||
|
||||
instructions
|
||||
}
|
||||
|
||||
// #[inline]
|
||||
pub async fn get_token_balance(rpc: &SolanaRpcClient, payer: &Pubkey, mint: &Pubkey) -> Result<u64, anyhow::Error> {
|
||||
let ata = get_associated_token_address(payer, mint);
|
||||
// let account_data = rpc.get_account_data(&ata).await?;
|
||||
// let token_account = Account::unpack(&account_data.as_slice())?;
|
||||
|
||||
// Ok(token_account.amount)
|
||||
|
||||
// println!("get_token_balance ata: {}", ata);
|
||||
let balance = rpc.get_token_account_balance(&ata).await?;
|
||||
let balance_u64 = balance.amount.parse::<u64>()
|
||||
.map_err(|_| anyhow!("Failed to parse token balance"))?;
|
||||
Ok(balance_u64)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub async fn get_token_balance_and_ata(rpc: &SolanaRpcClient, payer: &Keypair, mint: &Pubkey) -> Result<(u64, Pubkey), anyhow::Error> {
|
||||
let ata = get_associated_token_address(&payer.pubkey(), mint);
|
||||
// let account_data = rpc.get_account_data(&ata).await?;
|
||||
// let token_account = Account::unpack(&account_data)?;
|
||||
|
||||
// Ok((token_account.amount, ata))
|
||||
|
||||
let balance = rpc.get_token_account_balance(&ata).await?;
|
||||
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))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub async fn get_sol_balance(rpc: &SolanaRpcClient, account: &Pubkey) -> Result<u64, anyhow::Error> {
|
||||
println!("get_sol_balance account: {}", account);
|
||||
let balance = rpc.get_balance(account).await?;
|
||||
println!("get_sol_balance balance: {}", balance);
|
||||
Ok(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: &SolanaRpcClient) -> Result<Arc<accounts::GlobalAccount>, anyhow::Error> {
|
||||
let global = get_global_pda();
|
||||
if let Some(account) = ACCOUNT_CACHE.read().await.get(&global) {
|
||||
return Ok(account.clone());
|
||||
}
|
||||
|
||||
let account = rpc.get_account(&global).await?;
|
||||
let global_account = bincode::deserialize::<accounts::GlobalAccount>(&account.data)?;
|
||||
let global_account = Arc::new(global_account);
|
||||
|
||||
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: &SolanaRpcClient,
|
||||
mint: &Pubkey,
|
||||
) -> Result<Arc<accounts::BondingCurveAccount>, anyhow::Error> {
|
||||
let bonding_curve_pda = get_bonding_curve_pda(mint)
|
||||
.ok_or(anyhow!("Bonding curve not found"))?;
|
||||
|
||||
let account = rpc.get_account(&bonding_curve_pda).await?;
|
||||
if account.data.is_empty() {
|
||||
return Err(anyhow!("Bonding curve not found"));
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
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
|
||||
}
|
||||
|
||||
#[inline]
|
||||
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
|
||||
}
|
||||
Executable
+322
@@ -0,0 +1,322 @@
|
||||
use std::{str::FromStr, time::Instant, sync::Arc};
|
||||
|
||||
use anyhow::anyhow;
|
||||
use solana_client::rpc_config::RpcSimulateTransactionConfig;
|
||||
use solana_sdk::{
|
||||
commitment_config::CommitmentConfig, compute_budget::ComputeBudgetInstruction, instruction::Instruction, message::{v0, VersionedMessage}, native_token::sol_to_lamports, pubkey::Pubkey, signature::{Keypair, Signature}, signer::Signer, system_instruction, transaction::{Transaction, VersionedTransaction}
|
||||
};
|
||||
use spl_associated_token_account::{
|
||||
instruction::create_associated_token_account,
|
||||
};
|
||||
|
||||
use crate::{
|
||||
common::{PriorityFee, SolanaRpcClient}, constants, instruction,
|
||||
ipfs::TokenMetadataIPFS, jito::FeeClient,
|
||||
pumpfun::buy::build_buy_transaction_with_tip
|
||||
};
|
||||
|
||||
use crate::pumpfun::common::{
|
||||
create_priority_fee_instructions,
|
||||
get_buy_amount_with_slippage, get_global_account
|
||||
};
|
||||
|
||||
/// Create a new token
|
||||
pub async fn create(
|
||||
rpc: Arc<SolanaRpcClient>,
|
||||
payer: Arc<Keypair>,
|
||||
mint: Keypair,
|
||||
ipfs: TokenMetadataIPFS,
|
||||
priority_fee: PriorityFee,
|
||||
) -> Result<(), anyhow::Error> {
|
||||
let mut instructions = create_priority_fee_instructions(priority_fee);
|
||||
|
||||
instructions.push(instruction::create(
|
||||
payer.as_ref(),
|
||||
&mint,
|
||||
instruction::Create {
|
||||
_name: ipfs.metadata.name,
|
||||
_symbol: ipfs.metadata.symbol,
|
||||
_uri: ipfs.metadata_uri,
|
||||
},
|
||||
));
|
||||
|
||||
let recent_blockhash = rpc.get_latest_blockhash().await?;
|
||||
let transaction = Transaction::new_signed_with_payer(
|
||||
&instructions,
|
||||
Some(&payer.pubkey()),
|
||||
&[payer.as_ref(), &mint],
|
||||
recent_blockhash,
|
||||
);
|
||||
|
||||
rpc.send_and_confirm_transaction(&transaction).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Create and buy tokens in one transaction
|
||||
pub async fn create_and_buy(
|
||||
rpc: Arc<SolanaRpcClient>,
|
||||
payer: Arc<Keypair>,
|
||||
mint: Keypair,
|
||||
ipfs: TokenMetadataIPFS,
|
||||
amount_sol: u64,
|
||||
slippage_basis_points: Option<u64>,
|
||||
priority_fee: PriorityFee,
|
||||
) -> Result<(), anyhow::Error> {
|
||||
if amount_sol == 0 {
|
||||
return Err(anyhow!("Amount cannot be zero"));
|
||||
}
|
||||
|
||||
let mint = Arc::new(mint);
|
||||
let transaction = build_create_and_buy_transaction(rpc.clone(), payer.clone(), mint.clone(), ipfs, amount_sol, slippage_basis_points, priority_fee.clone()).await?;
|
||||
rpc.send_and_confirm_transaction(&transaction).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn create_and_buy_with_tip(
|
||||
rpc: Arc<SolanaRpcClient>,
|
||||
fee_clients: Vec<Arc<FeeClient>>,
|
||||
payer: Arc<Keypair>,
|
||||
mint: Keypair,
|
||||
ipfs: TokenMetadataIPFS,
|
||||
amount_sol: u64,
|
||||
slippage_basis_points: Option<u64>,
|
||||
priority_fee: PriorityFee,
|
||||
) -> Result<(), anyhow::Error> {
|
||||
let start_time = Instant::now();
|
||||
let mint = Arc::new(mint);
|
||||
let build_instructions = build_create_and_buy_instructions(rpc.clone(), payer.clone(), mint.clone(), ipfs.clone(), amount_sol, slippage_basis_points, priority_fee.clone()).await?;
|
||||
let mut handles = vec![];
|
||||
for fee_client in fee_clients {
|
||||
let rpc = rpc.clone();
|
||||
let payer = payer.clone();
|
||||
let mint = mint.clone();
|
||||
let priority_fee = priority_fee.clone();
|
||||
let tip_account = fee_client.get_tip_account().await.map_err(|e| anyhow!(e.to_string()))?;
|
||||
let tip_account = Arc::new(Pubkey::from_str(&tip_account).map_err(|e| anyhow!(e))?);
|
||||
let build_instructions = build_instructions.clone();
|
||||
|
||||
let handle = tokio::spawn(async move {
|
||||
let transaction = build_create_and_buy_transaction_with_tip(rpc, tip_account, payer, mint, priority_fee, build_instructions).await?;
|
||||
fee_client.send_transaction(&transaction).await.map_err(|e| anyhow!(e.to_string()))?;
|
||||
println!("Total Jito create and buy operation time: {:?}ms", start_time.elapsed().as_millis());
|
||||
Ok::<(), anyhow::Error>(())
|
||||
});
|
||||
|
||||
handles.push(handle);
|
||||
}
|
||||
|
||||
for handle in handles {
|
||||
match handle.await {
|
||||
Ok(Ok(_)) => (),
|
||||
Ok(Err(e)) => println!("Error in task: {}", e),
|
||||
Err(e) => println!("Task join error: {}", e),
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn build_create_and_buy_transaction(
|
||||
rpc: Arc<SolanaRpcClient>,
|
||||
payer: Arc<Keypair>,
|
||||
mint: Arc<Keypair>,
|
||||
ipfs: TokenMetadataIPFS,
|
||||
amount_sol: u64,
|
||||
slippage_basis_points: Option<u64>,
|
||||
priority_fee: PriorityFee,
|
||||
) -> Result<Transaction, anyhow::Error> {
|
||||
let mut instructions = vec![
|
||||
ComputeBudgetInstruction::set_compute_unit_price(priority_fee.unit_price),
|
||||
ComputeBudgetInstruction::set_compute_unit_limit(priority_fee.unit_limit),
|
||||
];
|
||||
|
||||
let build_instructions = build_create_and_buy_instructions(rpc.clone(), payer.clone(), mint.clone(), ipfs, amount_sol, slippage_basis_points, priority_fee.clone()).await?;
|
||||
instructions.extend(build_instructions);
|
||||
|
||||
let recent_blockhash = rpc.get_latest_blockhash().await?;
|
||||
let transaction = Transaction::new_signed_with_payer(
|
||||
&instructions,
|
||||
Some(&payer.pubkey()),
|
||||
&[payer.as_ref(), mint.as_ref()],
|
||||
recent_blockhash,
|
||||
);
|
||||
|
||||
Ok(transaction)
|
||||
}
|
||||
|
||||
pub async fn build_create_and_buy_transaction_with_tip(
|
||||
rpc: Arc<SolanaRpcClient>,
|
||||
tip_account: Arc<Pubkey>,
|
||||
payer: Arc<Keypair>,
|
||||
mint: Arc<Keypair>,
|
||||
priority_fee: PriorityFee,
|
||||
build_instructions: Vec<Instruction>,
|
||||
) -> Result<VersionedTransaction, anyhow::Error> {
|
||||
let mut instructions = vec![
|
||||
ComputeBudgetInstruction::set_compute_unit_price(priority_fee.unit_price),
|
||||
ComputeBudgetInstruction::set_compute_unit_limit(priority_fee.unit_limit),
|
||||
system_instruction::transfer(
|
||||
&payer.pubkey(),
|
||||
&tip_account,
|
||||
sol_to_lamports(priority_fee.buy_tip_fee),
|
||||
),
|
||||
];
|
||||
instructions.extend(build_instructions);
|
||||
|
||||
let recent_blockhash = rpc.get_latest_blockhash().await?;
|
||||
let v0_message: v0::Message =
|
||||
v0::Message::try_compile(&payer.pubkey(), &instructions, &[], recent_blockhash)?;
|
||||
|
||||
let versioned_message: VersionedMessage = VersionedMessage::V0(v0_message);
|
||||
let transaction = VersionedTransaction::try_new(versioned_message, &[&payer])?;
|
||||
|
||||
Ok(transaction)
|
||||
}
|
||||
|
||||
// pub async fn build_create_and_buy_instructions(
|
||||
// rpc: Arc<SolanaRpcClient>,
|
||||
// payer: Arc<Keypair>,
|
||||
// mint: Arc<Keypair>,
|
||||
// ipfs: TokenMetadataIPFS,
|
||||
// amount_sol: u64,
|
||||
// slippage_basis_points: Option<u64>,
|
||||
// priority_fee: PriorityFee,
|
||||
// ) -> Result<Vec<Instruction>, anyhow::Error> {
|
||||
// if amount_sol == 0 {
|
||||
// return Err(anyhow!("Amount cannot be zero"));
|
||||
// }
|
||||
|
||||
// let rpc = rpc.as_ref();
|
||||
// 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.as_ref(),
|
||||
// mint.as_ref(),
|
||||
// instruction::Create {
|
||||
// _name: ipfs.metadata.name,
|
||||
// _symbol: ipfs.metadata.symbol,
|
||||
// _uri: ipfs.metadata_uri,
|
||||
// },
|
||||
// ));
|
||||
|
||||
// instructions.push(create_associated_token_account(
|
||||
// &payer.pubkey(),
|
||||
// &payer.pubkey(),
|
||||
// &mint.pubkey(),
|
||||
// &constants::accounts::TOKEN_PROGRAM,
|
||||
// ));
|
||||
|
||||
|
||||
// instructions.push(instruction::buy(
|
||||
// payer.as_ref(),
|
||||
// &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).await?.0;
|
||||
|
||||
// let simulate_tx = Transaction::new_signed_with_payer(
|
||||
// &instructions,
|
||||
// Some(&payer.pubkey()),
|
||||
// &[payer.as_ref(), mint.as_ref()],
|
||||
// recent_blockhash,
|
||||
// );
|
||||
|
||||
// let config = RpcSimulateTransactionConfig {
|
||||
// sig_verify: true,
|
||||
// commitment: Some(commitment_config),
|
||||
// ..RpcSimulateTransactionConfig::default()
|
||||
// };
|
||||
|
||||
// let result = rpc.simulate_transaction_with_config(&simulate_tx, config).await?.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(&[]).await?;
|
||||
// let average_fees = if fees.is_empty() {
|
||||
// priority_fee.unit_price
|
||||
// } else {
|
||||
// fees.iter()
|
||||
// .map(|fee| fee.prioritization_fee)
|
||||
// .sum::<u64>() / fees.len() as u64
|
||||
// };
|
||||
|
||||
// let unit_price = if average_fees == 0 { priority_fee.unit_price } else { average_fees };
|
||||
|
||||
// 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(
|
||||
rpc: Arc<SolanaRpcClient>,
|
||||
payer: Arc<Keypair>,
|
||||
mint: Arc<Keypair>,
|
||||
ipfs: TokenMetadataIPFS,
|
||||
amount_sol: u64,
|
||||
slippage_basis_points: Option<u64>,
|
||||
priority_fee: PriorityFee,
|
||||
) -> Result<Vec<Instruction>, anyhow::Error> {
|
||||
if amount_sol == 0 {
|
||||
return Err(anyhow!("Amount cannot be zero"));
|
||||
}
|
||||
|
||||
let rpc = rpc.as_ref();
|
||||
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_price(priority_fee.unit_price),
|
||||
ComputeBudgetInstruction::set_compute_unit_limit(priority_fee.unit_limit),
|
||||
];
|
||||
|
||||
instructions.push(instruction::create(
|
||||
payer.as_ref(),
|
||||
mint.as_ref(),
|
||||
instruction::Create {
|
||||
_name: ipfs.metadata.name.clone(),
|
||||
_symbol: ipfs.metadata.symbol.clone(),
|
||||
_uri: ipfs.metadata_uri.clone(),
|
||||
},
|
||||
));
|
||||
|
||||
instructions.push(create_associated_token_account(
|
||||
&payer.pubkey(),
|
||||
&payer.pubkey(),
|
||||
&mint.pubkey(),
|
||||
&constants::accounts::TOKEN_PROGRAM,
|
||||
));
|
||||
|
||||
instructions.push(instruction::buy(
|
||||
payer.as_ref(),
|
||||
&mint.pubkey(),
|
||||
&global_account.fee_recipient,
|
||||
instruction::Buy {
|
||||
_amount: buy_amount,
|
||||
_max_sol_cost: buy_amount_with_slippage,
|
||||
},
|
||||
));
|
||||
|
||||
Ok(instructions)
|
||||
}
|
||||
Executable
+4
@@ -0,0 +1,4 @@
|
||||
pub mod buy;
|
||||
pub mod create;
|
||||
pub mod sell;
|
||||
pub mod common;
|
||||
Executable
+229
@@ -0,0 +1,229 @@
|
||||
use anyhow::anyhow;
|
||||
use solana_client::rpc_config::RpcSimulateTransactionConfig;
|
||||
use solana_sdk::{
|
||||
commitment_config::CommitmentConfig, compute_budget::ComputeBudgetInstruction, instruction::Instruction, message::{v0, VersionedMessage}, native_token::sol_to_lamports, pubkey::Pubkey, signature::{Keypair, Signature}, signer::Signer, system_instruction, transaction::{Transaction, VersionedTransaction}
|
||||
};
|
||||
use solana_hash::Hash;
|
||||
use spl_associated_token_account::get_associated_token_address;
|
||||
use spl_token::instruction::close_account;
|
||||
use tokio::task::JoinHandle;
|
||||
|
||||
use std::{str::FromStr, time::Instant, sync::Arc};
|
||||
|
||||
use crate::{common::{PriorityFee, SolanaRpcClient}, constants::trade::{DEFAULT_COMPUTE_UNIT_PRICE, DEFAULT_SLIPPAGE}, instruction, jito::FeeClient};
|
||||
|
||||
use super::common::{calculate_with_slippage_sell, get_bonding_curve_account, get_global_account};
|
||||
|
||||
async fn get_token_balance(rpc: &SolanaRpcClient, 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).await?;
|
||||
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: Arc<SolanaRpcClient>,
|
||||
payer: Arc<Keypair>,
|
||||
mint: Pubkey,
|
||||
amount_token: Option<u64>,
|
||||
slippage_basis_points: Option<u64>,
|
||||
priority_fee: PriorityFee,
|
||||
) -> Result<(), anyhow::Error> {
|
||||
let instructions = build_sell_instructions(rpc.clone(), payer.clone(), mint.clone(), amount_token, slippage_basis_points).await?;
|
||||
let transaction = build_sell_transaction(rpc.clone(), payer.clone(), priority_fee, instructions).await?;
|
||||
rpc.send_and_confirm_transaction(&transaction).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Sell tokens by percentage
|
||||
pub async fn sell_by_percent(
|
||||
rpc: Arc<SolanaRpcClient>,
|
||||
payer: Arc<Keypair>,
|
||||
mint: Pubkey,
|
||||
percent: u64,
|
||||
slippage_basis_points: Option<u64>,
|
||||
priority_fee: PriorityFee,
|
||||
) -> Result<(), anyhow::Error> {
|
||||
if percent == 0 || percent > 100 {
|
||||
return Err(anyhow!("Percentage must be between 1 and 100"));
|
||||
}
|
||||
|
||||
let (balance_u64, _) = get_token_balance(rpc.as_ref(), payer.as_ref(), &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: Arc<SolanaRpcClient>,
|
||||
fee_clients: Vec<Arc<FeeClient>>,
|
||||
payer: Arc<Keypair>,
|
||||
mint: Pubkey,
|
||||
percent: u64,
|
||||
slippage_basis_points: Option<u64>,
|
||||
priority_fee: PriorityFee,
|
||||
) -> Result<(), anyhow::Error> {
|
||||
if percent == 0 || percent > 100 {
|
||||
return Err(anyhow!("Percentage must be between 1 and 100"));
|
||||
}
|
||||
|
||||
let (balance_u64, _) = get_token_balance(rpc.as_ref(), payer.as_ref(), &mint).await?;
|
||||
let amount = balance_u64 * percent / 100;
|
||||
sell_with_jito(rpc, fee_clients, payer, mint, Some(amount), slippage_basis_points, priority_fee).await
|
||||
}
|
||||
|
||||
/// Sell tokens using Jito
|
||||
pub async fn sell_with_jito(
|
||||
rpc: Arc<SolanaRpcClient>,
|
||||
fee_clients: Vec<Arc<FeeClient>>,
|
||||
payer: Arc<Keypair>,
|
||||
mint: Pubkey,
|
||||
amount_token: Option<u64>,
|
||||
slippage_basis_points: Option<u64>,
|
||||
priority_fee: PriorityFee,
|
||||
) -> Result<(), anyhow::Error> {
|
||||
let start_time = Instant::now();
|
||||
|
||||
let mut transactions = vec![];
|
||||
let instructions = build_sell_instructions(rpc.clone(), payer.clone(), mint.clone(), amount_token, slippage_basis_points).await?;
|
||||
|
||||
let recent_blockhash = rpc.get_latest_blockhash().await?;
|
||||
for fee_client in fee_clients.clone() {
|
||||
let payer = payer.clone();
|
||||
let priority_fee = priority_fee.clone();
|
||||
let tip_account = fee_client.get_tip_account().await.map_err(|e| anyhow!(e.to_string()))?;
|
||||
let tip_account = Arc::new(Pubkey::from_str(&tip_account).map_err(|e| anyhow!(e))?);
|
||||
|
||||
let transaction = build_sell_transaction_with_tip(tip_account, payer, priority_fee, instructions.clone(), recent_blockhash).await?;
|
||||
transactions.push(transaction);
|
||||
}
|
||||
|
||||
let mut handles = vec![];
|
||||
for i in 0..fee_clients.len() {
|
||||
let fee_client = fee_clients[i].clone();
|
||||
let transaction = transactions[i].clone();
|
||||
let handle: JoinHandle<Result<(), anyhow::Error>> = tokio::spawn(async move {
|
||||
fee_client.send_transaction(&transaction).await?;
|
||||
println!("index: {}, Total Jito sell operation time: {:?}ms", i, start_time.elapsed().as_millis());
|
||||
Ok(())
|
||||
});
|
||||
|
||||
handles.push(handle);
|
||||
}
|
||||
|
||||
for handle in handles {
|
||||
match handle.await {
|
||||
Ok(Ok(_)) => (),
|
||||
Ok(Err(e)) => println!("Error in task: {}", e),
|
||||
Err(e) => println!("Task join error: {}", e),
|
||||
}
|
||||
}
|
||||
|
||||
println!("Total Jito sell operation time: {:?}ms", start_time.elapsed().as_millis());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn build_sell_transaction(
|
||||
rpc: Arc<SolanaRpcClient>,
|
||||
payer: Arc<Keypair>,
|
||||
priority_fee: PriorityFee,
|
||||
build_instructions: Vec<Instruction>
|
||||
) -> Result<Transaction, anyhow::Error> {
|
||||
let mut instructions = vec![
|
||||
ComputeBudgetInstruction::set_compute_unit_price(priority_fee.unit_price),
|
||||
ComputeBudgetInstruction::set_compute_unit_limit(priority_fee.unit_limit),
|
||||
];
|
||||
|
||||
instructions.extend(build_instructions);
|
||||
|
||||
let recent_blockhash = rpc.get_latest_blockhash().await?;
|
||||
let transaction = Transaction::new_signed_with_payer(
|
||||
&instructions,
|
||||
Some(&payer.pubkey()),
|
||||
&[payer.as_ref()],
|
||||
recent_blockhash,
|
||||
);
|
||||
|
||||
Ok(transaction)
|
||||
}
|
||||
|
||||
pub async fn build_sell_transaction_with_tip(
|
||||
tip_account: Arc<Pubkey>,
|
||||
payer: Arc<Keypair>,
|
||||
priority_fee: PriorityFee,
|
||||
build_instructions: Vec<Instruction>,
|
||||
blockhash: Hash,
|
||||
) -> Result<VersionedTransaction, anyhow::Error> {
|
||||
let mut instructions = vec![
|
||||
ComputeBudgetInstruction::set_compute_unit_price(priority_fee.unit_price),
|
||||
ComputeBudgetInstruction::set_compute_unit_limit(priority_fee.unit_limit),
|
||||
system_instruction::transfer(
|
||||
&payer.pubkey(),
|
||||
&tip_account,
|
||||
sol_to_lamports(priority_fee.sell_tip_fee),
|
||||
),
|
||||
];
|
||||
|
||||
instructions.extend(build_instructions);
|
||||
|
||||
let v0_message: v0::Message =
|
||||
v0::Message::try_compile(&payer.pubkey(), &instructions, &[], blockhash)?;
|
||||
let versioned_message: VersionedMessage = VersionedMessage::V0(v0_message);
|
||||
|
||||
let transaction = VersionedTransaction::try_new(versioned_message, &[&payer])?;
|
||||
|
||||
Ok(transaction)
|
||||
}
|
||||
|
||||
pub async fn build_sell_instructions(
|
||||
rpc: Arc<SolanaRpcClient>,
|
||||
payer: Arc<Keypair>,
|
||||
mint: Pubkey,
|
||||
amount_token: Option<u64>,
|
||||
slippage_basis_points: Option<u64>,
|
||||
) -> Result<Vec<Instruction>, anyhow::Error> {
|
||||
let (balance_u64, ata) = get_token_balance(rpc.as_ref(), payer.as_ref(), &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.as_ref()).await?;
|
||||
let bonding_curve_account = get_bonding_curve_account(rpc.as_ref(), &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 instructions = vec![
|
||||
instruction::sell(
|
||||
payer.as_ref(),
|
||||
&mint,
|
||||
&global_account.fee_recipient,
|
||||
instruction::Sell {
|
||||
_amount: amount,
|
||||
_min_sol_output: min_sol_output_with_slippage,
|
||||
},
|
||||
),
|
||||
|
||||
close_account(
|
||||
&spl_token::ID,
|
||||
&ata,
|
||||
&payer.pubkey(),
|
||||
&payer.pubkey(),
|
||||
&[&payer.pubkey()],
|
||||
)?
|
||||
];
|
||||
|
||||
Ok(instructions)
|
||||
}
|
||||
Reference in New Issue
Block a user