multiliquid-svm-sdk 0.1.2

Unsigned transaction builders, account codecs, and quoting for Multiliquid on Solana
Documentation
//! RPC-backed local quotes and unsigned on-chain simulation quotes.

use solana_sdk::pubkey::Pubkey;

use crate::{
    error::{Result, SdkError},
    errors::{parse_simulation_program_error_from_logs, parse_synthetic_simulation_error},
    events::parse_swap_events_from_logs,
    quote_core::compute_swap_quote,
    rpc::Rpc,
    swap::build_swap_instruction,
    transaction::build_unsigned_transaction,
    types::{SimulationQuote, SwapParams, SwapQuote},
    validation::assert_positive_amount,
};

pub async fn get_quote<R: Rpc + ?Sized>(
    rpc: &R,
    params: &SwapParams,
    program_id: &Pubkey,
) -> Result<SwapQuote> {
    compute_swap_quote(rpc, params, program_id).await
}

/// Simulate only the swap, without ATA creation or slippage constraints.
///
/// The transaction is a real unsigned v0 transaction. Program failures retain
/// their swap/treasury namespace and logs; unknown failures are never quotes.
pub async fn get_quote_via_simulation<R: Rpc + ?Sized>(
    rpc: &R,
    params: &SwapParams,
    program_id: &Pubkey,
) -> Result<SimulationQuote> {
    assert_positive_amount(params.amount, "amount")?;
    let simulation_params = SwapParams {
        min_amount_out: None,
        max_amount_in: None,
        auto_create_ata: Some(false),
        ..params.clone()
    };
    let built = build_swap_instruction(rpc, &simulation_params, program_id).await?;
    let transaction = build_unsigned_transaction(rpc, &params.user, &[built.instruction]).await?;
    let simulation = rpc.simulate_transaction(&transaction).await?;
    if let Some(error) = simulation.error {
        let parsed = parse_simulation_program_error_from_logs(
            &simulation.logs,
            program_id,
            built.treasury_program_address.as_ref(),
        )
        .or_else(|| {
            parse_synthetic_simulation_error(
                &simulation.logs,
                built.onchain_direction,
                params.user_input_token_account.as_ref(),
                params.user_output_token_account.as_ref(),
                program_id,
                built.treasury_program_address.as_ref(),
                built.has_protocol_fee_transfer,
            )
            .map(Into::into)
        });
        return Err(match parsed {
            Some(error) => SdkError::Program(error),
            None => SdkError::Simulation(format!("Simulation failed: {error}")),
        });
    }
    let event = parse_swap_events_from_logs(&simulation.logs, program_id)
        .pop()
        .ok_or_else(|| {
            SdkError::Simulation("No SwapExecuted event found in simulation logs".into())
        })?;
    Ok(SimulationQuote {
        amount_in: event.amount_in,
        amount_out: event.amount_out,
        protocol_fee: event.protocol_fee_amount,
        discount_bps: event.discount_bps,
        pair: event.pair,
        input_mint: params.input_mint,
        output_mint: params.output_mint,
        swap_type: event.swap_type,
        compute_units_consumed: simulation.units_consumed.unwrap_or(0),
    })
}

#[cfg(test)]
mod tests {
    use base64::{engine::general_purpose::STANDARD, Engine};
    use solana_sdk::{message::VersionedMessage, signature::Signature};

    use super::*;
    use crate::{
        constants::SPL_TOKEN_PROGRAM_ADDRESS,
        errors::ParsedSimulationProgramError,
        generated::swap::{SwapArgs, SwapExecuted},
        pda::{derive_associated_token_account, derive_pair},
        quote_core::test_support::{Fixture, TestRpc},
        rpc::SimulationResult,
        types::{SwapDirection, SwapType},
    };

    fn event_log(fixture: &Fixture, amount_in: u64) -> String {
        let event = SwapExecuted {
            requestor: fixture.params.user,
            amount_in,
            protocol_fee_amount: 5,
            discount_bps: 10,
            amount_out: 85,
            pair: derive_pair(
                &fixture.params.liquidity_provider,
                &fixture.pair.quote_token_mint_address,
                &fixture.pair.base_token_mint_address,
                &fixture.program,
            )
            .0,
            swap_direction: fixture.direction(),
            swap_type: fixture.params.swap_type,
            redemption_fee_bps: 10,
            discount_rate_bps: 20,
        };
        format!("Program data: {}", STANDARD.encode(event.encode().unwrap()))
    }

    fn failed_simulation(rpc: &mut TestRpc, logs: Vec<String>) {
        rpc.simulation = Ok(SimulationResult {
            logs,
            error: Some(serde_json::json!({"InstructionError": [0, {"Custom": 1}]})),
            units_consumed: None,
        });
    }

