feat: add flexible nonce parameter support

- Add nonce_account and current_nonce to trade parameters
- Remove hardcoded NonceCache dependency from nonce_manager
- Update examples and documentation for new nonce usage
- Fix nonce documentation errors and improve clarity
This commit is contained in:
ysq
2025-09-19 18:02:11 +08:00
parent a53038855e
commit 4907aafead
26 changed files with 214 additions and 71 deletions
-9
View File
@@ -85,15 +85,6 @@ impl AddressLookupTableCache {
key: *lookup_table_address,
addresses: Vec::new(),
});
if result.addresses.len() == 0 {
eprintln!(" ❌ Address lookup table account {} not setup", lookup_table_address);
eprintln!(" ❌ Please update the address table account information using 【AddressLookupTableCache】 first");
eprintln!(
" ❌ The current transaction will not include this address lookup table account"
);
}
return result;
}
}
+13 -1
View File
@@ -17,8 +17,8 @@ use crate::trading::core::params::RaydiumCpmmParams;
use crate::trading::core::traits::ProtocolParams;
use crate::trading::factory::DexType;
use crate::trading::BuyParams;
use crate::trading::SellParams;
use crate::trading::MiddlewareManager;
use crate::trading::SellParams;
use crate::trading::TradeFactory;
use common::SolanaRpcClient;
use parking_lot::Mutex;
@@ -90,6 +90,10 @@ pub struct TradeBuyParams {
pub create_mint_ata: bool,
/// Whether to enable seed-based optimization for account creation
pub open_seed_optimize: bool,
/// Nonce account for transaction validity
pub nonce_account: Option<Pubkey>,
/// Recent nonce for transaction validity
pub current_nonce: Option<Hash>,
}
/// Parameters for executing sell orders across different DEX protocols
@@ -124,6 +128,10 @@ pub struct TradeSellParams {
pub close_wsol_ata: bool,
/// Whether to enable seed-based optimization for account creation
pub open_seed_optimize: bool,
/// Nonce account for transaction validity
pub nonce_account: Option<Pubkey>,
/// Recent nonce for transaction validity
pub current_nonce: Option<Hash>,
}
impl SolanaTrade {
@@ -264,6 +272,8 @@ impl SolanaTrade {
create_mint_ata: params.create_mint_ata,
swqos_clients: self.swqos_clients.clone(),
middleware_manager: self.middleware_manager.clone(),
nonce_account: params.nonce_account,
current_nonce: params.current_nonce,
};
// Validate protocol params
@@ -334,6 +344,8 @@ impl SolanaTrade {
middleware_manager: self.middleware_manager.clone(),
create_wsol_ata: params.create_wsol_ata,
close_wsol_ata: params.close_wsol_ata,
nonce_account: params.nonce_account,
current_nonce: params.current_nonce,
};
// Validate protocol params
+23 -2
View File
@@ -1,16 +1,37 @@
use std::sync::Arc;
use solana_sdk::{message::AddressLookupTableAccount, pubkey::Pubkey};
use crate::common::address_lookup_cache::get_address_lookup_table_account;
use crate::common::{
address_lookup_cache::{get_address_lookup_table_account, AddressLookupTableCache},
SolanaRpcClient,
};
/// Get address lookup table account list
/// If lookup_table_key is provided, get the corresponding account, otherwise return empty list
pub async fn get_address_lookup_table_accounts(
rpc: Option<Arc<SolanaRpcClient>>,
lookup_table_key: Option<Pubkey>,
) -> Vec<AddressLookupTableAccount> {
match lookup_table_key {
Some(key) => {
let account = get_address_lookup_table_account(&key).await;
vec![account]
if account.addresses.len() == 0 {
if rpc.is_some() {
let _ = AddressLookupTableCache::get_instance()
.set_address_lookup_table(rpc.unwrap(), &key)
.await;
let new_account = get_address_lookup_table_account(&key).await;
if new_account.addresses.len() == 0 {
return Vec::new();
} else {
return vec![new_account];
}
} else {
return Vec::new();
}
}
return vec![account];
}
None => Vec::new(),
}
+12 -26
View File
@@ -1,10 +1,7 @@
use anyhow::anyhow;
use solana_hash::Hash;
use solana_sdk::{instruction::Instruction, signature::Keypair, signer::Signer};
use solana_sdk::{instruction::Instruction, pubkey::Pubkey, signature::Keypair, signer::Signer};
use solana_system_interface::instruction::advance_nonce_account;
use crate::common::nonce_cache::NonceCache;
/// Add nonce advance instruction to the instruction set
///
/// Nonce functionality is only used when nonce_pubkey is provided
@@ -13,36 +10,25 @@ use crate::common::nonce_cache::NonceCache;
pub fn add_nonce_instruction(
instructions: &mut Vec<Instruction>,
payer: &Keypair,
nonce_account: Option<Pubkey>,
current_nonce: Option<Hash>,
) -> Result<(), anyhow::Error> {
let nonce_cache = NonceCache::get_instance();
let nonce_info = nonce_cache.get_nonce_info();
// Only check if nonce_account exists
if let Some(nonce_pubkey) = nonce_info.nonce_account {
if nonce_info.used {
return Err(anyhow!("Nonce is used"));
}
if nonce_info.current_nonce == Hash::default() {
return Err(anyhow!("Nonce is not ready"));
}
// Create Solana system nonce advance instruction - using system program ID
let nonce_advance_ix = advance_nonce_account(&nonce_pubkey, &payer.pubkey());
if nonce_account.is_some() && current_nonce.is_some() {
let nonce_advance_ix = advance_nonce_account(&nonce_account.unwrap(), &payer.pubkey());
instructions.push(nonce_advance_ix);
}
Ok(())
}
/// Get blockhash for transaction
/// If nonce account is used, return blockhash from nonce, otherwise return the provided recent_blockhash
pub fn get_transaction_blockhash(recent_blockhash: Hash) -> Hash {
let nonce_cache = NonceCache::get_instance();
let nonce_info = nonce_cache.get_nonce_info();
if nonce_info.nonce_account.is_some() {
nonce_info.current_nonce
pub fn get_transaction_blockhash(
recent_blockhash: Hash,
nonce_account: Option<Pubkey>,
current_nonce: Option<Hash>,
) -> Hash {
if nonce_account.is_some() && current_nonce.is_some() {
current_nonce.unwrap()
} else {
recent_blockhash
}
+10 -5
View File
@@ -16,11 +16,12 @@ use super::{
compute_budget_manager::compute_budget_instructions,
nonce_manager::{add_nonce_instruction, get_transaction_blockhash},
};
use crate::trading::MiddlewareManager;
use crate::{common::SolanaRpcClient, trading::MiddlewareManager};
/// Build standard RPC transaction
pub async fn build_transaction(
payer: Arc<Keypair>,
rpc: Option<Arc<SolanaRpcClient>>,
unit_limit: u32,
unit_price: u64,
business_instructions: Vec<Instruction>,
@@ -33,11 +34,15 @@ pub async fn build_transaction(
with_tip: bool,
tip_account: &Pubkey,
tip_amount: f64,
nonce_account: Option<Pubkey>,
current_nonce: Option<Hash>,
) -> Result<VersionedTransaction, anyhow::Error> {
let mut instructions = Vec::with_capacity(business_instructions.len() + 5);
// Add nonce instruction
if let Err(e) = add_nonce_instruction(&mut instructions, payer.as_ref()) {
if let Err(e) =
add_nonce_instruction(&mut instructions, payer.as_ref(), nonce_account, current_nonce)
{
return Err(e);
}
@@ -62,11 +67,11 @@ pub async fn build_transaction(
instructions.extend(business_instructions);
// Get blockhash for transaction
let blockhash =
if is_buy { get_transaction_blockhash(recent_blockhash) } else { recent_blockhash };
let blockhash = get_transaction_blockhash(recent_blockhash, nonce_account, current_nonce);
// Get address lookup table accounts
let address_lookup_table_accounts = get_address_lookup_table_accounts(lookup_table_key).await;
let address_lookup_table_accounts =
get_address_lookup_table_accounts(rpc, lookup_table_key).await;
// Build transaction
build_versioned_transaction(
+14 -1
View File
@@ -8,7 +8,7 @@ use tokio::sync::mpsc;
use tokio::task::JoinHandle;
use crate::{
common::GasFeeStrategy,
common::{GasFeeStrategy, SolanaRpcClient},
swqos::{SwqosClient, SwqosType, TradeType},
trading::{common::build_transaction, BuyParams, MiddlewareManager, SellParams},
};
@@ -21,9 +21,12 @@ pub async fn buy_parallel_execute(
parallel_execute(
params.swqos_clients,
params.payer,
params.rpc,
instructions,
params.lookup_table_key,
params.recent_blockhash,
params.nonce_account,
params.current_nonce,
params.data_size_limit,
params.middleware_manager,
protocol_name,
@@ -42,9 +45,12 @@ pub async fn sell_parallel_execute(
parallel_execute(
params.swqos_clients,
params.payer,
params.rpc,
instructions,
params.lookup_table_key,
params.recent_blockhash,
params.nonce_account,
params.current_nonce,
0,
params.middleware_manager,
protocol_name,
@@ -59,9 +65,12 @@ pub async fn sell_parallel_execute(
async fn parallel_execute(
swqos_clients: Vec<Arc<SwqosClient>>,
payer: Arc<Keypair>,
rpc: Option<Arc<SolanaRpcClient>>,
instructions: Vec<Instruction>,
lookup_table_key: Option<Pubkey>,
recent_blockhash: Hash,
nonce_account: Option<Pubkey>,
current_nonce: Option<Hash>,
data_size_limit: u32,
middleware_manager: Option<Arc<MiddlewareManager>>,
protocol_name: &'static str,
@@ -123,6 +132,7 @@ async fn parallel_execute(
let unit_price = gas_fee_strategy_config.2.cu_price;
let swqos_type = swqos_type.clone();
let tip_account = tip_account.clone();
let rpc = rpc.clone();
let handle = tokio::spawn(async move {
core_affinity::set_for_current(core_id);
@@ -133,6 +143,7 @@ async fn parallel_execute(
let transaction = build_transaction(
payer,
rpc,
unit_limit,
unit_price,
instructions.as_ref().clone(),
@@ -145,6 +156,8 @@ async fn parallel_execute(
swqos_type != SwqosType::Default,
&tip_account,
tip_amount,
nonce_account,
current_nonce,
)
.await?;
+4
View File
@@ -35,6 +35,8 @@ pub struct BuyParams {
pub create_wsol_ata: bool,
pub close_wsol_ata: bool,
pub create_mint_ata: bool,
pub nonce_account: Option<Pubkey>,
pub current_nonce: Option<Hash>,
}
/// Sell parameters
@@ -55,6 +57,8 @@ pub struct SellParams {
pub middleware_manager: Option<Arc<MiddlewareManager>>,
pub create_wsol_ata: bool,
pub close_wsol_ata: bool,
pub nonce_account: Option<Pubkey>,
pub current_nonce: Option<Hash>,
}
impl std::fmt::Debug for BuyParams {