solana-pipkit 2.2.0

Pragmatic Rust utilities for Solana development - safety, speed, analytics, and DeFi
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
//! Transaction simulation for previewing outcomes before execution.
//!
//! Simulates transactions to detect potential issues, unexpected balance changes,
//! and preview swap outcomes before committing to the chain.

use crate::{Result, ToolkitError};
use solana_client::rpc_client::RpcClient;
use solana_client::rpc_config::{RpcSimulateTransactionConfig, RpcSimulateTransactionAccountsConfig};
use solana_sdk::{
    commitment_config::CommitmentConfig,
    pubkey::Pubkey,
    transaction::Transaction,
};
use solana_account_decoder::UiAccountEncoding;
use solana_transaction_status::UiTransactionEncoding;
use std::collections::HashMap;

/// Result of a transaction simulation.
#[derive(Debug, Clone)]
pub struct SimulationResult {
    /// Whether the simulation succeeded.
    pub success: bool,
    /// Program logs from simulation.
    pub logs: Vec<String>,
    /// Compute units consumed.
    pub units_consumed: u64,
    /// SOL balance changes.
    pub balance_changes: Vec<BalanceChange>,
    /// Token balance changes.
    pub token_balance_changes: Vec<TokenBalanceChange>,
    /// Error message if simulation failed.
    pub error: Option<String>,
}

/// SOL balance change for an account.
#[derive(Debug, Clone)]
pub struct BalanceChange {
    /// Account pubkey.
    pub account: Pubkey,
    /// Balance before transaction.
    pub before: u64,
    /// Balance after transaction.
    pub after: u64,
    /// Net change (can be negative).
    pub delta: i64,
}

/// Token balance change for an account.
#[derive(Debug, Clone)]
pub struct TokenBalanceChange {
    /// Token account pubkey.
    pub account: Pubkey,
    /// Token mint.
    pub mint: Pubkey,
    /// Balance before transaction.
    pub before: u64,
    /// Balance after transaction.
    pub after: u64,
    /// Net change (can be negative).
    pub delta: i64,
}

/// Configuration for simulation validation.
#[derive(Debug, Clone)]
pub struct SimulationConfig {
    /// Maximum acceptable SOL loss in lamports.
    pub max_sol_loss: u64,
    /// Maximum acceptable token loss percentage (0-100).
    pub max_token_loss_percent: u8,
    /// Fail if any unexpected account is modified.
    pub strict_account_checks: bool,
    /// Expected accounts to be modified.
    pub expected_accounts: Vec<Pubkey>,
}

impl Default for SimulationConfig {
    fn default() -> Self {
        Self {
            max_sol_loss: 10_000_000, // 0.01 SOL
            max_token_loss_percent: 5,
            strict_account_checks: false,
            expected_accounts: Vec::new(),
        }
    }
}

impl SimulationConfig {
    /// Create a new simulation config.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set maximum SOL loss.
    pub fn max_sol_loss(mut self, lamports: u64) -> Self {
        self.max_sol_loss = lamports;
        self
    }

    /// Set maximum token loss percentage.
    pub fn max_token_loss_percent(mut self, percent: u8) -> Self {
        self.max_token_loss_percent = percent.min(100);
        self
    }

    /// Enable strict account checks.
    pub fn strict(mut self) -> Self {
        self.strict_account_checks = true;
        self
    }

    /// Set expected accounts.
    pub fn expected_accounts(mut self, accounts: Vec<Pubkey>) -> Self {
        self.expected_accounts = accounts;
        self
    }
}

/// Preview of a swap transaction.
#[derive(Debug, Clone)]
pub struct SwapPreview {
    /// Input token mint.
    pub input_token: Pubkey,
    /// Input amount.
    pub input_amount: u64,
    /// Output token mint.
    pub output_token: Pubkey,
    /// Output amount.
    pub output_amount: u64,
    /// Price impact in basis points.
    pub price_impact_bps: u16,
    /// Fees paid.
    pub fees: u64,
}