    fn transfer_logs(fails: bool) -> Vec<String> {
        vec![
            format!("Program {SPL_TOKEN_PROGRAM_ADDRESS} invoke [2]"),
            "Program log: Instruction: TransferChecked".into(),
            if fails {
                "Program log: Error: insufficient funds".into()
            } else {
                format!("Program {SPL_TOKEN_PROGRAM_ADDRESS} success")
            },
        ]
    }

    #[tokio::test]
    async fn simulation_quotes_last_owned_event_without_fee_subtraction_or_ata_creation() {
        for direction in [SwapDirection::QuoteToBase, SwapDirection::BaseToQuote] {
            let mut fixture = Fixture::new();
            if direction != fixture.direction() {
                fixture.reverse();
            }
            fixture.params.auto_create_ata = Some(true);
            fixture.params.min_amount_out = Some(u64::MAX);
            fixture.params.max_amount_in = Some(1);
            let mut rpc = fixture.rpc();
            rpc.forbidden_accounts = [fixture.params.input_mint, fixture.params.output_mint]
                .map(|mint| {
                    derive_associated_token_account(
                        &fixture.params.user,
                        &mint,
                        &SPL_TOKEN_PROGRAM_ADDRESS,
                    )
                    .0
                })
                .to_vec();
            let foreign = Pubkey::new_from_array([10; 32]);
            rpc.simulation = Ok(SimulationResult {
                logs: vec![
                    format!("Program {} invoke [1]", fixture.program),
                    event_log(&fixture, 100),
                    event_log(&fixture, 777),
                    format!("Program {foreign} invoke [2]"),
                    event_log(&fixture, 999),
                    format!("Program {foreign} success"),
                    format!("Program {} success", fixture.program),
                ],
                error: None,
                units_consumed: Some(123_456),
            });
            let quote = get_quote_via_simulation(&rpc, &fixture.params, &fixture.program)
                .await
                .unwrap();
            assert_eq!(quote.amount_in, 777);
            assert_eq!(quote.amount_out, 85);
            assert_eq!(quote.protocol_fee, 5);
            assert_eq!(quote.compute_units_consumed, 123_456);
            assert_eq!(quote.input_mint, fixture.params.input_mint);
            assert_eq!(quote.output_mint, fixture.params.output_mint);

            let transactions = rpc.transactions.lock();
            let transaction = &transactions[0];
            let VersionedMessage::V0(message) = &transaction.message else {
                panic!("simulation must use a v0 transaction")
            };
            assert_eq!(message.instructions.len(), 1);
            assert_eq!(message.account_keys[0], fixture.params.user);
            assert_eq!(message.recent_blockhash.to_bytes(), [8; 32]);
            assert_eq!(
                transaction.signatures,
                vec![Signature::default(); usize::from(message.header.num_required_signatures)]
            );
            let args = SwapArgs::decode(&message.instructions[0].data).unwrap();
            assert_eq!(args.swap_direction, direction);
            assert_eq!((args.min_amount_out, args.max_amount_in), (None, None));
        }
    }

    #[tokio::test]
    async fn simulation_exact_out_trusts_event_and_defaults_missing_compute_units_to_zero() {
        let mut fixture = Fixture::new();
        fixture.params.swap_type = SwapType::ExactOut;
        let mut rpc = fixture.rpc();
        rpc.simulation.as_mut().unwrap().logs = vec![event_log(&fixture, 101)];
        let quote = get_quote_via_simulation(&rpc, &fixture.params, &fixture.program)
            .await
            .unwrap();
        assert_eq!(quote.amount_in, 101);
        assert_eq!(quote.swap_type, SwapType::ExactOut);
        assert_eq!(quote.compute_units_consumed, 0);
    }

    #[tokio::test]
    async fn missing_event_unknown_execution_error_and_transport_failure_are_errors() {
        let fixture = Fixture::new();
        let mut rpc = fixture.rpc();
        assert!(matches!(
            get_quote_via_simulation(&rpc, &fixture.params, &fixture.program).await,
            Err(SdkError::Simulation(_))
        ));
        failed_simulation(&mut rpc, vec![event_log(&fixture, 777)]);
        let error = get_quote_via_simulation(&rpc, &fixture.params, &fixture.program)
            .await
            .unwrap_err();
        let SdkError::Simulation(message) = error else {
            panic!("an unscoped custom code must remain a generic simulation error")
        };
        assert!(message.contains("\"InstructionError\":[0,{\"Custom\":1}]"));
        rpc.simulation = Err("RPC connection failed");
        assert!(matches!(
            get_quote_via_simulation(&rpc, &fixture.params, &fixture.program).await,
            Err(SdkError::Rpc(_))
        ));
    }

