Skip to main content

solana_pipkit/
simulation.rs

1//! Transaction simulation for previewing outcomes before execution.
2//!
3//! Simulates transactions to detect potential issues, unexpected balance changes,
4//! and preview swap outcomes before committing to the chain.
5
6use crate::{Result, ToolkitError};
7use solana_client::rpc_client::RpcClient;
8use solana_client::rpc_config::{RpcSimulateTransactionConfig, RpcSimulateTransactionAccountsConfig};
9use solana_sdk::{
10    commitment_config::CommitmentConfig,
11    pubkey::Pubkey,
12    transaction::Transaction,
13};
14use solana_account_decoder::UiAccountEncoding;
15use solana_transaction_status::UiTransactionEncoding;
16use std::collections::HashMap;
17
18/// Result of a transaction simulation.
19#[derive(Debug, Clone)]
20pub struct SimulationResult {
21    /// Whether the simulation succeeded.
22    pub success: bool,
23    /// Program logs from simulation.
24    pub logs: Vec<String>,
25    /// Compute units consumed.
26    pub units_consumed: u64,
27    /// SOL balance changes.
28    pub balance_changes: Vec<BalanceChange>,
29    /// Token balance changes.
30    pub token_balance_changes: Vec<TokenBalanceChange>,
31    /// Error message if simulation failed.
32    pub error: Option<String>,
33}
34
35/// SOL balance change for an account.
36#[derive(Debug, Clone)]
37pub struct BalanceChange {
38    /// Account pubkey.
39    pub account: Pubkey,
40    /// Balance before transaction.
41    pub before: u64,
42    /// Balance after transaction.
43    pub after: u64,
44    /// Net change (can be negative).
45    pub delta: i64,
46}
47
48/// Token balance change for an account.
49#[derive(Debug, Clone)]
50pub struct TokenBalanceChange {
51    /// Token account pubkey.
52    pub account: Pubkey,
53    /// Token mint.
54    pub mint: Pubkey,
55    /// Balance before transaction.
56    pub before: u64,
57    /// Balance after transaction.
58    pub after: u64,
59    /// Net change (can be negative).
60    pub delta: i64,
61}
62
63/// Configuration for simulation validation.
64#[derive(Debug, Clone)]
65pub struct SimulationConfig {
66    /// Maximum acceptable SOL loss in lamports.
67    pub max_sol_loss: u64,
68    /// Maximum acceptable token loss percentage (0-100).
69    pub max_token_loss_percent: u8,
70    /// Fail if any unexpected account is modified.
71    pub strict_account_checks: bool,
72    /// Expected accounts to be modified.
73    pub expected_accounts: Vec<Pubkey>,
74}
75
76impl Default for SimulationConfig {
77    fn default() -> Self {
78        Self {
79            max_sol_loss: 10_000_000, // 0.01 SOL
80            max_token_loss_percent: 5,
81            strict_account_checks: false,
82            expected_accounts: Vec::new(),
83        }
84    }
85}
86
87impl SimulationConfig {
88    /// Create a new simulation config.
89    pub fn new() -> Self {
90        Self::default()
91    }
92
93    /// Set maximum SOL loss.
94    pub fn max_sol_loss(mut self, lamports: u64) -> Self {
95        self.max_sol_loss = lamports;
96        self
97    }
98
99    /// Set maximum token loss percentage.
100    pub fn max_token_loss_percent(mut self, percent: u8) -> Self {
101        self.max_token_loss_percent = percent.min(100);
102        self
103    }
104
105    /// Enable strict account checks.
106    pub fn strict(mut self) -> Self {
107        self.strict_account_checks = true;
108        self
109    }
110
111    /// Set expected accounts.
112    pub fn expected_accounts(mut self, accounts: Vec<Pubkey>) -> Self {
113        self.expected_accounts = accounts;
114        self
115    }
116}
117
118/// Preview of a swap transaction.
119#[derive(Debug, Clone)]
120pub struct SwapPreview {
121    /// Input token mint.
122    pub input_token: Pubkey,
123    /// Input amount.
124    pub input_amount: u64,
125    /// Output token mint.
126    pub output_token: Pubkey,
127    /// Output amount.
128    pub output_amount: u64,
129    /// Price impact in basis points.
130    pub price_impact_bps: u16,
131    /// Fees paid.
132    pub fees: u64,
133}
134
135/// Simulation safety report.
136#[derive(Debug, Clone)]
137pub struct SimulationSafetyReport {
138    /// Whether the simulation passed safety checks.
139    pub safe: bool,
140    /// Risk level.
141    pub risk_level: SimulationRiskLevel,
142    /// Warnings found.
143    pub warnings: Vec<String>,
144    /// Blockers that prevent approval.
145    pub blockers: Vec<String>,
146    /// The simulation result.
147    pub simulation: SimulationResult,
148}
149
150/// Risk level from simulation.
151#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
152pub enum SimulationRiskLevel {
153    /// No issues detected.
154    Safe,
155    /// Minor warnings.
156    Low,
157    /// Significant concerns.
158    Medium,
159    /// High risk, requires confirmation.
160    High,
161    /// Critical issues, should not proceed.
162    Critical,
163}
164
165impl std::fmt::Display for SimulationRiskLevel {
166    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
167        match self {
168            SimulationRiskLevel::Safe => write!(f, "SAFE"),
169            SimulationRiskLevel::Low => write!(f, "LOW"),
170            SimulationRiskLevel::Medium => write!(f, "MEDIUM"),
171            SimulationRiskLevel::High => write!(f, "HIGH"),
172            SimulationRiskLevel::Critical => write!(f, "CRITICAL"),
173        }
174    }
175}
176
177/// Transaction simulator.
178pub struct TransactionSimulator {
179    rpc_client: RpcClient,
180}
181
182impl TransactionSimulator {
183    /// Create a new transaction simulator.
184    pub fn new(rpc_url: &str) -> Self {
185        Self {
186            rpc_client: RpcClient::new_with_commitment(
187                rpc_url.to_string(),
188                CommitmentConfig::confirmed(),
189            ),
190        }
191    }
192
193    /// Create from existing RpcClient.
194    pub fn from_client(client: RpcClient) -> Self {
195        Self { rpc_client: client }
196    }
197
198    /// Simulate a transaction and return detailed results.
199    pub fn simulate(&self, transaction: &Transaction) -> Result<SimulationResult> {
200        // Get accounts involved in transaction
201        let accounts: Vec<Pubkey> = transaction
202            .message
203            .account_keys
204            .iter()
205            .cloned()
206            .collect();
207
208        // Fetch pre-balances
209        let pre_balances = self.fetch_balances(&accounts)?;
210
211        // Configure simulation
212        let config = RpcSimulateTransactionConfig {
213            sig_verify: false,
214            replace_recent_blockhash: true,
215            commitment: Some(CommitmentConfig::confirmed()),
216            encoding: Some(UiTransactionEncoding::Base64),
217            accounts: Some(RpcSimulateTransactionAccountsConfig {
218                encoding: Some(UiAccountEncoding::Base64),
219                addresses: accounts.iter().map(|p| p.to_string()).collect(),
220            }),
221            min_context_slot: None,
222            inner_instructions: false,
223        };
224
225        // Run simulation
226        let sim_result = self
227            .rpc_client
228            .simulate_transaction_with_config(transaction, config)
229            .map_err(|e| ToolkitError::TransactionError(format!("Simulation failed: {}", e)))?;
230
231        let value = sim_result.value;
232
233        // Extract logs
234        let logs = value.logs.unwrap_or_default();
235
236        // Extract error
237        let error = value.err.map(|e| format!("{:?}", e));
238        let success = error.is_none();
239
240        // Extract compute units
241        let units_consumed = value.units_consumed.unwrap_or(0);
242
243        // Calculate balance changes (simplified - actual implementation would parse post accounts)
244        let balance_changes = self.calculate_balance_changes(&accounts, &pre_balances)?;
245
246        Ok(SimulationResult {
247            success,
248            logs,
249            units_consumed,
250            balance_changes,
251            token_balance_changes: Vec::new(), // Would require parsing token accounts
252            error,
253        })
254    }
255
256    /// Simulate and validate against safety config.
257    pub fn simulate_and_validate(
258        &self,
259        transaction: &Transaction,
260        config: &SimulationConfig,
261    ) -> Result<SimulationSafetyReport> {
262        let simulation = self.simulate(transaction)?;
263
264        let mut warnings = Vec::new();
265        let mut blockers = Vec::new();
266        let mut risk_level = SimulationRiskLevel::Safe;
267
268        // Check if simulation failed
269        if !simulation.success {
270            blockers.push(format!(
271                "Simulation failed: {}",
272                simulation.error.as_deref().unwrap_or("Unknown error")
273            ));
274            risk_level = SimulationRiskLevel::Critical;
275        }
276
277        // Check SOL losses
278        for change in &simulation.balance_changes {
279            if change.delta < 0 {
280                let loss = (-change.delta) as u64;
281                if loss > config.max_sol_loss {
282                    blockers.push(format!(
283                        "Excessive SOL loss: {} lamports from {}",
284                        loss,
285                        change.account
286                    ));
287                    risk_level = SimulationRiskLevel::Critical;
288                } else if loss > config.max_sol_loss / 2 {
289                    warnings.push(format!(
290                        "Significant SOL loss: {} lamports from {}",
291                        loss,
292                        change.account
293                    ));
294                    if risk_level < SimulationRiskLevel::Medium {
295                        risk_level = SimulationRiskLevel::Medium;
296                    }
297                }
298            }
299        }
300
301        // Check for unexpected account modifications
302        if config.strict_account_checks && !config.expected_accounts.is_empty() {
303            for change in &simulation.balance_changes {
304                if change.delta != 0 && !config.expected_accounts.contains(&change.account) {
305                    warnings.push(format!(
306                        "Unexpected account modified: {}",
307                        change.account
308                    ));
309                    if risk_level < SimulationRiskLevel::High {
310                        risk_level = SimulationRiskLevel::High;
311                    }
312                }
313            }
314        }
315
316        // Check compute units (warn if high)
317        if simulation.units_consumed > 1_000_000 {
318            warnings.push(format!(
319                "High compute usage: {} units",
320                simulation.units_consumed
321            ));
322            if risk_level < SimulationRiskLevel::Low {
323                risk_level = SimulationRiskLevel::Low;
324            }
325        }
326
327        let safe = blockers.is_empty() && risk_level < SimulationRiskLevel::High;
328
329        Ok(SimulationSafetyReport {
330            safe,
331            risk_level,
332            warnings,
333            blockers,
334            simulation,
335        })
336    }
337
338    /// Preview a swap outcome.
339    pub fn preview_swap(&self, transaction: &Transaction) -> Result<SwapPreview> {
340        let simulation = self.simulate(transaction)?;
341
342        if !simulation.success {
343            return Err(ToolkitError::TransactionError(format!(
344                "Swap simulation failed: {}",
345                simulation.error.unwrap_or_else(|| "Unknown error".to_string())
346            )));
347        }
348
349        // Parse token balance changes to determine swap details
350        // This is a simplified implementation - real implementation would parse
351        // the actual token account changes from simulation
352
353        // For now, return a placeholder that would need to be filled from actual simulation data
354        Ok(SwapPreview {
355            input_token: Pubkey::default(),
356            input_amount: 0,
357            output_token: Pubkey::default(),
358            output_amount: 0,
359            price_impact_bps: 0,
360            fees: 0,
361        })
362    }
363
364    /// Fetch current balances for accounts.
365    fn fetch_balances(&self, accounts: &[Pubkey]) -> Result<HashMap<Pubkey, u64>> {
366        let mut balances = HashMap::new();
367
368        for account in accounts {
369            match self.rpc_client.get_balance(account) {
370                Ok(balance) => {
371                    balances.insert(*account, balance);
372                }
373                Err(_) => {
374                    balances.insert(*account, 0);
375                }
376            }
377        }
378
379        Ok(balances)
380    }
381
382    /// Calculate balance changes.
383    fn calculate_balance_changes(
384        &self,
385        accounts: &[Pubkey],
386        pre_balances: &HashMap<Pubkey, u64>,
387    ) -> Result<Vec<BalanceChange>> {
388        let mut changes = Vec::new();
389
390        for account in accounts {
391            let before = *pre_balances.get(account).unwrap_or(&0);
392            // Post-balance would come from simulation result
393            // For now, assume no change (actual implementation would parse simulation accounts)
394            let after = before;
395            let delta = after as i64 - before as i64;
396
397            if delta != 0 {
398                changes.push(BalanceChange {
399                    account: *account,
400                    before,
401                    after,
402                    delta,
403                });
404            }
405        }
406
407        Ok(changes)
408    }
409}
410
411#[cfg(test)]
412mod tests {
413    use super::*;
414
415    #[test]
416    fn test_simulation_config_defaults() {
417        let config = SimulationConfig::default();
418        assert_eq!(config.max_sol_loss, 10_000_000);
419        assert_eq!(config.max_token_loss_percent, 5);
420        assert!(!config.strict_account_checks);
421    }
422
423    #[test]
424    fn test_simulation_config_builder() {
425        let config = SimulationConfig::new()
426            .max_sol_loss(5_000_000)
427            .max_token_loss_percent(10)
428            .strict();
429
430        assert_eq!(config.max_sol_loss, 5_000_000);
431        assert_eq!(config.max_token_loss_percent, 10);
432        assert!(config.strict_account_checks);
433    }
434
435    #[test]
436    fn test_simulation_config_max_percent_capped() {
437        let config = SimulationConfig::new().max_token_loss_percent(150);
438        assert_eq!(config.max_token_loss_percent, 100);
439    }
440
441    #[test]
442    fn test_simulation_result_success() {
443        let result = SimulationResult {
444            success: true,
445            logs: vec!["Program log: Success".to_string()],
446            units_consumed: 50000,
447            balance_changes: vec![],
448            token_balance_changes: vec![],
449            error: None,
450        };
451
452        assert!(result.success);
453        assert!(result.error.is_none());
454    }
455
456    #[test]
457    fn test_simulation_result_failure() {
458        let result = SimulationResult {
459            success: false,
460            logs: vec!["Program log: Error".to_string()],
461            units_consumed: 10000,
462            balance_changes: vec![],
463            token_balance_changes: vec![],
464            error: Some("Insufficient funds".to_string()),
465        };
466
467        assert!(!result.success);
468        assert!(result.error.is_some());
469    }
470
471    #[test]
472    fn test_balance_change() {
473        let change = BalanceChange {
474            account: Pubkey::new_unique(),
475            before: 1_000_000_000,
476            after: 900_000_000,
477            delta: -100_000_000,
478        };
479
480        assert!(change.delta < 0);
481        assert_eq!(change.before - change.after, 100_000_000);
482    }
483
484    #[test]
485    fn test_simulation_risk_level_ordering() {
486        assert!(SimulationRiskLevel::Safe < SimulationRiskLevel::Low);
487        assert!(SimulationRiskLevel::Low < SimulationRiskLevel::Medium);
488        assert!(SimulationRiskLevel::Medium < SimulationRiskLevel::High);
489        assert!(SimulationRiskLevel::High < SimulationRiskLevel::Critical);
490    }
491
492    #[test]
493    fn test_simulation_safety_report_safe() {
494        let report = SimulationSafetyReport {
495            safe: true,
496            risk_level: SimulationRiskLevel::Safe,
497            warnings: vec![],
498            blockers: vec![],
499            simulation: SimulationResult {
500                success: true,
501                logs: vec![],
502                units_consumed: 50000,
503                balance_changes: vec![],
504                token_balance_changes: vec![],
505                error: None,
506            },
507        };
508
509        assert!(report.safe);
510        assert!(report.blockers.is_empty());
511    }
512
513    #[test]
514    fn test_simulation_safety_report_blocked() {
515        let report = SimulationSafetyReport {
516            safe: false,
517            risk_level: SimulationRiskLevel::Critical,
518            warnings: vec![],
519            blockers: vec!["Simulation failed".to_string()],
520            simulation: SimulationResult {
521                success: false,
522                logs: vec![],
523                units_consumed: 0,
524                balance_changes: vec![],
525                token_balance_changes: vec![],
526                error: Some("Error".to_string()),
527            },
528        };
529
530        assert!(!report.safe);
531        assert!(!report.blockers.is_empty());
532    }
533
534    #[test]
535    fn test_swap_preview() {
536        let preview = SwapPreview {
537            input_token: Pubkey::new_unique(),
538            input_amount: 1_000_000,
539            output_token: Pubkey::new_unique(),
540            output_amount: 950_000,
541            price_impact_bps: 50,
542            fees: 1000,
543        };
544
545        assert!(preview.output_amount < preview.input_amount);
546        assert_eq!(preview.price_impact_bps, 50);
547    }
548}