Skip to main content

sol_parser_sdk/
rpc_parser.rs

1//! RPC Transaction Parser
2//!
3//! 提供独立的 RPC 交易解析功能,不依赖 gRPC streaming
4//! 可以用于测试验证和离线分析
5
6use crate::core::events::DexEvent;
7use crate::grpc::instruction_parser::parse_instructions_enhanced;
8use crate::grpc::types::EventTypeFilter;
9use crate::instr::read_pubkey_fast;
10use base64::{engine::general_purpose, Engine as _};
11use solana_client::rpc_client::RpcClient;
12use solana_client::rpc_config::RpcTransactionConfig;
13use solana_sdk::pubkey::Pubkey;
14use solana_sdk::signature::Signature;
15use solana_transaction_status::{
16    EncodedConfirmedTransactionWithStatusMeta, EncodedTransaction, UiTransactionEncoding,
17};
18use std::collections::HashMap;
19use std::str::FromStr;
20use yellowstone_grpc_proto::prelude::{
21    CompiledInstruction, InnerInstruction, InnerInstructions, Message, MessageAddressTableLookup,
22    MessageHeader, Transaction, TransactionStatusMeta,
23};
24
25/// Parse a transaction from RPC by signature
26///
27/// # Arguments
28/// * `rpc_client` - RPC client to fetch the transaction
29/// * `signature` - Transaction signature
30/// * `filter` - Optional event type filter
31///
32/// # Returns
33/// Vector of parsed DEX events
34///
35/// # Example
36/// ```no_run
37/// use solana_client::rpc_client::RpcClient;
38/// use solana_sdk::signature::Signature;
39/// use sol_parser_sdk::parse_transaction_from_rpc;
40/// use std::str::FromStr;
41///
42/// let client = RpcClient::new("https://api.mainnet-beta.solana.com".to_string());
43/// let sig = Signature::from_str("your-signature-here").unwrap();
44/// let events = parse_transaction_from_rpc(&client, &sig, None).unwrap();
45/// ```
46pub fn parse_transaction_from_rpc(
47    rpc_client: &RpcClient,
48    signature: &Signature,
49    filter: Option<&EventTypeFilter>,
50) -> Result<Vec<DexEvent>, ParseError> {
51    // Fetch transaction from RPC with V0 transaction support
52    let config = RpcTransactionConfig {
53        encoding: Some(UiTransactionEncoding::Base64),
54        commitment: None,
55        max_supported_transaction_version: Some(0),
56    };
57
58    let rpc_tx = rpc_client.get_transaction_with_config(signature, config).map_err(|e| {
59        let msg = e.to_string();
60        if msg.contains("invalid type: null") && msg.contains("EncodedConfirmedTransactionWithStatusMeta") {
61            ParseError::RpcError(format!(
62                "Transaction not found (RPC returned null). Common causes: 1) Transaction is too old and pruned (use an archive RPC). 2) Wrong network or invalid signature. Try SOLANA_RPC_URL with an archive endpoint (e.g. Helius, QuickNode) or a more recent tx. Original: {}",
63                msg
64            ))
65        } else {
66            ParseError::RpcError(msg)
67        }
68    })?;
69
70    parse_rpc_transaction(&rpc_tx, filter)
71}
72
73/// Parse a RPC transaction structure
74///
75/// # Arguments
76/// * `rpc_tx` - RPC transaction to parse
77/// * `filter` - Optional event type filter
78///
79/// # Returns
80/// Vector of parsed DEX events
81///
82/// # Example
83/// ```no_run
84/// use sol_parser_sdk::parse_rpc_transaction;
85///
86/// // Assuming you have an rpc_tx from RPC
87/// // let events = parse_rpc_transaction(&rpc_tx, None).unwrap();
88/// ```
89pub fn parse_rpc_transaction(
90    rpc_tx: &EncodedConfirmedTransactionWithStatusMeta,
91    filter: Option<&EventTypeFilter>,
92) -> Result<Vec<DexEvent>, ParseError> {
93    // Convert RPC format to gRPC format
94    let (grpc_meta, grpc_tx) = convert_rpc_to_grpc(rpc_tx)?;
95
96    // Extract metadata
97    let signature = extract_signature(rpc_tx)?;
98    let slot = rpc_tx.slot;
99    let block_time_us = rpc_tx.block_time.map(|t| t * 1_000_000);
100    let grpc_recv_us =
101        std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_micros()
102            as i64;
103
104    // Wrap grpc_tx in Option for reuse
105    let grpc_tx_opt = Some(grpc_tx);
106
107    let recent_blockhash = grpc_tx_opt.as_ref().and_then(|t| t.message.as_ref()).and_then(|m| {
108        if m.recent_blockhash.is_empty() {
109            None
110        } else {
111            Some(m.recent_blockhash.clone())
112        }
113    });
114
115    let mut program_invokes: HashMap<Pubkey, Vec<(i32, i32)>> = HashMap::new();
116
117    if let Some(ref tx) = grpc_tx_opt {
118        if let Some(ref msg) = tx.message {
119            let keys_len = msg.account_keys.len();
120            let writable_len = grpc_meta.loaded_writable_addresses.len();
121            let get_key = |i: usize| -> Option<&Vec<u8>> {
122                if i < keys_len {
123                    msg.account_keys.get(i)
124                } else if i < keys_len + writable_len {
125                    grpc_meta.loaded_writable_addresses.get(i - keys_len)
126                } else {
127                    grpc_meta.loaded_readonly_addresses.get(i - keys_len - writable_len)
128                }
129            };
130
131            for (i, ix) in msg.instructions.iter().enumerate() {
132                let pid = get_key(ix.program_id_index as usize)
133                    .map_or(Pubkey::default(), |k| read_pubkey_fast(k));
134                program_invokes.entry(pid).or_default().push((i as i32, -1));
135            }
136
137            for inner in &grpc_meta.inner_instructions {
138                let outer_idx = inner.index as usize;
139                for (j, inner_ix) in inner.instructions.iter().enumerate() {
140                    let pid = get_key(inner_ix.program_id_index as usize)
141                        .map_or(Pubkey::default(), |k| read_pubkey_fast(k));
142                    program_invokes.entry(pid).or_default().push((outer_idx as i32, j as i32));
143                }
144            }
145        }
146    }
147
148    // Parse instructions
149    let mut events = parse_instructions_enhanced(
150        &grpc_meta,
151        &grpc_tx_opt,
152        signature,
153        slot,
154        0, // tx_idx
155        block_time_us,
156        grpc_recv_us,
157        filter,
158    );
159
160    // Parse logs (for protocols like PumpFun that emit events in logs)
161    let needs_pumpfun = filter.map(|f| f.includes_pumpfun()).unwrap_or(true);
162    let is_created_buy = needs_pumpfun
163        && crate::logs::optimized_matcher::detect_pumpfun_create(&grpc_meta.log_messages);
164    let mut active_program_stack: Vec<Pubkey> = Vec::with_capacity(8);
165
166    for log in &grpc_meta.log_messages {
167        if let Some((pid, depth)) = crate::logs::optimized_matcher::parse_invoke_info(log) {
168            if let Ok(pk) = Pubkey::from_str(pid) {
169                active_program_stack.truncate(depth.saturating_sub(1));
170                active_program_stack.push(pk);
171            }
172        }
173
174        if let Some(mut event) = crate::logs::parse_log_with_program_id(
175            log,
176            signature,
177            slot,
178            0, // tx_index
179            block_time_us,
180            grpc_recv_us,
181            filter,
182            is_created_buy,
183            recent_blockhash.as_deref(),
184            active_program_stack.last(),
185        ) {
186            // Fill account fields - use same function as gRPC parsing
187            crate::core::account_dispatcher::fill_accounts_with_owned_keys(
188                &mut event,
189                &grpc_meta,
190                &grpc_tx_opt,
191                &program_invokes,
192            );
193
194            // Fill additional data fields (e.g., PumpSwap is_pump_pool)
195            crate::core::common_filler::fill_data(
196                &mut event,
197                &grpc_meta,
198                &grpc_tx_opt,
199                &program_invokes,
200            );
201
202            events.push(event);
203        }
204
205        if let Some(pid) = crate::logs::optimized_matcher::parse_program_complete_info(log) {
206            if let Ok(pk) = Pubkey::from_str(pid) {
207                if let Some(pos) = active_program_stack.iter().rposition(|active| *active == pk) {
208                    active_program_stack.truncate(pos);
209                }
210            }
211        }
212    }
213
214    Ok(events)
215}
216
217/// Parse error types
218#[derive(Debug)]
219pub enum ParseError {
220    RpcError(String),
221    ConversionError(String),
222    MissingField(String),
223}
224
225impl std::fmt::Display for ParseError {
226    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
227        match self {
228            ParseError::RpcError(msg) => write!(f, "RPC error: {}", msg),
229            ParseError::ConversionError(msg) => write!(f, "Conversion error: {}", msg),
230            ParseError::MissingField(msg) => write!(f, "Missing field: {}", msg),
231        }
232    }
233}
234
235impl std::error::Error for ParseError {}
236
237// ============================================================================
238// Internal conversion functions
239// ============================================================================
240
241fn extract_signature(
242    rpc_tx: &EncodedConfirmedTransactionWithStatusMeta,
243) -> Result<Signature, ParseError> {
244    let ui_tx = &rpc_tx.transaction.transaction;
245
246    match ui_tx {
247        EncodedTransaction::Binary(data, _encoding) => {
248            let bytes = general_purpose::STANDARD.decode(data).map_err(|e| {
249                ParseError::ConversionError(format!("Failed to decode base64: {}", e))
250            })?;
251
252            let versioned_tx: solana_sdk::transaction::VersionedTransaction =
253                bincode::deserialize(&bytes).map_err(|e| {
254                    ParseError::ConversionError(format!("Failed to deserialize transaction: {}", e))
255                })?;
256
257            Ok(versioned_tx.signatures[0])
258        }
259        _ => Err(ParseError::ConversionError("Unsupported transaction encoding".to_string())),
260    }
261}
262
263pub fn convert_rpc_to_grpc(
264    rpc_tx: &EncodedConfirmedTransactionWithStatusMeta,
265) -> Result<(TransactionStatusMeta, Transaction), ParseError> {
266    let rpc_meta = rpc_tx
267        .transaction
268        .meta
269        .as_ref()
270        .ok_or_else(|| ParseError::MissingField("meta".to_string()))?;
271
272    // Convert meta
273    let mut grpc_meta = TransactionStatusMeta {
274        err: None,
275        fee: rpc_meta.fee,
276        pre_balances: rpc_meta.pre_balances.clone(),
277        post_balances: rpc_meta.post_balances.clone(),
278        inner_instructions: Vec::new(),
279        log_messages: {
280            let opt: Option<Vec<String>> = rpc_meta.log_messages.clone().into();
281            opt.unwrap_or_default()
282        },
283        pre_token_balances: Vec::new(),
284        post_token_balances: Vec::new(),
285        rewards: Vec::new(),
286        loaded_writable_addresses: {
287            let loaded_opt: Option<solana_transaction_status::UiLoadedAddresses> =
288                rpc_meta.loaded_addresses.clone().into();
289            loaded_opt
290                .map(|addrs| {
291                    addrs
292                        .writable
293                        .iter()
294                        .map(|pk_str| {
295                            use std::str::FromStr;
296                            solana_sdk::pubkey::Pubkey::from_str(pk_str)
297                                .unwrap()
298                                .to_bytes()
299                                .to_vec()
300                        })
301                        .collect()
302                })
303                .unwrap_or_default()
304        },
305        loaded_readonly_addresses: {
306            let loaded_opt: Option<solana_transaction_status::UiLoadedAddresses> =
307                rpc_meta.loaded_addresses.clone().into();
308            loaded_opt
309                .map(|addrs| {
310                    addrs
311                        .readonly
312                        .iter()
313                        .map(|pk_str| {
314                            use std::str::FromStr;
315                            solana_sdk::pubkey::Pubkey::from_str(pk_str)
316                                .unwrap()
317                                .to_bytes()
318                                .to_vec()
319                        })
320                        .collect()
321                })
322                .unwrap_or_default()
323        },
324        return_data: None,
325        compute_units_consumed: rpc_meta.compute_units_consumed.clone().into(),
326
327        inner_instructions_none: {
328            let opt: Option<Vec<_>> = rpc_meta.inner_instructions.clone().into();
329            opt.is_none()
330        },
331        log_messages_none: {
332            let opt: Option<Vec<String>> = rpc_meta.log_messages.clone().into();
333            opt.is_none()
334        },
335        return_data_none: {
336            let opt: Option<solana_transaction_status::UiTransactionReturnData> =
337                rpc_meta.return_data.clone().into();
338            opt.is_none()
339        },
340        cost_units: rpc_meta.compute_units_consumed.clone().into(),
341    };
342
343    // Convert inner instructions
344    let inner_instructions_opt: Option<Vec<_>> = rpc_meta.inner_instructions.clone().into();
345    if let Some(ref inner_instructions) = inner_instructions_opt {
346        for inner in inner_instructions {
347            let mut grpc_inner =
348                InnerInstructions { index: inner.index as u32, instructions: Vec::new() };
349
350            for ix in &inner.instructions {
351                if let solana_transaction_status::UiInstruction::Compiled(compiled) = ix {
352                    // Decode base58 data
353                    let data = bs58::decode(&compiled.data).into_vec().map_err(|e| {
354                        ParseError::ConversionError(format!(
355                            "Failed to decode instruction data: {}",
356                            e
357                        ))
358                    })?;
359
360                    grpc_inner.instructions.push(InnerInstruction {
361                        program_id_index: compiled.program_id_index as u32,
362                        accounts: compiled.accounts.clone(),
363                        data,
364                        stack_height: compiled.stack_height.map(|h| h as u32),
365                    });
366                }
367            }
368
369            grpc_meta.inner_instructions.push(grpc_inner);
370        }
371    }
372
373    // Convert transaction
374    let ui_tx = &rpc_tx.transaction.transaction;
375
376    let (message, signatures) = match ui_tx {
377        EncodedTransaction::Binary(data, _encoding) => {
378            // Decode base64
379            let bytes = general_purpose::STANDARD.decode(data).map_err(|e| {
380                ParseError::ConversionError(format!("Failed to decode base64: {}", e))
381            })?;
382
383            // Parse as versioned transaction
384            let versioned_tx: solana_sdk::transaction::VersionedTransaction =
385                bincode::deserialize(&bytes).map_err(|e| {
386                    ParseError::ConversionError(format!("Failed to deserialize transaction: {}", e))
387                })?;
388
389            let sigs: Vec<Vec<u8>> =
390                versioned_tx.signatures.iter().map(|s| s.as_ref().to_vec()).collect();
391
392            let message = match versioned_tx.message {
393                solana_sdk::message::VersionedMessage::Legacy(legacy_msg) => {
394                    convert_legacy_message(&legacy_msg)?
395                }
396                solana_sdk::message::VersionedMessage::V0(v0_msg) => convert_v0_message(&v0_msg)?,
397            };
398
399            (message, sigs)
400        }
401        EncodedTransaction::Json(_) => {
402            return Err(ParseError::ConversionError(
403                "JSON encoded transactions not supported yet".to_string(),
404            ));
405        }
406        _ => {
407            return Err(ParseError::ConversionError(
408                "Unsupported transaction encoding".to_string(),
409            ));
410        }
411    };
412
413    let grpc_tx = Transaction { signatures, message: Some(message) };
414
415    Ok((grpc_meta, grpc_tx))
416}
417
418fn convert_legacy_message(
419    msg: &solana_sdk::message::legacy::Message,
420) -> Result<Message, ParseError> {
421    let account_keys: Vec<Vec<u8>> =
422        msg.account_keys.iter().map(|k| k.to_bytes().to_vec()).collect();
423
424    let instructions: Vec<CompiledInstruction> = msg
425        .instructions
426        .iter()
427        .map(|ix| CompiledInstruction {
428            program_id_index: ix.program_id_index as u32,
429            accounts: ix.accounts.clone(),
430            data: ix.data.clone(),
431        })
432        .collect();
433
434    Ok(Message {
435        header: Some(MessageHeader {
436            num_required_signatures: msg.header.num_required_signatures as u32,
437            num_readonly_signed_accounts: msg.header.num_readonly_signed_accounts as u32,
438            num_readonly_unsigned_accounts: msg.header.num_readonly_unsigned_accounts as u32,
439        }),
440        account_keys,
441        recent_blockhash: msg.recent_blockhash.to_bytes().to_vec(),
442        instructions,
443        versioned: false,
444        address_table_lookups: Vec::new(),
445    })
446}
447
448fn convert_v0_message(msg: &solana_sdk::message::v0::Message) -> Result<Message, ParseError> {
449    let account_keys: Vec<Vec<u8>> =
450        msg.account_keys.iter().map(|k| k.to_bytes().to_vec()).collect();
451
452    let instructions: Vec<CompiledInstruction> = msg
453        .instructions
454        .iter()
455        .map(|ix| CompiledInstruction {
456            program_id_index: ix.program_id_index as u32,
457            accounts: ix.accounts.clone(),
458            data: ix.data.clone(),
459        })
460        .collect();
461
462    Ok(Message {
463        header: Some(MessageHeader {
464            num_required_signatures: msg.header.num_required_signatures as u32,
465            num_readonly_signed_accounts: msg.header.num_readonly_signed_accounts as u32,
466            num_readonly_unsigned_accounts: msg.header.num_readonly_unsigned_accounts as u32,
467        }),
468        account_keys,
469        recent_blockhash: msg.recent_blockhash.to_bytes().to_vec(),
470        instructions,
471        versioned: true,
472        address_table_lookups: msg
473            .address_table_lookups
474            .iter()
475            .map(|lookup| MessageAddressTableLookup {
476                account_key: lookup.account_key.to_bytes().to_vec(),
477                writable_indexes: lookup.writable_indexes.clone(),
478                readonly_indexes: lookup.readonly_indexes.clone(),
479            })
480            .collect(),
481    })
482}