/// Simulation safety report.
#[derive(Debug, Clone)]
pub struct SimulationSafetyReport {
    /// Whether the simulation passed safety checks.
    pub safe: bool,
    /// Risk level.
    pub risk_level: SimulationRiskLevel,
    /// Warnings found.
    pub warnings: Vec<String>,
    /// Blockers that prevent approval.
    pub blockers: Vec<String>,
    /// The simulation result.
    pub simulation: SimulationResult,
}

/// Risk level from simulation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum SimulationRiskLevel {
    /// No issues detected.
    Safe,
    /// Minor warnings.
    Low,
    /// Significant concerns.
    Medium,
    /// High risk, requires confirmation.
    High,
    /// Critical issues, should not proceed.
    Critical,
}

impl std::fmt::Display for SimulationRiskLevel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SimulationRiskLevel::Safe => write!(f, "SAFE"),
            SimulationRiskLevel::Low => write!(f, "LOW"),
            SimulationRiskLevel::Medium => write!(f, "MEDIUM"),
            SimulationRiskLevel::High => write!(f, "HIGH"),
            SimulationRiskLevel::Critical => write!(f, "CRITICAL"),
        }
    }
}

/// Transaction simulator.
pub struct TransactionSimulator {
    rpc_client: RpcClient,
}

impl TransactionSimulator {
    /// Create a new transaction simulator.
    pub fn new(rpc_url: &str) -> Self {
        Self {
            rpc_client: RpcClient::new_with_commitment(
                rpc_url.to_string(),
                CommitmentConfig::confirmed(),
            ),
        }
    }

    /// Create from existing RpcClient.
    pub fn from_client(client: RpcClient) -> Self {
        Self { rpc_client: client }
    }

    /// Simulate a transaction and return detailed results.
    pub fn simulate(&self, transaction: &Transaction) -> Result<SimulationResult> {
        // Get accounts involved in transaction
        let accounts: Vec<Pubkey> = transaction
            .message
            .account_keys
            .iter()
            .cloned()
            .collect();

        // Fetch pre-balances
        let pre_balances = self.fetch_balances(&accounts)?;

        // Configure simulation
        let config = RpcSimulateTransactionConfig {
            sig_verify: false,
            replace_recent_blockhash: true,
            commitment: Some(CommitmentConfig::confirmed()),
            encoding: Some(UiTransactionEncoding::Base64),
            accounts: Some(RpcSimulateTransactionAccountsConfig {
                encoding: Some(UiAccountEncoding::Base64),
                addresses: accounts.iter().map(|p| p.to_string()).collect(),
            }),
            min_context_slot: None,
            inner_instructions: false,
        };

        // Run simulation
        let sim_result = self
            .rpc_client
            .simulate_transaction_with_config(transaction, config)
            .map_err(|e| ToolkitError::TransactionError(format!("Simulation failed: {}", e)))?;

        let value = sim_result.value;

        // Extract logs
        let logs = value.logs.unwrap_or_default();

        // Extract error
        let error = value.err.map(|e| format!("{:?}", e));
        let success = error.is_none();

        // Extract compute units
        let units_consumed = value.units_consumed.unwrap_or(0);

        // Calculate balance changes (simplified - actual implementation would parse post accounts)
        let balance_changes = self.calculate_balance_changes(&accounts, &pre_balances)?;

        Ok(SimulationResult {
            success,
            logs,
            units_consumed,
            balance_changes,
            token_balance_changes: Vec::new(), // Would require parsing token accounts
            error,
        })
    }

