multiliquid-svm-sdk 0.1.2

Unsigned transaction builders, account codecs, and quoting for Multiliquid on Solana
Documentation
//! Swap event decoding and program-scoped transaction log parsing.

use std::str::FromStr;

use base64::{engine::general_purpose::STANDARD, Engine};
use solana_sdk::{pubkey::Pubkey, signature::Signature};

use crate::{
    error::{Result, SdkError},
    rpc::Rpc,
    types::SwapExecutedEvent,
};

/// Decode the checked-in IDL's event layout, including its discriminator.
/// Trailing bytes are accepted, matching the TypeScript decoder.
pub fn decode_swap_executed_event(data: &[u8]) -> Result<SwapExecutedEvent> {
    Ok(SwapExecutedEvent::decode(data)?)
}

/// Extract events emitted directly by `program_id`, excluding its CPIs.
///
/// Log arrays without any invocation/exit records are treated as already scoped,
/// as in the TypeScript SDK. With runtime context present, an active matching
/// invocation is required, including for data preceding the first invocation.
pub fn parse_swap_events_from_logs(logs: &[String], program_id: &Pubkey) -> Vec<SwapExecutedEvent> {
    let has_context = logs.iter().any(|line| parse_program_log(line).is_some());
    let mut stack: Vec<(Pubkey, usize)> = Vec::new();
    let mut events = Vec::new();

    for line in logs {
        match parse_program_log(line) {
            Some(ProgramLog::Invoke { program_id, depth }) => {
                while stack
                    .last()
                    .is_some_and(|(_, current_depth)| *current_depth >= depth)
                {
                    stack.pop();
                }
                stack.push((program_id, depth));
                continue;
            }
            Some(ProgramLog::Exit { program_id, .. }) => {
                if let Some(index) = stack.iter().rposition(|(active, _)| *active == program_id) {
                    stack.truncate(index);
                }
                continue;
            }
            None => {}
        }

        if has_context && stack.last().map(|(active, _)| active) != Some(program_id) {
            continue;
        }
        // A program can print "Program data:" inside an ordinary log message.
        // Only the runtime's data-record prefix denotes an event payload.
        let Some(payload) = line.strip_prefix("Program data:") else {
            continue;
        };
        let Ok(data) = STANDARD.decode(payload.trim()) else {
            continue;
        };
        if let Ok(event) = decode_swap_executed_event(&data) {
            events.push(event);
        }
    }
    events
}

/// Fetch transaction logs using the RPC client's configured commitment.
/// Missing transactions or metadata produce an empty event list.
pub async fn parse_swap_events_from_transaction<R: Rpc + ?Sized>(
    rpc: &R,
    signature: &str,
    program_id: &Pubkey,
) -> Result<Vec<SwapExecutedEvent>> {
    Signature::from_str(signature).map_err(|error| {
        SdkError::InvalidInput(format!("Invalid transaction signature: {error}"))
    })?;
    let logs = rpc
        .get_transaction_logs(signature)
        .await?
        .unwrap_or_default();
    Ok(parse_swap_events_from_logs(&logs, program_id))
}

#[derive(Debug, Clone, Copy)]
pub(crate) enum ProgramLog {
    Invoke {
        program_id: Pubkey,
        depth: usize,
    },
    Exit {
        program_id: Pubkey,
        failed: bool,
        custom_code: Option<u32>,
    },
}

