1use 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#[derive(Debug, Clone)]
20pub struct SimulationResult {
21 pub success: bool,
23 pub logs: Vec<String>,
25 pub units_consumed: u64,
27 pub balance_changes: Vec<BalanceChange>,
29 pub token_balance_changes: Vec<TokenBalanceChange>,
31 pub error: Option<String>,
33}
34
35#[derive(Debug, Clone)]
37pub struct BalanceChange {
38 pub account: Pubkey,
40 pub before: u64,
42 pub after: u64,
44 pub delta: i64,
46}
47
48#[derive(Debug, Clone)]
50pub struct TokenBalanceChange {
51 pub account: Pubkey,
53 pub mint: Pubkey,
55 pub before: u64,
57 pub after: u64,
59 pub delta: i64,
61}
62
63#[derive(Debug, Clone)]
65pub struct SimulationConfig {
66 pub max_sol_loss: u64,
68 pub max_token_loss_percent: u8,
70 pub strict_account_checks: bool,
72 pub expected_accounts: Vec<Pubkey>,
74}
75
76impl Default for SimulationConfig {
77 fn default() -> Self {
78 Self {
79 max_sol_loss: 10_000_000, max_token_loss_percent: 5,
81 strict_account_checks: false,
82 expected_accounts: Vec::new(),
83 }
84 }
85}
86
87impl SimulationConfig {
88 pub fn new() -> Self {
90 Self::default()
91 }
92
93 pub fn max_sol_loss(mut self, lamports: u64) -> Self {
95 self.max_sol_loss = lamports;
96 self
97 }
98
99 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 pub fn strict(mut self) -> Self {
107 self.strict_account_checks = true;
108 self
109 }
110
111 pub fn expected_accounts(mut self, accounts: Vec<Pubkey>) -> Self {
113 self.expected_accounts = accounts;
114 self
115 }
116}
117
118#[derive(Debug, Clone)]
120pub struct SwapPreview {
121 pub input_token: Pubkey,
123 pub input_amount: u64,
125 pub output_token: Pubkey,
127 pub output_amount: u64,
129 pub price_impact_bps: u16,
131 pub fees: u64,
133}
134
135#[derive(Debug, Clone)]
137pub struct SimulationSafetyReport {
138 pub safe: bool,
140 pub risk_level: SimulationRiskLevel,
142 pub warnings: Vec<String>,
144 pub blockers: Vec<String>,
146 pub simulation: SimulationResult,
148}
149
150#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
152pub enum SimulationRiskLevel {
153 Safe,
155 Low,
157 Medium,
159 High,
161 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
177pub struct TransactionSimulator {
179 rpc_client: RpcClient,
180}
181
182impl TransactionSimulator {
183 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 pub fn from_client(client: RpcClient) -> Self {
195 Self { rpc_client: client }
196 }
197
198 pub fn simulate(&self, transaction: &Transaction) -> Result<SimulationResult> {
200 let accounts: Vec<Pubkey> = transaction
202 .message
203 .account_keys
204 .iter()
205 .cloned()
206 .collect();
207
208 let pre_balances = self.fetch_balances(&accounts)?;
210
211 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 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 let logs = value.logs.unwrap_or_default();
235
236 let error = value.err.map(|e| format!("{:?}", e));
238 let success = error.is_none();
239
240 let units_consumed = value.units_consumed.unwrap_or(0);
242
243 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(), error,
253 })
254 }
255
256 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 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 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 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 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 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 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 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 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 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}