    /// Simulate and validate against safety config.
    pub fn simulate_and_validate(
        &self,
        transaction: &Transaction,
        config: &SimulationConfig,
    ) -> Result<SimulationSafetyReport> {
        let simulation = self.simulate(transaction)?;

        let mut warnings = Vec::new();
        let mut blockers = Vec::new();
        let mut risk_level = SimulationRiskLevel::Safe;

        // Check if simulation failed
        if !simulation.success {
            blockers.push(format!(
                "Simulation failed: {}",
                simulation.error.as_deref().unwrap_or("Unknown error")
            ));
            risk_level = SimulationRiskLevel::Critical;
        }

        // Check SOL losses
        for change in &simulation.balance_changes {
            if change.delta < 0 {
                let loss = (-change.delta) as u64;
                if loss > config.max_sol_loss {
                    blockers.push(format!(
                        "Excessive SOL loss: {} lamports from {}",
                        loss,
                        change.account
                    ));
                    risk_level = SimulationRiskLevel::Critical;
                } else if loss > config.max_sol_loss / 2 {
                    warnings.push(format!(
                        "Significant SOL loss: {} lamports from {}",
                        loss,
                        change.account
                    ));
                    if risk_level < SimulationRiskLevel::Medium {
                        risk_level = SimulationRiskLevel::Medium;
                    }
                }
            }
        }

        // Check for unexpected account modifications
        if config.strict_account_checks && !config.expected_accounts.is_empty() {
            for change in &simulation.balance_changes {
                if change.delta != 0 && !config.expected_accounts.contains(&change.account) {
                    warnings.push(format!(
                        "Unexpected account modified: {}",
                        change.account
                    ));
                    if risk_level < SimulationRiskLevel::High {
                        risk_level = SimulationRiskLevel::High;
                    }
                }
            }
        }

        // Check compute units (warn if high)
        if simulation.units_consumed > 1_000_000 {
            warnings.push(format!(
                "High compute usage: {} units",
                simulation.units_consumed
            ));
            if risk_level < SimulationRiskLevel::Low {
                risk_level = SimulationRiskLevel::Low;
            }
        }

        let safe = blockers.is_empty() && risk_level < SimulationRiskLevel::High;

        Ok(SimulationSafetyReport {
            safe,
            risk_level,
            warnings,
            blockers,
            simulation,
        })
    }

    /// Preview a swap outcome.
    pub fn preview_swap(&self, transaction: &Transaction) -> Result<SwapPreview> {
        let simulation = self.simulate(transaction)?;

        if !simulation.success {
            return Err(ToolkitError::TransactionError(format!(
                "Swap simulation failed: {}",
                simulation.error.unwrap_or_else(|| "Unknown error".to_string())
            )));
        }

        // Parse token balance changes to determine swap details
        // This is a simplified implementation - real implementation would parse
        // the actual token account changes from simulation

        // For now, return a placeholder that would need to be filled from actual simulation data
        Ok(SwapPreview {
            input_token: Pubkey::default(),
            input_amount: 0,
            output_token: Pubkey::default(),
            output_amount: 0,
            price_impact_bps: 0,
            fees: 0,
        })
    }

    /// Fetch current balances for accounts.
    fn fetch_balances(&self, accounts: &[Pubkey]) -> Result<HashMap<Pubkey, u64>> {
        let mut balances = HashMap::new();

        for account in accounts {
            match self.rpc_client.get_balance(account) {
                Ok(balance) => {
                    balances.insert(*account, balance);
                }
                Err(_) => {
                    balances.insert(*account, 0);
                }
            }
        }

        Ok(balances)
    }

