pub struct TradingClient {
pub payer: Arc<Keypair>,
pub infrastructure: Arc<TradingInfrastructure>,
pub middleware_manager: Option<Arc<MiddlewareManager>>,
pub use_seed_optimize: bool,
}Expand description
Main trading client for Solana DeFi protocols
SolTradingSDK provides a unified interface for trading across multiple Solana DEXs
including PumpFun, PumpSwap, Bonk, Raydium AMM V4, and Raydium CPMM.
It manages RPC connections, transaction signing, and SWQOS (Solana Web Quality of Service) settings.
Fields§
§payer: Arc<Keypair>The keypair used for signing all transactions
infrastructure: Arc<TradingInfrastructure>Shared infrastructure (RPC client, SWQOS clients) Can be shared across multiple TradingClient instances with different wallets
middleware_manager: Option<Arc<MiddlewareManager>>Optional middleware manager for custom transaction processing
use_seed_optimize: boolWhether to use seed optimization for all ATA operations (default: true) Applies to all token account creations across buy and sell operations
Implementations§
Source§impl TradingClient
impl TradingClient
pub async fn get_sol_balance(&self, payer: &Pubkey) -> Result<u64, Error>
pub async fn get_payer_sol_balance(&self) -> Result<u64, Error>
pub async fn get_token_balance( &self, payer: &Pubkey, mint: &Pubkey, ) -> Result<u64, Error>
pub async fn get_payer_token_balance(&self, mint: &Pubkey) -> Result<u64, Error>
pub fn get_payer_pubkey(&self) -> Pubkey
pub fn get_payer(&self) -> &Keypair
pub async fn transfer_sol( &self, payer: &Keypair, receive_wallet: &Pubkey, amount: u64, ) -> Result<(), Error>
pub async fn close_token_account(&self, mint: &Pubkey) -> Result<(), Error>
Source§impl TradingClient
impl TradingClient
Sourcepub fn from_infrastructure(
payer: Arc<Keypair>,
infrastructure: Arc<TradingInfrastructure>,
use_seed_optimize: bool,
) -> Self
pub fn from_infrastructure( payer: Arc<Keypair>, infrastructure: Arc<TradingInfrastructure>, use_seed_optimize: bool, ) -> Self
Create a TradingClient from shared infrastructure (fast path)
This is the preferred method when multiple wallets share the same infrastructure. It only performs wallet-specific initialization (fast_init) without the expensive RPC/SWQOS client creation.
§Arguments
payer- The keypair used for signing transactionsinfrastructure- Shared infrastructure (RPC client, SWQOS clients)use_seed_optimize- Whether to use seed optimization for ATA operations
§Returns
Returns a configured TradingClient instance ready for trading operations
Sourcepub async fn from_infrastructure_with_wsol_setup(
payer: Arc<Keypair>,
infrastructure: Arc<TradingInfrastructure>,
use_seed_optimize: bool,
create_wsol_ata: bool,
) -> Self
pub async fn from_infrastructure_with_wsol_setup( payer: Arc<Keypair>, infrastructure: Arc<TradingInfrastructure>, use_seed_optimize: bool, create_wsol_ata: bool, ) -> Self
Create a TradingClient from shared infrastructure with optional WSOL ATA setup
Same as from_infrastructure but also handles WSOL ATA creation if requested.
§Arguments
payer- The keypair used for signing transactionsinfrastructure- Shared infrastructure (RPC client, SWQOS clients)use_seed_optimize- Whether to use seed optimization for ATA operationscreate_wsol_ata- Whether to check/create WSOL ATA
Sourcepub async fn new(payer: Arc<Keypair>, trade_config: TradeConfig) -> Self
pub async fn new(payer: Arc<Keypair>, trade_config: TradeConfig) -> Self
Creates a new SolTradingSDK instance with the specified configuration
This function initializes the trading system with RPC connection, SWQOS settings, and sets up necessary components for trading operations.
§Arguments
payer- The keypair used for signing transactionstrade_config- Trading configuration including RPC URL, SWQOS settings, etc.
§Returns
Returns a configured SolTradingSDK instance ready for trading operations
Sourcepub fn with_middleware_manager(
self,
middleware_manager: MiddlewareManager,
) -> Self
pub fn with_middleware_manager( self, middleware_manager: MiddlewareManager, ) -> Self
Adds a middleware manager to the SolanaTrade instance
Middleware managers can be used to implement custom logic that runs before or after trading operations, such as logging, monitoring, or custom validation.
§Arguments
middleware_manager- The middleware manager to attach
§Returns
Returns the modified SolanaTrade instance with middleware manager attached
Sourcepub fn get_rpc(&self) -> &Arc<SolanaRpcClient>
pub fn get_rpc(&self) -> &Arc<SolanaRpcClient>
Gets the RPC client instance for direct Solana blockchain interactions
This provides access to the underlying Solana RPC client that can be used for custom blockchain operations outside of the trading framework.
§Returns
Returns a reference to the Arc-wrapped SolanaRpcClient instance
Sourcepub fn get_instance() -> Arc<Self>
pub fn get_instance() -> Arc<Self>
Gets the current globally shared SolanaTrade instance
This provides access to the singleton instance that was created with new().
Useful for accessing the trading instance from different parts of the application.
§Returns
Returns the Arc-wrapped SolanaTrade instance
§Panics
Panics if no instance has been initialized yet. Make sure to call new() first.
Sourcepub async fn buy(
&self,
params: TradeBuyParams,
) -> Result<(bool, Vec<Signature>, Option<TradeError>), Error>
pub async fn buy( &self, params: TradeBuyParams, ) -> Result<(bool, Vec<Signature>, Option<TradeError>), Error>
Execute a buy order for a specified token
🔧 修复:返回Vec
- bool: 是否至少有一个交易成功
- Vec
: 所有提交的交易签名(按SWQOS顺序) - Option
: 最后一个错误(如果全部失败)
§Arguments
params- Buy trade parameters containing all necessary trading configuration
§Returns
Returns Ok((bool, Vec<Signature>, Option<TradeError>)) with success flag and all transaction signatures,
or an error if the transaction fails.
§Errors
This function will return an error if:
- Invalid protocol parameters are provided for the specified DEX type
- The transaction fails to execute
- Network or RPC errors occur
- Insufficient SOL balance for the purchase
- Required accounts cannot be created or accessed
Sourcepub async fn sell(
&self,
params: TradeSellParams,
) -> Result<(bool, Vec<Signature>, Option<TradeError>), Error>
pub async fn sell( &self, params: TradeSellParams, ) -> Result<(bool, Vec<Signature>, Option<TradeError>), Error>
Execute a sell order for a specified token
🔧 修复:返回Vec
- bool: 是否至少有一个交易成功
- Vec
: 所有提交的交易签名(按SWQOS顺序) - Option
: 最后一个错误(如果全部失败)
§Arguments
params- Sell trade parameters containing all necessary trading configuration
§Returns
Returns Ok((bool, Vec<Signature>, Option<TradeError>)) with success flag and all transaction signatures,
or an error if the transaction fails.
§Errors
This function will return an error if:
- Invalid protocol parameters are provided for the specified DEX type
- The transaction fails to execute
- Network or RPC errors occur
- Insufficient token balance for the sale
- Token account doesn’t exist or is not properly initialized
- Required accounts cannot be created or accessed
Sourcepub async fn sell_by_percent(
&self,
params: TradeSellParams,
amount_token: u64,
percent: u64,
) -> Result<(bool, Vec<Signature>, Option<TradeError>), Error>
pub async fn sell_by_percent( &self, params: TradeSellParams, amount_token: u64, percent: u64, ) -> Result<(bool, Vec<Signature>, Option<TradeError>), Error>
Execute a sell order for a percentage of the specified token amount
This is a convenience function that calculates the exact amount to sell based on
a percentage of the total token amount and then calls the sell function.
§Arguments
params- Sell trade parameters (will be modified with calculated token amount)amount_token- Total amount of tokens available (in smallest token units)percent- Percentage of tokens to sell (1-100, where 100 = 100%)
§Returns
Returns Ok(Signature) with the transaction signature if the sell order is successfully executed,
or an error if the transaction fails.
§Errors
This function will return an error if:
percentis 0 or greater than 100- Invalid protocol parameters are provided for the specified DEX type
- The transaction fails to execute
- Network or RPC errors occur
- Insufficient token balance for the calculated sale amount
- Token account doesn’t exist or is not properly initialized
- Required accounts cannot be created or accessed
Sourcepub async fn wrap_sol_to_wsol(&self, amount: u64) -> Result<String, Error>
pub async fn wrap_sol_to_wsol(&self, amount: u64) -> Result<String, Error>
Wraps native SOL into wSOL (Wrapped SOL) for use in SPL token operations
This function creates a wSOL associated token account (if it doesn’t exist), transfers the specified amount of SOL to that account, and then syncs the native token balance to make SOL usable as an SPL token in trading operations.
§Arguments
amount- The amount of SOL to wrap (in lamports)
§Returns
Ok(String)- Transaction signature if successfulErr(anyhow::Error)- If the transaction fails to execute
§Errors
This function will return an error if:
- Insufficient SOL balance for the wrap operation
- wSOL associated token account creation fails
- Transaction fails to execute or confirm
- Network or RPC errors occur
Sourcepub async fn close_wsol(&self) -> Result<String, Error>
pub async fn close_wsol(&self) -> Result<String, Error>
Closes the wSOL associated token account and unwraps remaining balance to native SOL
This function closes the wSOL associated token account, which automatically transfers any remaining wSOL balance back to the account owner as native SOL. This is useful for cleaning up wSOL accounts and recovering wrapped SOL after trading operations.
§Returns
Ok(String)- Transaction signature if successfulErr(anyhow::Error)- If the transaction fails to execute
§Errors
This function will return an error if:
- wSOL associated token account doesn’t exist
- Account closure fails due to insufficient permissions
- Transaction fails to execute or confirm
- Network or RPC errors occur
Sourcepub async fn create_wsol_ata(&self) -> Result<String, Error>
pub async fn create_wsol_ata(&self) -> Result<String, Error>
Creates a wSOL associated token account (ATA) without wrapping any SOL
This function only creates the wSOL associated token account for the payer without transferring any SOL into it. This is useful when you want to set up the account infrastructure in advance without committing funds yet.
§Returns
Ok(String)- Transaction signature if successfulErr(anyhow::Error)- If the transaction fails to execute
§Errors
This function will return an error if:
- wSOL ATA account already exists (idempotent, will succeed silently)
- Transaction fails to execute or confirm
- Network or RPC errors occur
- Insufficient SOL for transaction fees
Sourcepub async fn wrap_wsol_to_sol(&self, amount: u64) -> Result<String, Error>
pub async fn wrap_wsol_to_sol(&self, amount: u64) -> Result<String, Error>
将 WSOL 转换为 SOL,使用 seed 账户
这个函数实现以下步骤:
- 使用 super::seed::create_associated_token_account_use_seed 创建 WSOL seed 账号
- 使用 get_associated_token_address_with_program_id_use_seed 获取该账号的 ATA 地址
- 添加从用户 WSOL ATA 转账到该 seed ATA 账号的指令
- 添加关闭 WSOL seed 账号的指令
§Arguments
amount- 要转换的 WSOL 数量(以 lamports 为单位)
§Returns
Ok(String)- 交易签名Err(anyhow::Error)- 如果交易执行失败
§Errors
此函数在以下情况下会返回错误:
- 用户 WSOL ATA 中余额不足
- seed 账户创建失败
- 转账指令执行失败
- 交易执行或确认失败
- 网络或 RPC 错误
Trait Implementations§
Auto Trait Implementations§
impl Freeze for TradingClient
impl !RefUnwindSafe for TradingClient
impl Send for TradingClient
impl Sync for TradingClient
impl Unpin for TradingClient
impl !UnwindSafe for TradingClient
Blanket Implementations§
Source§impl<'a, T, E> AsTaggedExplicit<'a, E> for Twhere
T: 'a,
impl<'a, T, E> AsTaggedExplicit<'a, E> for Twhere
T: 'a,
Source§impl<'a, T, E> AsTaggedImplicit<'a, E> for Twhere
T: 'a,
impl<'a, T, E> AsTaggedImplicit<'a, E> for Twhere
T: 'a,
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
Source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read more