pub(crate) fn parse_program_log(line: &str) -> Option<ProgramLog> {
    let (address, message) = line.strip_prefix("Program ")?.split_once(' ')?;
    let program_id = Pubkey::from_str(address).ok()?;
    if let Some(depth) = message
        .strip_prefix("invoke [")
        .and_then(|value| value.strip_suffix(']'))
    {
        if depth.is_empty() || !depth.bytes().all(|byte| byte.is_ascii_digit()) {
            return None;
        }
        let depth = depth.parse::<usize>().ok()?;
        return (depth > 0).then_some(ProgramLog::Invoke { program_id, depth });
    }
    if message == "success" {
        return Some(ProgramLog::Exit {
            program_id,
            failed: false,
            custom_code: None,
        });
    }
    let failure = message.strip_prefix("failed: ")?;
    if failure.is_empty() {
        return None;
    }
    let custom_code = failure
        .strip_prefix("custom program error: ")
        .and_then(|value| {
            if let Some(hex) = value.strip_prefix("0x") {
                u32::from_str_radix(hex, 16).ok()
            } else {
                value.parse().ok()
            }
        });
    Some(ProgramLog::Exit {
        program_id,
        failed: true,
        custom_code,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::{SwapDirection, SwapType};

    fn event() -> SwapExecutedEvent {
        SwapExecutedEvent {
            requestor: Pubkey::new_from_array([1; 32]),
            amount_in: u64::MAX,
            protocol_fee_amount: 2,
            discount_bps: 10,
            amount_out: 50,
            pair: Pubkey::new_from_array([2; 32]),
            swap_direction: SwapDirection::QuoteToBase,
            swap_type: SwapType::ExactOut,
            redemption_fee_bps: 12,
            discount_rate_bps: 34,
        }
    }

    fn payload(event: &SwapExecutedEvent) -> String {
        format!("Program data: {}", STANDARD.encode(event.encode().unwrap()))
    }

    #[test]
    fn decodes_binary_boundaries_and_rejects_invalid_layouts() {
        let expected = event();
        let mut bytes = expected.encode().unwrap();
        assert_eq!(decode_swap_executed_event(&bytes).unwrap(), expected);
        assert!(decode_swap_executed_event(&bytes[..103]).is_err());
        bytes.push(0);
        assert_eq!(decode_swap_executed_event(&bytes).unwrap(), expected);
        bytes[98] = 2;
        assert!(decode_swap_executed_event(&bytes).is_err());
        bytes[98] = 0;
        bytes[99] = 2;
        assert!(decode_swap_executed_event(&bytes).is_err());
        bytes[99] = 1;
        bytes[0] ^= 0xff;
        assert!(decode_swap_executed_event(&bytes).is_err());
    }

    #[test]
    fn excludes_nested_programs_and_restores_context_on_both_exit_kinds() {
        let swap = Pubkey::new_from_array([3; 32]);
        let other = Pubkey::new_from_array([4; 32]);
        let expected = event();
        let data = payload(&expected);
        let logs = vec![
            data.clone(),
            format!("Program {swap} invoke [1]"),
            format!("Program {other} invoke [2]"),
            data.clone(),
            format!("Program {other} success"),
            data.clone(),
            format!("Program {other} invoke [2]"),
            data.clone(),
            format!("Program {other} failed: custom program error: 0x1"),
            data.clone(),
            format!("Program {swap} success"),
            data,
        ];
        assert_eq!(
            parse_swap_events_from_logs(&logs, &swap),
            vec![expected.clone(), expected]
        );
    }

    #[test]
    fn ignores_spoofed_malformed_and_unrelated_data_without_aborting_scan() {
        let expected = event();
        let mut unrelated = expected.encode().unwrap();
        unrelated[0] ^= 0xff;
        let mut unknown_enum = expected.encode().unwrap();
        unknown_enum[98] = 255;
        let data = payload(&expected);
        let logs = vec![
            "Program data:".into(),
            "Program data: %%%invalid%%%".into(),
            format!("Program data: {}", STANDARD.encode(&unrelated)),
            format!("Program data: {}", STANDARD.encode(&unknown_enum)),
            format!("Program data: {}", STANDARD.encode(&unrelated[..99])),
            format!("Program log: {data}"),
            data,
        ];
        assert_eq!(
            parse_swap_events_from_logs(&logs, &Pubkey::default()),
            vec![expected]
        );
    }

    #[test]
    fn stale_and_out_of_order_frames_never_own_later_data() {
        let swap = Pubkey::new_from_array([3; 32]);
        let other = Pubkey::new_from_array([4; 32]);
        let data = payload(&event());
        let logs = vec![
            format!("Program {swap} invoke [1]"),
            format!("Program {other} invoke [2]"),
            format!("Program {swap} success"),
            data.clone(),
            format!("Program {other} success"),
            format!("Program {swap} invoke [1]"),
            format!("Program {other} invoke [1]"),
            data,
        ];
        assert!(parse_swap_events_from_logs(&logs, &swap).is_empty());
    }
}