    /// Calculate balance changes.
    fn calculate_balance_changes(
        &self,
        accounts: &[Pubkey],
        pre_balances: &HashMap<Pubkey, u64>,
    ) -> Result<Vec<BalanceChange>> {
        let mut changes = Vec::new();

        for account in accounts {
            let before = *pre_balances.get(account).unwrap_or(&0);
            // Post-balance would come from simulation result
            // For now, assume no change (actual implementation would parse simulation accounts)
            let after = before;
            let delta = after as i64 - before as i64;

            if delta != 0 {
                changes.push(BalanceChange {
                    account: *account,
                    before,
                    after,
                    delta,
                });
            }
        }

        Ok(changes)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_simulation_config_defaults() {
        let config = SimulationConfig::default();
        assert_eq!(config.max_sol_loss, 10_000_000);
        assert_eq!(config.max_token_loss_percent, 5);
        assert!(!config.strict_account_checks);
    }

    #[test]
    fn test_simulation_config_builder() {
        let config = SimulationConfig::new()
            .max_sol_loss(5_000_000)
            .max_token_loss_percent(10)
            .strict();

        assert_eq!(config.max_sol_loss, 5_000_000);
        assert_eq!(config.max_token_loss_percent, 10);
        assert!(config.strict_account_checks);
    }

    #[test]
    fn test_simulation_config_max_percent_capped() {
        let config = SimulationConfig::new().max_token_loss_percent(150);
        assert_eq!(config.max_token_loss_percent, 100);
    }

    #[test]
    fn test_simulation_result_success() {
        let result = SimulationResult {
            success: true,
            logs: vec!["Program log: Success".to_string()],
            units_consumed: 50000,
            balance_changes: vec![],
            token_balance_changes: vec![],
            error: None,
        };

        assert!(result.success);
        assert!(result.error.is_none());
    }

    #[test]
    fn test_simulation_result_failure() {
        let result = SimulationResult {
            success: false,
            logs: vec!["Program log: Error".to_string()],
            units_consumed: 10000,
            balance_changes: vec![],
            token_balance_changes: vec![],
            error: Some("Insufficient funds".to_string()),
        };

        assert!(!result.success);
        assert!(result.error.is_some());
    }

    #[test]
    fn test_balance_change() {
        let change = BalanceChange {
            account: Pubkey::new_unique(),
            before: 1_000_000_000,
            after: 900_000_000,
            delta: -100_000_000,
        };

        assert!(change.delta < 0);
        assert_eq!(change.before - change.after, 100_000_000);
    }

    #[test]
    fn test_simulation_risk_level_ordering() {
        assert!(SimulationRiskLevel::Safe < SimulationRiskLevel::Low);
        assert!(SimulationRiskLevel::Low < SimulationRiskLevel::Medium);
        assert!(SimulationRiskLevel::Medium < SimulationRiskLevel::High);
        assert!(SimulationRiskLevel::High < SimulationRiskLevel::Critical);
    }

    #[test]
    fn test_simulation_safety_report_safe() {
        let report = SimulationSafetyReport {
            safe: true,
            risk_level: SimulationRiskLevel::Safe,
            warnings: vec![],
            blockers: vec![],
            simulation: SimulationResult {
                success: true,
                logs: vec![],
                units_consumed: 50000,
                balance_changes: vec![],
                token_balance_changes: vec![],
                error: None,
            },
        };

        assert!(report.safe);
        assert!(report.blockers.is_empty());
    }

    #[test]
    fn test_simulation_safety_report_blocked() {
        let report = SimulationSafetyReport {
            safe: false,
            risk_level: SimulationRiskLevel::Critical,
            warnings: vec![],
            blockers: vec!["Simulation failed".to_string()],
            simulation: SimulationResult {
                success: false,
                logs: vec![],
                units_consumed: 0,
                balance_changes: vec![],
                token_balance_changes: vec![],
                error: Some("Error".to_string()),
            },
        };

        assert!(!report.safe);
        assert!(!report.blockers.is_empty());
    }

    #[test]
    fn test_swap_preview() {
        let preview = SwapPreview {
            input_token: Pubkey::new_unique(),
            input_amount: 1_000_000,
            output_token: Pubkey::new_unique(),
            output_amount: 950_000,
            price_impact_bps: 50,
            fees: 1000,
        };

        assert!(preview.output_amount < preview.input_amount);
        assert_eq!(preview.price_impact_bps, 50);
    }
}