use std::{fmt, str::FromStr, sync::Arc};
use serde::{Deserialize, Serialize};
use solana_sdk::{
instruction::{AccountMeta, Instruction},
pubkey::Pubkey,
transaction::VersionedTransaction,
};
use crate::{error::SdkError, rpc::Rpc};
pub use crate::errors::{ParsedSwapError, SwapErrorCategory};
pub use crate::generated::swap::{
AssetConfig as AssetConfigAccount, AssetType, ExactMode, GlobalConfig as GlobalConfigAccount,
LpProtocolFeeConfig as LpProtocolFeeConfigAccount, LpStableConfig as LpStableConfigAccount,
NavData, Pair as PairAccount, SwapDirection, SwapExecuted as SwapExecutedEvent, SwapType,
};
pub use crate::rpc::Rpc as MultiliquidRpcApi;
pub type MultiliquidInstruction = Instruction;
pub type MultiliquidRpc = Arc<dyn Rpc>;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
pub enum Cluster {
#[default]
#[serde(rename = "devnet")]
Devnet,
#[serde(rename = "mainnet-beta")]
MainnetBeta,
}
impl Cluster {
pub const fn as_str(self) -> &'static str {
match self {
Self::Devnet => "devnet",
Self::MainnetBeta => "mainnet-beta",
}
}
}
impl fmt::Display for Cluster {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
impl FromStr for Cluster {
type Err = SdkError;
fn from_str(value: &str) -> Result<Self, Self::Err> {
match value {
"devnet" => Ok(Self::Devnet),
"mainnet-beta" => Ok(Self::MainnetBeta),
_ => Err(SdkError::InvalidInput(format!(
"unsupported cluster: {value}"
))),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum NavDataKind {
U64FixedAddress = 0,
Hardcoded = 1,
PythPush = 2,
RedstonePush = 3,
}
impl From<&NavData> for NavDataKind {
fn from(value: &NavData) -> Self {
match value {
NavData::U64FixedAddress { .. } => Self::U64FixedAddress,
NavData::Hardcoded { .. } => Self::Hardcoded,
NavData::PythPush { .. } => Self::PythPush,
NavData::RedstonePush { .. } => Self::RedstonePush,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedSwapPair {
pub pair_address: Pubkey,
pub pair: PairAccount,
pub input_mint: Pubkey,
pub output_mint: Pubkey,
pub quote_mint: Pubkey,
pub base_mint: Pubkey,
pub swap_direction: SwapDirection,
}
#[derive(Debug, Clone)]
pub struct SwapParams {
pub user: Pubkey,
pub liquidity_provider: Pubkey,
pub input_mint: Pubkey,
pub output_mint: Pubkey,
pub pair_address: Option<Pubkey>,
pub amount: u64,
pub swap_type: SwapType,
pub min_amount_out: Option<u64>,
pub max_amount_in: Option<u64>,
pub user_input_token_account: Option<Pubkey>,
pub user_output_token_account: Option<Pubkey>,
pub auto_create_ata: Option<bool>,
pub remaining_accounts: Option<Vec<AccountMeta>>,
}
pub type BuildSwapTransactionParams = SwapParams;
#[derive(Debug, Clone)]
pub struct UpdatePairParams {
pub liquidity_provider: Pubkey,
pub mint_a: Pubkey,
pub mint_b: Pubkey,
pub pair_address: Option<Pubkey>,
pub redemption_fee_bps: u16,
pub discount_rate_bps: u16,
pub paused: bool,
}
pub type BuildUpdatePairTransactionParams = UpdatePairParams;
#[derive(Debug, Clone)]
pub struct InitPairParams {
pub liquidity_provider: Pubkey,
pub mint_a: Pubkey,
pub mint_b: Pubkey,
pub redemption_fee_bps: u16,
pub discount_rate_bps: u16,
}
pub type BuildInitPairTransactionParams = InitPairParams;
#[derive(Debug, Clone)]
pub struct ClosePairParams {
pub liquidity_provider: Pubkey,
pub mint_a: Pubkey,
pub mint_b: Pubkey,
pub pair_address: Option<Pubkey>,
pub admin: Option<Pubkey>,
pub lp_mint_a_token_account: Option<Pubkey>,
pub lp_mint_b_token_account: Option<Pubkey>,
pub auto_create_ata: Option<bool>,
pub remaining_accounts: Option<Vec<AccountMeta>>,
}
pub type BuildClosePairTransactionParams = ClosePairParams;
#[derive(Debug, Clone)]
pub struct LpLiquidityParams {
pub liquidity_provider: Pubkey,
pub mint: Pubkey,
pub amount: u64,
pub amount_threshold: Option<u64>,
pub exact_mode: Option<ExactMode>,
pub lp_token_account: Option<Pubkey>,
pub auto_create_ata: Option<bool>,
pub remaining_accounts: Option<Vec<AccountMeta>>,
}
pub type BuildAddLiquidityTransactionParams = LpLiquidityParams;
pub type BuildRemoveLiquidityTransactionParams = LpLiquidityParams;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SwapQuote {
pub amount_in: u64,
pub amount_out: u64,
pub protocol_fees: u64,
pub issuer_protocol_fees: u64,
pub spread_protocol_fees: u64,
pub discount_amount: u64,
pub amount_in_for_vault: u64,
pub input_nav: u64,
pub output_nav: u64,
pub fee_token_mint: Pubkey,
pub fee_token_nav: u64,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SimulationQuote {
pub amount_in: u64,
pub amount_out: u64,
pub protocol_fee: u64,
pub discount_bps: u16,
pub pair: Pubkey,
pub input_mint: Pubkey,
pub output_mint: Pubkey,
pub swap_type: SwapType,
pub compute_units_consumed: u64,
}
#[derive(Debug, Clone)]
pub struct BuildSwapInstructionResult {
pub instruction: Instruction,
pub setup_instructions: Vec<Instruction>,
pub accounts: SwapAccountKeys,
pub onchain_direction: SwapDirection,
pub treasury_program_address: Option<Pubkey>,
pub has_protocol_fee_transfer: bool,
}
#[derive(Debug, Clone)]
pub struct BuildSwapTransactionResult {
pub transaction: VersionedTransaction,
pub accounts: SwapAccountKeys,
pub onchain_direction: SwapDirection,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UpdatePairAccountKeys {
pub liquidity_provider: Pubkey,
pub pair: Pubkey,
pub quote_token_mint_address: Pubkey,
pub base_token_mint_address: Pubkey,
pub global_config: Pubkey,
}
#[derive(Debug, Clone)]
pub struct BuildUpdatePairInstructionResult {
pub instruction: Instruction,
pub accounts: UpdatePairAccountKeys,
}
#[derive(Debug, Clone)]
pub struct BuildUpdatePairTransactionResult {
pub transaction: VersionedTransaction,
pub accounts: UpdatePairAccountKeys,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InitPairAccountKeys {
pub liquidity_provider: Pubkey,
pub pair: Pubkey,
pub quote_token_mint_address: Pubkey,
pub base_token_mint_address: Pubkey,
pub lp_vault_authority: Pubkey,
pub lp_fee_vault_authority: Pubkey,
pub quote_token_vault_token_account: Pubkey,
pub base_token_vault_token_account: Pubkey,
pub lp_vault_quote_pda: Pubkey,
pub lp_vault_base_pda: Pubkey,
pub global_config: Pubkey,
pub fee_token_mint_address: Pubkey,
pub lp_fee_token_account: Pubkey,
pub lp_stable_config_quote: Pubkey,
pub lp_stable_config_base: Pubkey,
pub quote_asset_config: Pubkey,
pub base_asset_config: Pubkey,
pub token_program_quote: Pubkey,
pub token_program_base: Pubkey,
pub token_program_fee: Pubkey,
pub associated_token_program: Pubkey,
pub system_program: Pubkey,
}
#[derive(Debug, Clone)]
pub struct BuildInitPairInstructionResult {
pub instruction: Instruction,
pub accounts: InitPairAccountKeys,
}
#[derive(Debug, Clone)]
pub struct BuildInitPairTransactionResult {
pub transaction: VersionedTransaction,
pub accounts: InitPairAccountKeys,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ClosePairAccountKeys {
pub admin: Pubkey,
pub liquidity_provider: Pubkey,
pub pair: Pubkey,
pub quote_token_mint_address: Pubkey,
pub base_token_mint_address: Pubkey,
pub lp_vault_authority: Pubkey,
pub quote_token_vault_token_account: Pubkey,
pub base_token_vault_token_account: Pubkey,
pub lp_quote_token_account: Pubkey,
pub lp_base_token_account: Pubkey,
pub lp_vault_quote_pda: Pubkey,
pub lp_vault_base_pda: Pubkey,
pub quote_asset_config: Pubkey,
pub base_asset_config: Pubkey,
pub global_config: Pubkey,
pub lp_protocol_fee_config: Pubkey,
pub treasury_user_position: Pubkey,
pub token_program_quote: Pubkey,
pub token_program_base: Pubkey,
pub remaining_accounts: Vec<AccountMeta>,
}
#[derive(Debug, Clone)]
pub struct BuildClosePairInstructionResult {
pub instruction: Instruction,
pub setup_instructions: Vec<Instruction>,
pub accounts: ClosePairAccountKeys,
}
#[derive(Debug, Clone)]
pub struct BuildClosePairTransactionResult {
pub transaction: VersionedTransaction,
pub accounts: ClosePairAccountKeys,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LiquidityAccountKeys {
pub liquidity_provider: Pubkey,
pub mint_address: Pubkey,
pub lp_token_account: Pubkey,
pub vault_token_account: Pubkey,
pub lp_vault_authority: Pubkey,
pub global_config: Pubkey,
pub lp_protocol_fee_config: Pubkey,
pub asset_config: Pubkey,
pub lp_stable_config: Pubkey,
pub token_program: Pubkey,
pub remaining_accounts: Vec<Pubkey>,
}
#[derive(Debug, Clone)]
pub struct BuildAddLiquidityInstructionResult {
pub instruction: Instruction,
pub setup_instructions: Vec<Instruction>,
pub accounts: LiquidityAccountKeys,
}
#[derive(Debug, Clone)]
pub struct BuildAddLiquidityTransactionResult {
pub transaction: VersionedTransaction,
pub accounts: LiquidityAccountKeys,
}
#[derive(Debug, Clone)]
pub struct BuildRemoveLiquidityInstructionResult {
pub instruction: Instruction,
pub setup_instructions: Vec<Instruction>,
pub accounts: LiquidityAccountKeys,
}
#[derive(Debug, Clone)]
pub struct BuildRemoveLiquidityTransactionResult {
pub transaction: VersionedTransaction,
pub accounts: LiquidityAccountKeys,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SwapAccountKeys {
pub user: Pubkey,
pub pair: Pubkey,
pub program_authority: Pubkey,
pub liquidity_provider: Pubkey,
pub lp_vault_authority: Pubkey,
pub lp_fee_vault_authority: Pubkey,
pub input_token_mint_address: Pubkey,
pub output_token_mint_address: Pubkey,
pub input_token_user_token_account: Pubkey,
pub output_token_user_token_account: Pubkey,
pub input_token_vault_token_account: Pubkey,
pub output_token_vault_token_account: Pubkey,
pub global_config: Pubkey,
pub fee_token_mint_address: Pubkey,
pub lp_fee_token_account: Pubkey,
pub fee_token_account: Pubkey,
pub input_config: Pubkey,
pub output_config: Pubkey,
pub fee_config: Pubkey,
pub input_lp_stable_config: Pubkey,
pub output_lp_stable_config: Pubkey,
pub lp_protocol_fee_config: Pubkey,
pub token_program_input: Pubkey,
pub token_program_output: Pubkey,
pub token_program_fee: Pubkey,
pub remaining_accounts: Vec<Pubkey>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PairRegistryEntry {
#[serde(with = "pubkey_string")]
pub pair: Pubkey,
#[serde(with = "pubkey_string")]
pub liquidity_provider: Pubkey,
#[serde(
default,
with = "optional_pubkey_string",
skip_serializing_if = "Option::is_none"
)]
pub vault_authority: Option<Pubkey>,
#[serde(with = "pubkey_string")]
pub quote_mint: Pubkey,
#[serde(with = "pubkey_string")]
pub base_mint: Pubkey,
pub quote_decimals: u8,
pub base_decimals: u8,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub label: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TransferHookRegistryEntry {
#[serde(with = "pubkey_string")]
pub mint: Pubkey,
#[serde(with = "pubkey_string")]
pub hook_program: Pubkey,
#[serde(with = "pubkey_string")]
pub extra_account_meta_list: Pubkey,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub label: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct PairRegistry {
pub devnet: Vec<PairRegistryEntry>,
#[serde(rename = "mainnet-beta")]
pub mainnet_beta: Vec<PairRegistryEntry>,
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct PairFilters {
pub quote_mint: Option<Pubkey>,
pub base_mint: Option<Pubkey>,
pub liquidity_provider: Option<Pubkey>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PairRegistryErrorContext {
pub cluster: Cluster,
pub registry_api_url: String,
}
pub type PairRegistryErrorHandler = Arc<dyn Fn(&SdkError, &PairRegistryErrorContext) + Send + Sync>;
#[derive(Clone, Default)]
pub struct PairRegistryFetchOptions {
pub registry_api_url: Option<String>,
pub rpc: Option<MultiliquidRpc>,
pub timeout_ms: Option<u64>,
pub on_error: Option<PairRegistryErrorHandler>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PauseStatus {
pub global_paused: bool,
pub pair_paused: bool,
pub input_paused: bool,
pub output_paused: bool,
pub fee_paused: bool,
pub input_lp_paused: bool,
pub output_lp_paused: bool,
pub any_paused: bool,
pub pause_reasons: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SwapMathResult {
pub protocol_fees: u64,
pub protocol_fee_basis: u64,
pub discount_amount: u64,
pub amount_in_for_vault: u64,
pub amount_out: u64,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SwapState {
pub global_config: GlobalConfigAccount,
pub pair_address: Pubkey,
pub pair: PairAccount,
pub onchain_direction: SwapDirection,
pub input_config: AssetConfigAccount,
pub output_config: AssetConfigAccount,
pub input_lp_stable_config: Option<LpStableConfigAccount>,
pub output_lp_stable_config: Option<LpStableConfigAccount>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OracleResolutionResult {
pub remaining_accounts: Vec<AccountMeta>,
}
mod pubkey_string {
use super::*;
use serde::{de::Error, Deserializer, Serializer};
pub fn serialize<S: Serializer>(key: &Pubkey, serializer: S) -> Result<S::Ok, S::Error> {
serializer.collect_str(key)
}
pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Pubkey, D::Error> {
String::deserialize(deserializer)?
.parse()
.map_err(D::Error::custom)
}
}
mod optional_pubkey_string {
use super::*;
use serde::{de::Error, Deserializer, Serializer};
struct PubkeyString<'a>(&'a Pubkey);
impl Serialize for PubkeyString<'_> {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.collect_str(self.0)
}
}
pub fn serialize<S: Serializer>(
key: &Option<Pubkey>,
serializer: S,
) -> Result<S::Ok, S::Error> {
match key {
Some(key) => serializer.serialize_some(&PubkeyString(key)),
None => serializer.serialize_none(),
}
}
pub fn deserialize<'de, D: Deserializer<'de>>(
deserializer: D,
) -> Result<Option<Pubkey>, D::Error> {
Option::<String>::deserialize(deserializer)?
.map(|key| key.parse().map_err(D::Error::custom))
.transpose()
}
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::*;
#[test]
fn registry_json_uses_base58_addresses_and_original_api_field_names() {
let pair = Pubkey::new_unique();
let lp = Pubkey::new_unique();
let quote = Pubkey::new_unique();
let base = Pubkey::new_unique();
let vault = Pubkey::new_unique();
let payload = json!({
"devnet": [{
"pair": pair.to_string(),
"liquidityProvider": lp.to_string(),
"vaultAuthority": vault.to_string(),
"quoteMint": quote.to_string(),
"baseMint": base.to_string(),
"quoteDecimals": 6,
"baseDecimals": 9,
}],
"mainnet-beta": [],
});
let registry: PairRegistry = serde_json::from_value(payload.clone()).unwrap();
assert_eq!(
registry.devnet[0],
PairRegistryEntry {
pair,
liquidity_provider: lp,
vault_authority: Some(vault),
quote_mint: quote,
base_mint: base,
quote_decimals: 6,
base_decimals: 9,
label: None,
}
);
assert_eq!(serde_json::to_value(registry).unwrap(), payload);
let mut invalid = payload;
invalid["devnet"][0]["pair"] = json!("not-a-solana-address");
assert!(serde_json::from_value::<PairRegistry>(invalid).is_err());
}
}