Skip to main content

TradingClient

Struct TradingClient 

Source
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: bool

Whether 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

Source

pub async fn get_sol_balance(&self, payer: &Pubkey) -> Result<u64, Error>

Source

pub async fn get_payer_sol_balance(&self) -> Result<u64, Error>

Source

pub async fn get_token_balance( &self, payer: &Pubkey, mint: &Pubkey, ) -> Result<u64, Error>

Source

pub async fn get_payer_token_balance(&self, mint: &Pubkey) -> Result<u64, Error>

Source

pub fn get_payer_pubkey(&self) -> Pubkey

Source

pub fn get_payer(&self) -> &Keypair

Source

pub async fn transfer_sol( &self, payer: &Keypair, receive_wallet: &Pubkey, amount: u64, ) -> Result<(), Error>

Source

pub async fn close_token_account(&self, mint: &Pubkey) -> Result<(), Error>

Source§

impl TradingClient

Source

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 transactions
  • infrastructure - 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

Source

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 transactions
  • infrastructure - Shared infrastructure (RPC client, SWQOS clients)
  • use_seed_optimize - Whether to use seed optimization for ATA operations
  • create_wsol_ata - Whether to check/create WSOL ATA
Source

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 transactions
  • trade_config - Trading configuration including RPC URL, SWQOS settings, etc.
§Returns

Returns a configured SolTradingSDK instance ready for trading operations

Source

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

Source

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

Source

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.

Source

pub async fn buy( &self, params: TradeBuyParams, ) -> Result<(bool, Vec<Signature>, Option<TradeError>), Error>

Execute a buy order for a specified token

🔧 修复:返回Vec支持多SWQOS并发交易

  • 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
Source

pub async fn sell( &self, params: TradeSellParams, ) -> Result<(bool, Vec<Signature>, Option<TradeError>), Error>

Execute a sell order for a specified token

🔧 修复:返回Vec支持多SWQOS并发交易

  • 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
Source

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:

  • percent is 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
Source

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 successful
  • Err(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
Source

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 successful
  • Err(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
Source

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 successful
  • Err(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
Source

pub async fn wrap_wsol_to_sol(&self, amount: u64) -> Result<String, Error>

将 WSOL 转换为 SOL,使用 seed 账户

这个函数实现以下步骤:

  1. 使用 super::seed::create_associated_token_account_use_seed 创建 WSOL seed 账号
  2. 使用 get_associated_token_address_with_program_id_use_seed 获取该账号的 ATA 地址
  3. 添加从用户 WSOL ATA 转账到该 seed ATA 账号的指令
  4. 添加关闭 WSOL seed 账号的指令
§Arguments
  • amount - 要转换的 WSOL 数量(以 lamports 为单位)
§Returns
  • Ok(String) - 交易签名
  • Err(anyhow::Error) - 如果交易执行失败
§Errors

此函数在以下情况下会返回错误:

  • 用户 WSOL ATA 中余额不足
  • seed 账户创建失败
  • 转账指令执行失败
  • 交易执行或确认失败
  • 网络或 RPC 错误

Trait Implementations§

Source§

impl Clone for TradingClient

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

Source§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

Source§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

Source§

fn implicit( self, class: Class, constructed: bool, tag: u32, ) -> TaggedParser<'a, Implicit, Self, E>

Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts 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 more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts 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
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more