    #[tokio::test]
    async fn simulation_preserves_recognized_program_error_and_logs() {
        let fixture = Fixture::new();
        let mut rpc = fixture.rpc();
        let logs = vec![
            format!("Program {} invoke [1]", fixture.program),
            "Program log: Error Code: InsufficientLpFeeBalance. Error Number: 6028.".into(),
            format!(
                "Program {} failed: custom program error: 0x178c",
                fixture.program
            ),
        ];
        failed_simulation(&mut rpc, logs.clone());
        let error = get_quote_via_simulation(&rpc, &fixture.params, &fixture.program)
            .await
            .unwrap_err();
        let SdkError::Program(ParsedSimulationProgramError::Swap(error)) = error else {
            panic!("recognized swap errors must retain their structured namespace")
        };
        assert_eq!(error.code, 6028);
        assert_eq!(error.name, "InsufficientLpFeeBalance");
        assert_eq!(error.logs, Some(logs));
    }

    #[tokio::test]
    async fn simulation_distinguishes_optional_fee_output_and_input_funds_failures() {
        for (fee_bps, failed_ordinal, expected_code) in
            [(0, 1, 1), (0, 2, 2), (100, 1, 1), (100, 2, 1), (100, 3, 2)]
        {
            let mut fixture = Fixture::new();
            fixture.global.protocol_fees_bps = fee_bps;
            let mut rpc = fixture.rpc();
            let mut logs = vec![format!("Program {} invoke [1]", fixture.program)];
            for ordinal in 1..=failed_ordinal {
                logs.extend(transfer_logs(ordinal == failed_ordinal));
            }
            failed_simulation(&mut rpc, logs);
            let error = get_quote_via_simulation(&rpc, &fixture.params, &fixture.program)
                .await
                .unwrap_err();
            let SdkError::Program(ParsedSimulationProgramError::Swap(error)) = error else {
                panic!("expected synthetic swap funds error")
            };
            assert_eq!(error.code, expected_code);
        }
    }

    #[tokio::test]
    async fn synthetic_uninitialized_accounts_respect_direction_and_explicit_overrides() {
        for direction in [SwapDirection::QuoteToBase, SwapDirection::BaseToQuote] {
            for input in [true, false] {
                let mut fixture = Fixture::new();
                if direction != fixture.direction() {
                    fixture.reverse();
                }
                let quote_side = (direction == SwapDirection::QuoteToBase) == input;
                let account_name = if quote_side {
                    "quote_token_user_token_account"
                } else {
                    "base_token_user_token_account"
                };
                let mut rpc = fixture.rpc();
                failed_simulation(
                    &mut rpc,
                    vec![
                        format!("Program {} invoke [1]", fixture.program),
                        format!(
                            "Program log: AnchorError caused by account: {account_name}. Error Code: AccountNotInitialized. Error Number: 3012."
                        ),
                        format!("Program {} failed: custom program error: 0xbc4", fixture.program),
                    ],
                );
                let error = get_quote_via_simulation(&rpc, &fixture.params, &fixture.program)
                    .await
                    .unwrap_err();
                assert!(matches!(
                    error,
                    SdkError::Program(ParsedSimulationProgramError::Swap(error))
                        if error.code == 2
                ));
                let override_account = Pubkey::new_from_array([11; 32]);
                if input {
                    fixture.params.user_input_token_account = Some(override_account);
                } else {
                    fixture.params.user_output_token_account = Some(override_account);
                }
                assert!(matches!(
                    get_quote_via_simulation(&rpc, &fixture.params, &fixture.program).await,
                    Err(SdkError::Simulation(_))
                ));
            }
        }
    }

    #[tokio::test]
    async fn transfer_hook_failure_cannot_be_attributed_to_the_parent_token_transfer() {
        let fixture = Fixture::new();
        let mut rpc = fixture.rpc();
        let hook = Pubkey::new_from_array([12; 32]);
        failed_simulation(
            &mut rpc,
            vec![
                format!("Program {} invoke [1]", fixture.program),
                format!("Program {SPL_TOKEN_PROGRAM_ADDRESS} invoke [2]"),
                "Program log: Instruction: TransferChecked".into(),
                format!("Program {hook} invoke [3]"),
                "Program log: Error: insufficient funds".into(),
                format!("Program {hook} failed: custom program error: 0x1"),
                format!("Program {SPL_TOKEN_PROGRAM_ADDRESS} failed: custom program error: 0x1"),
                format!(
                    "Program {} failed: custom program error: 0x1",
                    fixture.program
                ),
            ],
        );
        assert!(matches!(
            get_quote_via_simulation(&rpc, &fixture.params, &fixture.program).await,
            Err(SdkError::Simulation(_))
        ));
    }

    #[tokio::test]
    async fn zero_amount_is_rejected_before_resolving_either_quote_path() {
        let mut fixture = Fixture::new();
        fixture.params.amount = 0;
        let mut rpc = fixture.rpc();
        rpc.forbidden_accounts = rpc.accounts.keys().copied().collect();
        assert!(matches!(
            get_quote(&rpc, &fixture.params, &fixture.program).await,
            Err(SdkError::InvalidInput(_))
        ));
        assert!(matches!(
            get_quote_via_simulation(&rpc, &fixture.params, &fixture.program).await,
            Err(SdkError::InvalidInput(_))
        ));
    }
}