refactor: optimize trading execution architecture and add wSOL management
- Simplify TradeExecutor interface by integrating middleware and swqos clients into params - Refactor parallel execution module with dedicated buy/sell execute functions - Add SOL wrapping/unwrapping functionality for wSOL management - Remove redundant parameter passing in sell operations - Delete example main.rs file - Optimize transaction building with integrated parameter structures BREAKING CHANGE: TradeExecutor interface simplified, middleware and swqos_clients now passed through params
This commit is contained in:
+113
-33
@@ -25,21 +25,22 @@ pub enum InstructionCacheKey {
|
||||
owner: Pubkey,
|
||||
mint: Pubkey,
|
||||
token_program: Pubkey,
|
||||
use_seed: bool,
|
||||
},
|
||||
/// Close wSOL Account
|
||||
CloseWsolAccount { payer: Pubkey, wsol_token_account: Pubkey },
|
||||
}
|
||||
|
||||
/// Global instruction cache for storing common instructions
|
||||
static INSTRUCTION_CACHE: Lazy<RwLock<CLruCache<InstructionCacheKey, Instruction>>> =
|
||||
static INSTRUCTION_CACHE: Lazy<RwLock<CLruCache<InstructionCacheKey, Vec<Instruction>>>> =
|
||||
Lazy::new(|| {
|
||||
RwLock::new(CLruCache::new(NonZeroUsize::new(MAX_INSTRUCTION_CACHE_SIZE).unwrap()))
|
||||
});
|
||||
|
||||
/// Get cached instruction, compute and cache if not exists
|
||||
pub fn get_cached_instruction<F>(cache_key: InstructionCacheKey, compute_fn: F) -> Instruction
|
||||
pub fn get_cached_instructions<F>(cache_key: InstructionCacheKey, compute_fn: F) -> Vec<Instruction>
|
||||
where
|
||||
F: FnOnce() -> Instruction,
|
||||
F: FnOnce() -> Vec<Instruction>,
|
||||
{
|
||||
// Try to get from cache (using read lock)
|
||||
{
|
||||
@@ -63,41 +64,75 @@ where
|
||||
|
||||
// --------------------- Associated Token Account ---------------------
|
||||
|
||||
pub fn create_associated_token_account_idempotent_fast_use_seed(
|
||||
payer: &Pubkey,
|
||||
owner: &Pubkey,
|
||||
mint: &Pubkey,
|
||||
token_program: &Pubkey,
|
||||
use_seed: bool,
|
||||
) -> Vec<Instruction> {
|
||||
_create_associated_token_account_idempotent_fast(payer, owner, mint, token_program, use_seed)
|
||||
}
|
||||
|
||||
pub fn create_associated_token_account_idempotent_fast(
|
||||
payer: &Pubkey,
|
||||
owner: &Pubkey,
|
||||
mint: &Pubkey,
|
||||
token_program: &Pubkey,
|
||||
) -> Instruction {
|
||||
) -> Vec<Instruction> {
|
||||
_create_associated_token_account_idempotent_fast(payer, owner, mint, token_program, false)
|
||||
}
|
||||
|
||||
pub fn _create_associated_token_account_idempotent_fast(
|
||||
payer: &Pubkey,
|
||||
owner: &Pubkey,
|
||||
mint: &Pubkey,
|
||||
token_program: &Pubkey,
|
||||
use_seed: bool,
|
||||
) -> Vec<Instruction> {
|
||||
// Create cache key
|
||||
let cache_key = InstructionCacheKey::CreateAssociatedTokenAccount {
|
||||
payer: *payer,
|
||||
owner: *owner,
|
||||
mint: *mint,
|
||||
token_program: *token_program,
|
||||
use_seed,
|
||||
};
|
||||
|
||||
// Use cache to get instruction
|
||||
get_cached_instruction(cache_key, || {
|
||||
// Get Associated Token Address using cache
|
||||
let associated_token_address =
|
||||
get_associated_token_address_with_program_id_fast(owner, mint, token_program);
|
||||
|
||||
// Create Associated Token Account instruction
|
||||
// Reference implementation of spl_associated_token_account::instruction::create_associated_token_account
|
||||
Instruction {
|
||||
program_id: ASSOCIATED_TOKEN_PROGRAM_ID,
|
||||
accounts: vec![
|
||||
AccountMeta::new(*payer, true), // Payer (signer, writable)
|
||||
AccountMeta::new(associated_token_address, false), // ATA address (writable, non-signer)
|
||||
AccountMeta::new_readonly(*owner, false), // Token account owner (readonly, non-signer)
|
||||
AccountMeta::new_readonly(*mint, false), // Token mint address (readonly, non-signer)
|
||||
crate::constants::SYSTEM_PROGRAM_META,
|
||||
AccountMeta::new_readonly(*token_program, false), // Token program (readonly, non-signer)
|
||||
],
|
||||
data: vec![1],
|
||||
}
|
||||
})
|
||||
// Only use seed if the mint address is not wSOL or SOL
|
||||
// token 2022 测试不成功(TODO)
|
||||
if use_seed
|
||||
&& !mint.eq(&crate::constants::WSOL_TOKEN_ACCOUNT)
|
||||
&& !mint.eq(&crate::constants::SOL_TOKEN_ACCOUNT)
|
||||
&& token_program.eq(&spl_token::ID)
|
||||
{
|
||||
// Use cache to get instruction
|
||||
get_cached_instructions(cache_key, || {
|
||||
super::seed::create_associated_token_account_use_seed(payer, owner, mint, token_program)
|
||||
.unwrap()
|
||||
})
|
||||
} else {
|
||||
// Use cache to get instruction
|
||||
get_cached_instructions(cache_key, || {
|
||||
// Get Associated Token Address using cache
|
||||
let associated_token_address =
|
||||
get_associated_token_address_with_program_id_fast(owner, mint, token_program);
|
||||
// Create Associated Token Account instruction
|
||||
// Reference implementation of spl_associated_token_account::instruction::create_associated_token_account
|
||||
vec![Instruction {
|
||||
program_id: ASSOCIATED_TOKEN_PROGRAM_ID,
|
||||
accounts: vec![
|
||||
AccountMeta::new(*payer, true), // Payer (signer, writable)
|
||||
AccountMeta::new(associated_token_address, false), // ATA address (writable, non-signer)
|
||||
AccountMeta::new_readonly(*owner, false), // Token account owner (readonly, non-signer)
|
||||
AccountMeta::new_readonly(*mint, false), // Token mint address (readonly, non-signer)
|
||||
crate::constants::SYSTEM_PROGRAM_META,
|
||||
AccountMeta::new_readonly(*token_program, false), // Token program (readonly, non-signer)
|
||||
],
|
||||
data: vec![1],
|
||||
}]
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// --------------------- PDA ---------------------
|
||||
@@ -150,22 +185,52 @@ struct AtaCacheKey {
|
||||
wallet_address: Pubkey,
|
||||
token_mint_address: Pubkey,
|
||||
token_program_id: Pubkey,
|
||||
use_seed: bool,
|
||||
}
|
||||
|
||||
/// Global ATA cache for storing Associated Token Address computation results
|
||||
static ATA_CACHE: Lazy<RwLock<CLruCache<AtaCacheKey, Pubkey>>> =
|
||||
Lazy::new(|| RwLock::new(CLruCache::new(NonZeroUsize::new(MAX_ATA_CACHE_SIZE).unwrap())));
|
||||
|
||||
pub fn get_associated_token_address_with_program_id_fast_use_seed(
|
||||
wallet_address: &Pubkey,
|
||||
token_mint_address: &Pubkey,
|
||||
token_program_id: &Pubkey,
|
||||
use_seed: bool,
|
||||
) -> Pubkey {
|
||||
_get_associated_token_address_with_program_id_fast(
|
||||
wallet_address,
|
||||
token_mint_address,
|
||||
token_program_id,
|
||||
use_seed,
|
||||
)
|
||||
}
|
||||
|
||||
/// Get cached Associated Token Address, compute and cache if not exists
|
||||
pub fn get_associated_token_address_with_program_id_fast(
|
||||
wallet_address: &Pubkey,
|
||||
token_mint_address: &Pubkey,
|
||||
token_program_id: &Pubkey,
|
||||
) -> Pubkey {
|
||||
_get_associated_token_address_with_program_id_fast(
|
||||
wallet_address,
|
||||
token_mint_address,
|
||||
token_program_id,
|
||||
false,
|
||||
)
|
||||
}
|
||||
|
||||
fn _get_associated_token_address_with_program_id_fast(
|
||||
wallet_address: &Pubkey,
|
||||
token_mint_address: &Pubkey,
|
||||
token_program_id: &Pubkey,
|
||||
use_seed: bool,
|
||||
) -> Pubkey {
|
||||
let cache_key = AtaCacheKey {
|
||||
wallet_address: *wallet_address,
|
||||
token_mint_address: *token_mint_address,
|
||||
token_program_id: *token_program_id,
|
||||
use_seed,
|
||||
};
|
||||
|
||||
// Try to get from cache (using read lock)
|
||||
@@ -177,11 +242,26 @@ pub fn get_associated_token_address_with_program_id_fast(
|
||||
}
|
||||
|
||||
// Cache miss, compute new ATA
|
||||
let ata = get_associated_token_address_with_program_id(
|
||||
wallet_address,
|
||||
token_mint_address,
|
||||
token_program_id,
|
||||
);
|
||||
// Only use seed if the token mint address is not wSOL or SOL
|
||||
// token 2022 测试不成功(TODO)
|
||||
let ata = if use_seed
|
||||
&& !token_mint_address.eq(&crate::constants::WSOL_TOKEN_ACCOUNT)
|
||||
&& !token_mint_address.eq(&crate::constants::SOL_TOKEN_ACCOUNT)
|
||||
&& token_program_id.eq(&spl_token::ID)
|
||||
{
|
||||
super::seed::get_associated_token_address_with_program_id_use_seed(
|
||||
wallet_address,
|
||||
token_mint_address,
|
||||
token_program_id,
|
||||
)
|
||||
.unwrap()
|
||||
} else {
|
||||
get_associated_token_address_with_program_id(
|
||||
wallet_address,
|
||||
token_mint_address,
|
||||
token_program_id,
|
||||
)
|
||||
};
|
||||
|
||||
// Store computation result in cache (using write lock)
|
||||
{
|
||||
@@ -206,20 +286,20 @@ pub fn fast_init(payer: &Pubkey) {
|
||||
&crate::constants::TOKEN_PROGRAM,
|
||||
);
|
||||
// Get Close wSOL Account instruction
|
||||
get_cached_instruction(
|
||||
get_cached_instructions(
|
||||
crate::common::fast_fn::InstructionCacheKey::CloseWsolAccount {
|
||||
payer: *payer,
|
||||
wsol_token_account,
|
||||
},
|
||||
|| {
|
||||
spl_token::instruction::close_account(
|
||||
vec![spl_token::instruction::close_account(
|
||||
&crate::constants::TOKEN_PROGRAM,
|
||||
&wsol_token_account,
|
||||
&payer,
|
||||
&payer,
|
||||
&[],
|
||||
)
|
||||
.unwrap()
|
||||
.unwrap()]
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ pub mod bonding_curve;
|
||||
pub mod fast_fn;
|
||||
pub mod global;
|
||||
pub mod nonce_cache;
|
||||
pub mod seed;
|
||||
pub mod subscription_handle;
|
||||
pub mod types;
|
||||
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
use crate::common::SolanaRpcClient;
|
||||
use anyhow::anyhow;
|
||||
use fnv::FnvHasher;
|
||||
use solana_sdk::{instruction::Instruction, program_pack::Pack, pubkey::Pubkey};
|
||||
use solana_system_interface::instruction::create_account_with_seed;
|
||||
use std::hash::Hasher;
|
||||
use std::sync::Arc;
|
||||
use tokio::time::{sleep, Duration};
|
||||
|
||||
// Global rent values for token accounts
|
||||
pub static mut SPL_TOKEN_RENT: Option<u64> = None;
|
||||
pub static mut SPL_TOKEN_2022_RENT: Option<u64> = None;
|
||||
|
||||
pub async fn update_rents(client: &SolanaRpcClient) -> Result<(), anyhow::Error> {
|
||||
let rent = fetch_rent_for_token_account(client, false).await?;
|
||||
unsafe {
|
||||
SPL_TOKEN_RENT = Some(rent);
|
||||
}
|
||||
let rent = fetch_rent_for_token_account(client, true).await?;
|
||||
unsafe {
|
||||
SPL_TOKEN_2022_RENT = Some(rent);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn start_rent_updater(client: Arc<SolanaRpcClient>) {
|
||||
tokio::spawn(async move {
|
||||
loop {
|
||||
if let Err(_e) = update_rents(&client).await {}
|
||||
sleep(Duration::from_secs(60 * 60)).await;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async fn fetch_rent_for_token_account(
|
||||
client: &SolanaRpcClient,
|
||||
is_2022_token: bool,
|
||||
) -> Result<u64, anyhow::Error> {
|
||||
Ok(client
|
||||
.get_minimum_balance_for_rent_exemption(if is_2022_token {
|
||||
spl_token_2022::state::Account::LEN as usize
|
||||
} else {
|
||||
spl_token::state::Account::LEN as usize
|
||||
})
|
||||
.await?)
|
||||
}
|
||||
|
||||
pub fn create_associated_token_account_use_seed(
|
||||
payer: &Pubkey,
|
||||
owner: &Pubkey,
|
||||
mint: &Pubkey,
|
||||
token_program: &Pubkey,
|
||||
) -> Result<Vec<Instruction>, anyhow::Error> {
|
||||
let is_2022_token = token_program == &spl_token_2022::id();
|
||||
let rent =
|
||||
if is_2022_token { unsafe { SPL_TOKEN_2022_RENT } } else { unsafe { SPL_TOKEN_RENT } };
|
||||
if rent.is_none() {
|
||||
return Err(anyhow!("Rent is required when using seed"));
|
||||
}
|
||||
let mut buf = [0u8; 8];
|
||||
let mut hasher = FnvHasher::default();
|
||||
hasher.write(mint.as_ref());
|
||||
let hash = hasher.finish();
|
||||
let v = (hash & 0xFFFF_FFFF) as u32;
|
||||
for i in 0..8 {
|
||||
let nibble = ((v >> (28 - i * 4)) & 0xF) as u8;
|
||||
buf[i] = match nibble {
|
||||
0..=9 => b'0' + nibble,
|
||||
_ => b'a' + (nibble - 10),
|
||||
};
|
||||
}
|
||||
let seed = unsafe { std::str::from_utf8_unchecked(&buf) };
|
||||
let ata_like = Pubkey::create_with_seed(payer, seed, token_program)?;
|
||||
|
||||
let len = if is_2022_token {
|
||||
spl_token_2022::state::Account::LEN as u64
|
||||
} else {
|
||||
spl_token::state::Account::LEN as u64
|
||||
};
|
||||
let create_acc =
|
||||
create_account_with_seed(payer, &ata_like, owner, seed, rent.unwrap(), len, token_program);
|
||||
|
||||
let init_acc = if is_2022_token {
|
||||
spl_token_2022::instruction::initialize_account3(&token_program, &ata_like, mint, owner)?
|
||||
} else {
|
||||
spl_token::instruction::initialize_account3(&token_program, &ata_like, mint, owner)?
|
||||
};
|
||||
|
||||
Ok(vec![create_acc, init_acc])
|
||||
}
|
||||
|
||||
pub fn get_associated_token_address_with_program_id_use_seed(
|
||||
wallet_address: &Pubkey,
|
||||
token_mint_address: &Pubkey,
|
||||
token_program_id: &Pubkey,
|
||||
) -> Result<Pubkey, anyhow::Error> {
|
||||
let mut buf = [0u8; 8];
|
||||
let mut hasher = FnvHasher::default();
|
||||
hasher.write(token_mint_address.as_ref());
|
||||
let hash = hasher.finish();
|
||||
let v = (hash & 0xFFFF_FFFF) as u32;
|
||||
for i in 0..8 {
|
||||
let nibble = ((v >> (28 - i * 4)) & 0xF) as u8;
|
||||
buf[i] = match nibble {
|
||||
0..=9 => b'0' + nibble,
|
||||
_ => b'a' + (nibble - 10),
|
||||
};
|
||||
}
|
||||
let is_2022_token = token_program_id == &spl_token_2022::id();
|
||||
let seed = unsafe { std::str::from_utf8_unchecked(&buf) };
|
||||
let token_program = if is_2022_token { &spl_token_2022::id() } else { &spl_token::id() };
|
||||
let ata_like = Pubkey::create_with_seed(wallet_address, seed, token_program)?;
|
||||
Ok(ata_like)
|
||||
}
|
||||
+2
-4
@@ -9,7 +9,7 @@ use crate::{
|
||||
};
|
||||
use serde::Deserialize;
|
||||
use solana_client::rpc_client::RpcClient;
|
||||
use solana_sdk::{commitment_config::CommitmentConfig, pubkey::Pubkey, signature::Keypair};
|
||||
use solana_sdk::{commitment_config::CommitmentConfig, signature::Keypair};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct TradeConfig {
|
||||
@@ -17,7 +17,6 @@ pub struct TradeConfig {
|
||||
pub swqos_configs: Vec<SwqosConfig>,
|
||||
pub priority_fee: PriorityFee,
|
||||
pub commitment: CommitmentConfig,
|
||||
pub lookup_table_key: Option<Pubkey>,
|
||||
}
|
||||
|
||||
impl TradeConfig {
|
||||
@@ -26,9 +25,8 @@ impl TradeConfig {
|
||||
swqos_configs: Vec<SwqosConfig>,
|
||||
priority_fee: PriorityFee,
|
||||
commitment: CommitmentConfig,
|
||||
lookup_table_key: Option<Pubkey>,
|
||||
) -> Self {
|
||||
Self { rpc_url, swqos_configs, priority_fee, commitment, lookup_table_key }
|
||||
Self { rpc_url, swqos_configs, priority_fee, commitment }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user