Skip to main content

solana_pipkit/
transaction.rs

1//! Transaction batching and building utilities.
2//!
3//! This module provides utilities for building, batching, and executing
4//! Solana transactions efficiently with automatic size management.
5
6use solana_client::nonblocking::rpc_client::RpcClient;
7use solana_sdk::{
8    commitment_config::CommitmentConfig,
9    compute_budget::ComputeBudgetInstruction,
10    hash::Hash,
11    instruction::Instruction,
12    message::Message,
13    pubkey::Pubkey,
14    signature::{Keypair, Signature, Signer},
15    transaction::Transaction,
16};
17
18use crate::{Result, ToolkitError};
19
20/// Maximum transaction size in bytes (1232 bytes for legacy transactions).
21pub const MAX_TRANSACTION_SIZE: usize = 1232;
22
23/// Maximum number of accounts per transaction (64 for legacy).
24pub const MAX_ACCOUNTS_PER_TX: usize = 64;
25
26/// Default compute units per transaction.
27pub const DEFAULT_COMPUTE_UNITS: u32 = 200_000;
28
29/// Configuration for transaction execution.
30#[derive(Debug, Clone)]
31pub struct TransactionConfig {
32    /// Compute unit limit for the transaction.
33    pub compute_units: Option<u32>,
34    /// Priority fee in micro-lamports per compute unit.
35    pub priority_fee_micro_lamports: Option<u64>,
36    /// Whether to simulate before sending.
37    pub simulate_before_send: bool,
38    /// Whether to skip preflight checks.
39    pub skip_preflight: bool,
40    /// Number of retry attempts on failure.
41    pub max_retries: u8,
42    /// Commitment level for confirmation.
43    pub commitment: CommitmentConfig,
44}
45
46impl Default for TransactionConfig {
47    fn default() -> Self {
48        Self {
49            compute_units: None,
50            priority_fee_micro_lamports: None,
51            simulate_before_send: true,
52            skip_preflight: false,
53            max_retries: 3,
54            commitment: CommitmentConfig::confirmed(),
55        }
56    }
57}
58
59impl TransactionConfig {
60    /// Create a config optimized for speed (skip simulation, preflight).
61    pub fn fast() -> Self {
62        Self {
63            simulate_before_send: false,
64            skip_preflight: true,
65            max_retries: 1,
66            ..Default::default()
67        }
68    }
69
70    /// Create a config optimized for reliability.
71    pub fn reliable() -> Self {
72        Self {
73            simulate_before_send: true,
74            skip_preflight: false,
75            max_retries: 5,
76            commitment: CommitmentConfig::finalized(),
77            ..Default::default()
78        }
79    }
80
81    /// Set compute units.
82    pub fn with_compute_units(mut self, units: u32) -> Self {
83        self.compute_units = Some(units);
84        self
85    }
86
87    /// Set priority fee in micro-lamports.
88    pub fn with_priority_fee(mut self, micro_lamports: u64) -> Self {
89        self.priority_fee_micro_lamports = Some(micro_lamports);
90        self
91    }
92}
93
94/// Result of a batch transaction execution.
95#[derive(Debug, Clone)]
96pub struct BatchResult {
97    /// Successful transaction signatures.
98    pub successful: Vec<Signature>,
99    /// Failed transactions with their errors.
100    pub failed: Vec<(usize, String)>,
101    /// Total instructions processed.
102    pub instructions_processed: usize,
103}
104
105impl BatchResult {
106    /// Check if all transactions succeeded.
107    pub fn all_succeeded(&self) -> bool {
108        self.failed.is_empty()
109    }
110
111    /// Get success rate as a percentage.
112    pub fn success_rate(&self) -> f64 {
113        let total = self.successful.len() + self.failed.len();
114        if total == 0 {
115            100.0
116        } else {
117            (self.successful.len() as f64 / total as f64) * 100.0
118        }
119    }
120}
121
122/// Transaction builder for constructing complex transactions.
123#[derive(Default)]
124pub struct TransactionBuilder {
125    instructions: Vec<Instruction>,
126    signers: Vec<Pubkey>,
127    config: TransactionConfig,
128}
129
130impl TransactionBuilder {
131    /// Create a new transaction builder.
132    pub fn new() -> Self {
133        Self::default()
134    }
135
136    /// Create a builder with custom config.
137    pub fn with_config(config: TransactionConfig) -> Self {
138        Self {
139            config,
140            ..Default::default()
141        }
142    }
143
144    /// Add an instruction to the transaction.
145    pub fn add_instruction(mut self, instruction: Instruction) -> Self {
146        self.instructions.push(instruction);
147        self
148    }
149
150    /// Add multiple instructions.
151    pub fn add_instructions(mut self, instructions: Vec<Instruction>) -> Self {
152        self.instructions.extend(instructions);
153        self
154    }
155
156    /// Add a signer pubkey (for account tracking).
157    pub fn add_signer(mut self, signer: Pubkey) -> Self {
158        if !self.signers.contains(&signer) {
159            self.signers.push(signer);
160        }
161        self
162    }
163
164    /// Set compute units for this transaction.
165    pub fn compute_units(mut self, units: u32) -> Self {
166        self.config.compute_units = Some(units);
167        self
168    }
169
170    /// Set priority fee for this transaction.
171    pub fn priority_fee(mut self, micro_lamports: u64) -> Self {
172        self.config.priority_fee_micro_lamports = Some(micro_lamports);
173        self
174    }
175
176    /// Get the number of instructions currently in the builder.
177    pub fn instruction_count(&self) -> usize {
178        self.instructions.len()
179    }
180
181    /// Estimate the number of unique accounts in the transaction.
182    pub fn estimate_accounts(&self) -> usize {
183        let mut accounts = std::collections::HashSet::new();
184        for ix in &self.instructions {
185            accounts.insert(ix.program_id);
186            for meta in &ix.accounts {
187                accounts.insert(meta.pubkey);
188            }
189        }
190        accounts.len()
191    }
192
193    /// Check if adding more instructions might exceed transaction limits.
194    pub fn might_exceed_limits(&self) -> bool {
195        self.estimate_accounts() >= MAX_ACCOUNTS_PER_TX - 5
196    }
197
198    /// Build the final instructions with compute budget if configured.
199    pub fn build_instructions(self) -> Vec<Instruction> {
200        let mut instructions = Vec::new();
201
202        // Add compute budget instructions if configured
203        if let Some(units) = self.config.compute_units {
204            instructions.push(ComputeBudgetInstruction::set_compute_unit_limit(units));
205        }
206
207        if let Some(fee) = self.config.priority_fee_micro_lamports {
208            instructions.push(ComputeBudgetInstruction::set_compute_unit_price(fee));
209        }
210
211        instructions.extend(self.instructions);
212        instructions
213    }
214
215    /// Build a transaction ready for signing.
216    pub fn build(self, payer: &Pubkey, _recent_blockhash: Hash) -> Transaction {
217        let instructions = self.build_instructions();
218        let message = Message::new(&instructions, Some(payer));
219        Transaction::new_unsigned(message)
220    }
221}
222
223/// Batch executor for processing multiple transactions.
224pub struct BatchExecutor {
225    client: RpcClient,
226    config: TransactionConfig,
227}
228
229impl BatchExecutor {
230    /// Create a new batch executor.
231    pub fn new(rpc_url: &str) -> Self {
232        Self {
233            client: RpcClient::new_with_commitment(
234                rpc_url.to_string(),
235                CommitmentConfig::confirmed(),
236            ),
237            config: TransactionConfig::default(),
238        }
239    }
240
241    /// Create with custom configuration.
242    pub fn with_config(rpc_url: &str, config: TransactionConfig) -> Self {
243        Self {
244            client: RpcClient::new_with_commitment(rpc_url.to_string(), config.commitment),
245            config,
246        }
247    }
248
249    /// Execute a single transaction with the configured settings.
250    pub async fn execute_transaction(
251        &self,
252        instructions: Vec<Instruction>,
253        signers: &[&Keypair],
254    ) -> Result<Signature> {
255        if signers.is_empty() {
256            return Err(ToolkitError::SigningError("No signers provided".to_string()));
257        }
258
259        let payer = signers[0];
260        let mut all_instructions = Vec::new();
261
262        // Add compute budget instructions if configured
263        if let Some(units) = self.config.compute_units {
264            all_instructions.push(ComputeBudgetInstruction::set_compute_unit_limit(units));
265        }
266
267        if let Some(fee) = self.config.priority_fee_micro_lamports {
268            all_instructions.push(ComputeBudgetInstruction::set_compute_unit_price(fee));
269        }
270
271        all_instructions.extend(instructions);
272
273        let recent_blockhash = self.client.get_latest_blockhash().await?;
274        let message = Message::new(&all_instructions, Some(&payer.pubkey()));
275        let transaction = Transaction::new(signers, message, recent_blockhash);
276
277        // Simulate if configured
278        if self.config.simulate_before_send {
279            let sim_result = self.client.simulate_transaction(&transaction).await?;
280            if let Some(err) = sim_result.value.err {
281                return Err(ToolkitError::TransactionError(format!(
282                    "Simulation failed: {:?}",
283                    err
284                )));
285            }
286        }
287
288        // Send with retries
289        let mut last_error = None;
290        for attempt in 0..=self.config.max_retries {
291            match self.client.send_and_confirm_transaction(&transaction).await {
292                Ok(sig) => return Ok(sig),
293                Err(e) => {
294                    last_error = Some(e);
295                    if attempt < self.config.max_retries {
296                        tokio::time::sleep(tokio::time::Duration::from_millis(500)).await;
297                    }
298                }
299            }
300        }
301
302        Err(ToolkitError::TransactionError(format!(
303            "Failed after {} retries: {:?}",
304            self.config.max_retries,
305            last_error
306        )))
307    }
308
309    /// Split instructions into batches based on account limits.
310    pub fn split_into_batches(&self, instructions: Vec<Instruction>, max_per_batch: usize) -> Vec<Vec<Instruction>> {
311        let effective_max = max_per_batch.min(MAX_ACCOUNTS_PER_TX / 4); // Conservative estimate
312        instructions.chunks(effective_max).map(|c| c.to_vec()).collect()
313    }
314
315    /// Execute multiple instruction batches sequentially.
316    pub async fn execute_batches(
317        &self,
318        instruction_batches: Vec<Vec<Instruction>>,
319        signers: &[&Keypair],
320    ) -> Result<BatchResult> {
321        let mut result = BatchResult {
322            successful: Vec::new(),
323            failed: Vec::new(),
324            instructions_processed: 0,
325        };
326
327        for (batch_idx, instructions) in instruction_batches.into_iter().enumerate() {
328            let ix_count = instructions.len();
329            match self.execute_transaction(instructions, signers).await {
330                Ok(sig) => {
331                    result.successful.push(sig);
332                    result.instructions_processed += ix_count;
333                }
334                Err(e) => {
335                    result.failed.push((batch_idx, e.to_string()));
336                }
337            }
338        }
339
340        Ok(result)
341    }
342
343    /// Execute all instructions, automatically batching as needed.
344    pub async fn execute_all(
345        &self,
346        instructions: Vec<Instruction>,
347        signers: &[&Keypair],
348        max_per_batch: usize,
349    ) -> Result<BatchResult> {
350        let batches = self.split_into_batches(instructions, max_per_batch);
351        self.execute_batches(batches, signers).await
352    }
353}
354
355/// Parallel batch executor for concurrent transaction processing.
356pub struct ParallelBatchExecutor {
357    client: RpcClient,
358    config: TransactionConfig,
359    max_concurrent: usize,
360}
361
362impl ParallelBatchExecutor {
363    /// Create a new parallel batch executor.
364    pub fn new(rpc_url: &str, max_concurrent: usize) -> Self {
365        Self {
366            client: RpcClient::new_with_commitment(
367                rpc_url.to_string(),
368                CommitmentConfig::confirmed(),
369            ),
370            config: TransactionConfig::default(),
371            max_concurrent,
372        }
373    }
374
375    /// Create with custom configuration.
376    pub fn with_config(rpc_url: &str, config: TransactionConfig, max_concurrent: usize) -> Self {
377        Self {
378            client: RpcClient::new_with_commitment(rpc_url.to_string(), config.commitment),
379            config,
380            max_concurrent,
381        }
382    }
383
384    /// Execute multiple independent transactions in parallel.
385    pub async fn execute_parallel(
386        &self,
387        transaction_instructions: Vec<Vec<Instruction>>,
388        signers: &[&Keypair],
389    ) -> Result<BatchResult> {
390        use futures::stream::{self, StreamExt};
391
392        if signers.is_empty() {
393            return Err(ToolkitError::SigningError("No signers provided".to_string()));
394        }
395
396        let payer = signers[0];
397        let recent_blockhash = self.client.get_latest_blockhash().await?;
398
399        let transactions: Vec<_> = transaction_instructions
400            .iter()
401            .map(|instructions| {
402                let mut all_instructions = Vec::new();
403
404                if let Some(units) = self.config.compute_units {
405                    all_instructions.push(ComputeBudgetInstruction::set_compute_unit_limit(units));
406                }
407
408                if let Some(fee) = self.config.priority_fee_micro_lamports {
409                    all_instructions.push(ComputeBudgetInstruction::set_compute_unit_price(fee));
410                }
411
412                all_instructions.extend(instructions.clone());
413
414                let message = Message::new(&all_instructions, Some(&payer.pubkey()));
415                Transaction::new(signers, message, recent_blockhash)
416            })
417            .collect();
418
419        let results: Vec<_> = stream::iter(transactions.into_iter().enumerate())
420            .map(|(idx, tx)| {
421                let client = &self.client;
422                async move {
423                    match client.send_and_confirm_transaction(&tx).await {
424                        Ok(sig) => (idx, Ok(sig)),
425                        Err(e) => (idx, Err(e.to_string())),
426                    }
427                }
428            })
429            .buffer_unordered(self.max_concurrent)
430            .collect()
431            .await;
432
433        let mut batch_result = BatchResult {
434            successful: Vec::new(),
435            failed: Vec::new(),
436            instructions_processed: 0,
437        };
438
439        for (idx, result) in results {
440            let idx: usize = idx;
441            match result {
442                Ok(sig) => {
443                    batch_result.successful.push(sig);
444                    batch_result.instructions_processed += transaction_instructions[idx].len();
445                }
446                Err(e) => {
447                    batch_result.failed.push((idx, e));
448                }
449            }
450        }
451
452        Ok(batch_result)
453    }
454}
455
456/// Estimate transaction size for a set of instructions.
457pub fn estimate_transaction_size(instructions: &[Instruction], num_signers: usize) -> usize {
458    let mut size = 0;
459
460    // Signature size (64 bytes per signer)
461    size += num_signers * 64;
462
463    // Message header (3 bytes)
464    size += 3;
465
466    // Account keys
467    let mut accounts = std::collections::HashSet::new();
468    for ix in instructions {
469        accounts.insert(ix.program_id);
470        for meta in &ix.accounts {
471            accounts.insert(meta.pubkey);
472        }
473    }
474    size += accounts.len() * 32;
475
476    // Recent blockhash
477    size += 32;
478
479    // Instruction count (compact-u16)
480    size += 1;
481
482    // Instructions
483    for ix in instructions {
484        size += 1; // Program ID index
485        size += 1; // Account indices length
486        size += ix.accounts.len(); // Account indices
487        size += 2; // Data length (compact-u16)
488        size += ix.data.len(); // Data
489    }
490
491    size
492}
493
494/// Check if a set of instructions will fit in a single transaction.
495pub fn will_fit_in_transaction(instructions: &[Instruction], num_signers: usize) -> bool {
496    estimate_transaction_size(instructions, num_signers) <= MAX_TRANSACTION_SIZE
497}
498
499#[cfg(test)]
500mod tests {
501    use super::*;
502    use solana_sdk::system_instruction;
503
504    #[test]
505    fn test_transaction_config_default() {
506        let config = TransactionConfig::default();
507        assert!(config.simulate_before_send);
508        assert!(!config.skip_preflight);
509        assert_eq!(config.max_retries, 3);
510    }
511
512    #[test]
513    fn test_transaction_config_fast() {
514        let config = TransactionConfig::fast();
515        assert!(!config.simulate_before_send);
516        assert!(config.skip_preflight);
517    }
518
519    #[test]
520    fn test_transaction_builder() {
521        let payer = Pubkey::new_unique();
522        let to = Pubkey::new_unique();
523
524        let builder = TransactionBuilder::new()
525            .add_instruction(system_instruction::transfer(&payer, &to, 1000))
526            .compute_units(100_000)
527            .priority_fee(1000);
528
529        assert_eq!(builder.instruction_count(), 1);
530    }
531
532    #[test]
533    fn test_batch_result() {
534        let result = BatchResult {
535            successful: vec![Signature::default()],
536            failed: vec![],
537            instructions_processed: 5,
538        };
539
540        assert!(result.all_succeeded());
541        assert_eq!(result.success_rate(), 100.0);
542    }
543
544    #[test]
545    fn test_estimate_transaction_size() {
546        let from = Pubkey::new_unique();
547        let to = Pubkey::new_unique();
548        let instructions = vec![system_instruction::transfer(&from, &to, 1000)];
549
550        let size = estimate_transaction_size(&instructions, 1);
551        assert!(size > 0);
552        assert!(size < MAX_TRANSACTION_SIZE);
553    }
554}