use std::{
collections::{HashMap, HashSet},
sync::LazyLock,
};
use serde::Deserialize;
use solana_sdk::pubkey::Pubkey;
use crate::{
constants::{DISCRIMINATOR_PAIR, PAIR_LAYOUT},
error::{Result, SdkError},
rpc::{Rpc, RpcFilter},
token::parse_mint_account_context,
types::{
Cluster, PairAccount, PairFilters, PairRegistry, PairRegistryEntry,
TransferHookRegistryEntry,
},
};
pub const DEFAULT_REGISTRY_API_URL: &str = "https://api.multiliquid.xyz";
pub const DEFAULT_REGISTRY_FETCH_TIMEOUT_MS: u64 = 10_000;
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct BundledRegistry {
pairs: PairRegistry,
mainnet_rwa_transfer_hooks: Vec<TransferHookRegistryEntry>,
}
static BUNDLED_REGISTRY: LazyLock<BundledRegistry> = LazyLock::new(|| {
serde_json::from_str(include_str!("../data/registry.json"))
.expect("the bundled registry contains valid deployment metadata")
});
pub static PAIR_REGISTRY: LazyLock<&'static PairRegistry> =
LazyLock::new(|| &BUNDLED_REGISTRY.pairs);
pub static DEVNET_PAIRS: LazyLock<&'static [PairRegistryEntry]> =
LazyLock::new(|| &BUNDLED_REGISTRY.pairs.devnet);
pub static MAINNET_PAIRS: LazyLock<&'static [PairRegistryEntry]> =
LazyLock::new(|| &BUNDLED_REGISTRY.pairs.mainnet_beta);
pub static MAINNET_RWA_TRANSFER_HOOKS: LazyLock<&'static [TransferHookRegistryEntry]> =
LazyLock::new(|| &BUNDLED_REGISTRY.mainnet_rwa_transfer_hooks);
pub fn get_mainnet_rwa_transfer_hook(mint: &Pubkey) -> Option<TransferHookRegistryEntry> {
MAINNET_RWA_TRANSFER_HOOKS
.iter()
.find(|entry| entry.mint == *mint)
.cloned()
}
fn matches_filters(
quote_mint: &Pubkey,
base_mint: &Pubkey,
liquidity_provider: &Pubkey,
filters: Option<&PairFilters>,
) -> bool {
let Some(filters) = filters else { return true };
filters
.quote_mint
.as_ref()
.is_none_or(|mint| mint == quote_mint)
&& filters
.base_mint
.as_ref()
.is_none_or(|mint| mint == base_mint)
&& filters
.liquidity_provider
.as_ref()
.is_none_or(|lp| lp == liquidity_provider)
}
pub fn get_offline_pairs(
cluster: Cluster,
filters: Option<&PairFilters>,
) -> Vec<PairRegistryEntry> {
let pairs = match cluster {
Cluster::Devnet => *DEVNET_PAIRS,
Cluster::MainnetBeta => *MAINNET_PAIRS,
};
pairs
.iter()
.filter(|entry| {
matches_filters(
&entry.quote_mint,
&entry.base_mint,
&entry.liquidity_provider,
filters,
)
})
.cloned()
.collect()
}
async fn fetch_mint_decimals<R: Rpc + ?Sized>(
rpc: &R,
mints: &[Pubkey],
) -> Result<HashMap<Pubkey, u8>> {
let mut decimals = HashMap::with_capacity(mints.len());
for chunk in mints.chunks(100) {
let accounts = rpc.get_multiple_accounts(chunk).await?;
if accounts.len() != chunk.len() {
return Err(SdkError::Rpc(
"Mint account response length does not match request".into(),
));
}
for (mint, account) in chunk.iter().zip(&accounts) {
let context = parse_mint_account_context(mint, account.as_ref())?;
decimals.insert(*mint, context.decimals);
}
}
Ok(decimals)
}
fn resolved_decimals(decimals: &HashMap<Pubkey, u8>, mint: &Pubkey) -> Result<u8> {
decimals.get(mint).copied().ok_or_else(|| {
SdkError::InvalidAccount(format!("Missing decimals for registry mint: {mint}"))
})
}
pub async fn discover_pairs<R: Rpc + ?Sized>(
rpc: &R,
program_id: &Pubkey,
filters: Option<&PairFilters>,
) -> Result<Vec<PairRegistryEntry>> {
let mut memcmp = vec![RpcFilter::Memcmp {
offset: PAIR_LAYOUT.discriminator_offset,
bytes: DISCRIMINATOR_PAIR.to_vec(),
}];
if let Some(filters) = filters {
for (mint, offset) in [
(filters.quote_mint, PAIR_LAYOUT.quote_mint_offset),
(filters.base_mint, PAIR_LAYOUT.base_mint_offset),
(
filters.liquidity_provider,
PAIR_LAYOUT.liquidity_provider_offset,
),
] {
if let Some(mint) = mint {
memcmp.push(RpcFilter::Memcmp {
offset,
bytes: mint.to_bytes().to_vec(),
});
}
}
}
let accounts = rpc.get_program_accounts(program_id, &memcmp).await?;
let mut pairs = Vec::with_capacity(accounts.len());
let mut mints = Vec::new();
let mut seen = HashSet::new();
for (address, account) in accounts {
if account.owner != *program_id || account.executable {
return Err(SdkError::InvalidAccount(format!(
"Invalid pair account owner or executable account: {address}"
)));
}
let pair = PairAccount::decode(&account.data).map_err(|error| {
SdkError::InvalidAccount(format!("Invalid pair account {address}: {error}"))
})?;
if pair.quote_token_mint_address == pair.base_token_mint_address {
return Err(SdkError::InvalidAccount(format!(
"Pair {address} must contain two different mints"
)));
}
for mint in [pair.quote_token_mint_address, pair.base_token_mint_address] {
if seen.insert(mint) {
mints.push(mint);
}
}
pairs.push((address, pair));
}
let decimals = fetch_mint_decimals(rpc, &mints).await?;
pairs
.into_iter()
.filter(|(_, pair)| {
matches_filters(
&pair.quote_token_mint_address,
&pair.base_token_mint_address,
&pair.liquidity_provider,
filters,
)
})
.map(|(pair, account)| {
Ok(PairRegistryEntry {
pair,
liquidity_provider: account.liquidity_provider,
vault_authority: None,
quote_mint: account.quote_token_mint_address,
base_mint: account.base_token_mint_address,
quote_decimals: resolved_decimals(&decimals, &account.quote_token_mint_address)?,
base_decimals: resolved_decimals(&decimals, &account.base_token_mint_address)?,
label: None,
})
})
.collect()
}
#[cfg(feature = "http")]
pub use api::get_pairs;
#[cfg(any(feature = "http", test))]
mod api {
use std::str::FromStr;
use serde_json::{Map, Value};
use super::*;
#[cfg(feature = "http")]
use crate::types::{PairRegistryErrorContext, PairRegistryFetchOptions};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum AssetKind {
Stable,
Rwa,
}
struct AssetMetadata {
decimals: Option<u8>,
kind: AssetKind,
}
#[derive(Debug)]
struct ApiPairCandidate {
pair: Pubkey,
liquidity_provider: Pubkey,
vault_authority: Pubkey,
quote_mint: Pubkey,
base_mint: Pubkey,
quote_decimals: Option<u8>,
base_decimals: Option<u8>,
label: String,
admin_name: String,
}
fn invalid(message: impl Into<String>) -> SdkError {
SdkError::InvalidInput(format!("Invalid SVM info response: {}", message.into()))
}
fn record<'a>(value: &'a Value, path: &str) -> Result<&'a Map<String, Value>> {
value
.as_object()
.ok_or_else(|| invalid(format!("{path} must be an object")))
}
fn array<'a>(record: &'a Map<String, Value>, key: &str, path: &str) -> Result<&'a [Value]> {
record
.get(key)
.and_then(Value::as_array)
.map(Vec::as_slice)
.ok_or_else(|| invalid(format!("{path}.{key} must be an array")))
}
fn string<'a>(record: &'a Map<String, Value>, key: &str, path: &str) -> Result<&'a str> {
record
.get(key)
.and_then(Value::as_str)
.filter(|value| !value.trim().is_empty())
.ok_or_else(|| invalid(format!("{path}.{key} must be a non-empty string")))
}
fn decimal(record: &Map<String, Value>, key: &str, path: &str) -> Result<Option<u8>> {
let Some(value) = record.get(key).filter(|value| !value.is_null()) else {
return Ok(None);
};
let number = value
.as_f64()
.filter(|number| number.fract() == 0.0 && (0.0..=255.0).contains(number))
.ok_or_else(|| {
invalid(format!(
"{path}.{key} must be an integer from 0 through 255"
))
})?;
Ok(Some(number as u8))
}
fn pubkey(value: &str) -> Result<Pubkey> {
Pubkey::from_str(value)
.map_err(|error| invalid(format!("Invalid public key {value}: {error}")))
}
fn asset_metadata(
deployment: &Map<String, Value>,
key: &str,
path: &str,
kind: AssetKind,
) -> Result<HashMap<Pubkey, AssetMetadata>> {
let mut metadata = HashMap::new();
for (index, value) in array(deployment, key, path)?.iter().enumerate() {
let path = format!("{path}.{key}[{index}]");
let asset = record(value, &path)?;
string(asset, "token", &path)?;
let mint = pubkey(string(asset, "mint_address", &path)?)?;
let decimals = decimal(asset, "decimals", &path)?;
if metadata
.insert(mint, AssetMetadata { decimals, kind })
.is_some()
{
return Err(invalid(format!("duplicate asset mint in {path}: {mint}")));
}
}
Ok(metadata)
}
fn metadata_for_mint<'a>(
mint: &Pubkey,
stable: &'a HashMap<Pubkey, AssetMetadata>,
rwa: &'a HashMap<Pubkey, AssetMetadata>,
) -> Result<&'a AssetMetadata> {
match (stable.get(mint), rwa.get(mint)) {
(Some(metadata), None) | (None, Some(metadata)) => Ok(metadata),
_ => Err(invalid(format!(
"mint {mint} must appear in exactly one asset metadata list"
))),
}
}
fn side_decimals(
side: Option<u8>,
stable: Option<u8>,
asset: Option<u8>,
metadata: &AssetMetadata,
other: &AssetMetadata,
) -> Option<u8> {
side.or_else(|| {
if metadata.kind == other.kind {
None
} else {
match metadata.kind {
AssetKind::Stable => stable,
AssetKind::Rwa => asset,
}
}
})
.or(metadata.decimals)
}
fn normalized_label(label: &str) -> String {
let mut parts = label.split('/').peekable();
let mut normalized = String::with_capacity(label.len());
let mut first = true;
while let Some(part) = parts.next() {
let part = if first { part } else { part.trim_start() };
let part = if parts.peek().is_some() {
part.trim_end()
} else {
part
};
if !first {
normalized.push_str(" / ");
}
normalized.push_str(part);
first = false;
}
normalized
}
fn parse_api_pair_candidates(raw: &Value, cluster: Cluster) -> Result<Vec<ApiPairCandidate>> {
let root = record(raw, "root")?;
let cluster = match cluster {
Cluster::Devnet => "devnet",
Cluster::MainnetBeta => "mainnet",
};
let deployment = record(root.get(cluster).unwrap_or(&Value::Null), cluster)?;
let stable = asset_metadata(deployment, "stable_assets", cluster, AssetKind::Stable)?;
let rwa = asset_metadata(deployment, "rwa_assets", cluster, AssetKind::Rwa)?;
let mut candidates = Vec::new();
for (index, value) in array(deployment, "lp_info", cluster)?.iter().enumerate() {
let path = format!("{cluster}.lp_info[{index}]");
let lp = record(value, &path)?;
let admin_name = string(lp, "admin_name", &path)?;
let admin_address = string(lp, "admin_address", &path)?;
let vault_authority = string(lp, "vault_authority", &path)?;
for (index, value) in array(lp, "pair_info", &path)?.iter().enumerate() {
let path = format!("{path}.pair_info[{index}]");
let pair = record(value, &path)?;
let label = normalized_label(string(pair, "pair_name", &path)?);
let pair_address = string(pair, "pair_address", &path)?;
let quote_mint = pubkey(string(pair, "mint_a", &path)?)?;
let base_mint = pubkey(string(pair, "mint_b", &path)?)?;
let quote_decimals = decimal(pair, "mint_a_decimals", &path)?;
let base_decimals = decimal(pair, "mint_b_decimals", &path)?;
let stable_decimals = decimal(pair, "stable_decimals", &path)?;
let asset_decimals = decimal(pair, "asset_decimals", &path)?;
if quote_mint == base_mint {
return Err(invalid(format!(
"pair {pair_address} must contain two different mints"
)));
}
let quote = metadata_for_mint("e_mint, &stable, &rwa)?;
let base = metadata_for_mint(&base_mint, &stable, &rwa)?;
candidates.push(ApiPairCandidate {
pair: pubkey(pair_address)?,
liquidity_provider: pubkey(admin_address)?,
vault_authority: pubkey(vault_authority)?,
quote_mint,
base_mint,
quote_decimals: side_decimals(
quote_decimals,
stable_decimals,
asset_decimals,
quote,
base,
),
base_decimals: side_decimals(
base_decimals,
stable_decimals,
asset_decimals,
base,
quote,
),
label,
admin_name: admin_name.to_owned(),
});
}
}
Ok(candidates)
}
static STATIC_MINT_DECIMALS: LazyLock<HashMap<Pubkey, u8>> = LazyLock::new(|| {
let mut decimals = HashMap::new();
for pair in DEVNET_PAIRS.iter().chain(MAINNET_PAIRS.iter()) {
decimals.insert(pair.quote_mint, pair.quote_decimals);
decimals.insert(pair.base_mint, pair.base_decimals);
}
decimals
});
async fn parse_api_pair_registry(
raw: &Value,
cluster: Cluster,
rpc: Option<&dyn Rpc>,
) -> Result<Vec<PairRegistryEntry>> {
let candidates = parse_api_pair_candidates(raw, cluster)?;
let mut decimals = HashMap::new();
let mut missing = Vec::new();
let mut seen_missing = HashSet::new();
for candidate in &candidates {
for (mint, supplied) in [
(candidate.quote_mint, candidate.quote_decimals),
(candidate.base_mint, candidate.base_decimals),
] {
if decimals.contains_key(&mint) {
continue;
}
if let Some(value) = supplied.or_else(|| STATIC_MINT_DECIMALS.get(&mint).copied()) {
decimals.insert(mint, value);
} else if seen_missing.insert(mint) {
missing.push(mint);
}
}
}
missing.retain(|mint| !decimals.contains_key(mint));
if !missing.is_empty() {
let rpc = rpc.ok_or_else(|| invalid("A Solana RPC is required to fetch decimals for API registry mints not bundled statically"))?;
decimals.extend(fetch_mint_decimals(rpc, &missing).await?);
}
let mut seen_labels = HashSet::new();
candidates
.into_iter()
.map(|candidate| {
let label = if seen_labels.insert(candidate.label.clone()) {
candidate.label
} else {
format!("{} ({})", candidate.label, candidate.admin_name)
};
Ok(PairRegistryEntry {
pair: candidate.pair,
liquidity_provider: candidate.liquidity_provider,
vault_authority: Some(candidate.vault_authority),
quote_mint: candidate.quote_mint,
base_mint: candidate.base_mint,
quote_decimals: resolved_decimals(&decimals, &candidate.quote_mint)?,
base_decimals: resolved_decimals(&decimals, &candidate.base_mint)?,
label: Some(label),
})
})
.collect()
}
#[cfg(feature = "http")]
fn build_svm_info_url(base: &str) -> Result<reqwest::Url> {
let mut url = reqwest::Url::parse(base).map_err(|error| {
SdkError::InvalidInput(format!("Invalid registry API URL: {error}"))
})?;
match url.path().trim_end_matches('/') {
"" | "/v1/info/svm" => url.set_path("/v1/info/svm"),
_ => {
return Err(SdkError::InvalidInput(
"registryApiUrl must be an API base URL or /v1/info/svm endpoint".into(),
))
}
}
Ok(url)
}
#[cfg(feature = "http")]
fn fetch_error(error: reqwest::Error, timeout_ms: u64) -> SdkError {
if error.is_timeout() {
SdkError::Rpc(format!("SVM registry fetch timed out after {timeout_ms}ms"))
} else {
SdkError::Rpc(format!("SVM info request failed: {error}"))
}
}
#[cfg(feature = "http")]
async fn fetch_api_pair_registry(
cluster: Cluster,
base_url: &str,
options: &PairRegistryFetchOptions,
) -> Result<Vec<PairRegistryEntry>> {
let url = build_svm_info_url(base_url)?;
let client = reqwest::Client::builder()
.build()
.map_err(|error| SdkError::Rpc(error.to_string()))?;
let mut request = client
.get(url)
.header(reqwest::header::ACCEPT, "application/json");
let timeout_ms = options
.timeout_ms
.unwrap_or(DEFAULT_REGISTRY_FETCH_TIMEOUT_MS);
if timeout_ms > 0 {
request = request.timeout(std::time::Duration::from_millis(timeout_ms));
}
let response = request
.send()
.await
.map_err(|error| fetch_error(error, timeout_ms))?;
if !response.status().is_success() {
return Err(SdkError::Rpc(format!(
"SVM info request failed with status {}",
response.status()
)));
}
let raw = response
.json::<Value>()
.await
.map_err(|error| fetch_error(error, timeout_ms))?;
parse_api_pair_registry(&raw, cluster, options.rpc.as_deref()).await
}
#[cfg(feature = "http")]
fn report_fallback(
error: &SdkError,
cluster: Cluster,
base_url: &str,
options: &PairRegistryFetchOptions,
) {
if let Some(callback) = &options.on_error {
let context = PairRegistryErrorContext {
cluster,
registry_api_url: base_url.to_owned(),
};
if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| callback(error, &context)))
.is_ok()
{
return;
}
eprintln!("[multiliquid-svm-sdk] SVM registry onError handler failed.");
}
eprintln!("[multiliquid-svm-sdk] Failed to fetch API-backed SVM pair registry; falling back to static registry: {error}");
}
#[cfg(feature = "http")]
pub async fn get_pairs(
cluster: Cluster,
filters: Option<&PairFilters>,
options: &PairRegistryFetchOptions,
) -> Result<Vec<PairRegistryEntry>> {
let base_url = options
.registry_api_url
.as_deref()
.unwrap_or(DEFAULT_REGISTRY_API_URL);
match fetch_api_pair_registry(cluster, base_url, options).await {
Ok(pairs) => Ok(pairs
.into_iter()
.filter(|entry| {
matches_filters(
&entry.quote_mint,
&entry.base_mint,
&entry.liquidity_provider,
filters,
)
})
.collect()),
Err(error) => {
report_fallback(&error, cluster, base_url, options);
Ok(get_offline_pairs(cluster, filters))
}
}
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::*;
use crate::registry::tests::{key, mint, RegistryRpc};
fn deployment(quote: Pubkey, base: Pubkey) -> Value {
json!({
"devnet": {
"stable_assets": [{"token": "STABLE", "mint_address": quote.to_string()}],
"rwa_assets": [{"token": "RWA", "mint_address": base.to_string()}],
"lp_info": [{
"admin_name": "Uniform",
"admin_address": key(10).to_string(),
"vault_authority": key(11).to_string(),
"pair_info": [{
"pair_name": "STABLE/RWA",
"pair_address": key(12).to_string(),
"mint_a": quote.to_string(),
"mint_b": base.to_string()
}]
}]
}
})
}
#[tokio::test]
async fn legacy_metadata_uses_bundled_decimals_without_sorting_or_losing_duplicate_lps() {
let known = &DEVNET_PAIRS[0];
let mut raw = deployment(known.quote_mint, known.base_mint);
let mut duplicate = raw["devnet"]["lp_info"][0].clone();
duplicate["admin_name"] = json!("Metalayer");
duplicate["admin_address"] = json!(key(20).to_string());
duplicate["pair_info"][0]["pair_address"] = json!(key(21).to_string());
raw["devnet"]["lp_info"]
.as_array_mut()
.unwrap()
.push(duplicate);
let pairs = parse_api_pair_registry(&raw, Cluster::Devnet, None)
.await
.unwrap();
assert_eq!(pairs[0].quote_mint, known.quote_mint);
assert_eq!(pairs[0].base_mint, known.base_mint);
assert!(pairs[0].quote_mint.to_bytes() > pairs[0].base_mint.to_bytes());
assert_eq!((pairs[0].quote_decimals, pairs[0].base_decimals), (6, 9));
assert_eq!(pairs[0].label.as_deref(), Some("STABLE / RWA"));
assert_eq!(pairs[1].label.as_deref(), Some("STABLE / RWA (Metalayer)"));
assert_eq!(pairs[1].liquidity_provider, key(20));
assert_eq!(pairs[0].vault_authority, Some(key(11)));
let mainnet = json!({"mainnet": raw["devnet"]});
assert_eq!(
parse_api_pair_registry(&mainnet, Cluster::MainnetBeta, None)
.await
.unwrap(),
pairs
);
}
#[tokio::test]
async fn side_decimals_precede_semantic_and_asset_decimals_in_either_orientation() {
let mut raw = deployment(key(201), key(202));
raw["devnet"]["stable_assets"][0]["decimals"] = json!(6.0);
raw["devnet"]["rwa_assets"][0]["decimals"] = json!(9);
let pair = &mut raw["devnet"]["lp_info"][0]["pair_info"][0];
pair["stable_decimals"] = json!(7);
pair["asset_decimals"] = json!(8);
pair["mint_a_decimals"] = json!(0);
pair["mint_b_decimals"] = json!(255);
let pairs = parse_api_pair_registry(&raw, Cluster::Devnet, None)
.await
.unwrap();
assert_eq!((pairs[0].quote_decimals, pairs[0].base_decimals), (0, 255));
let pair = &mut raw["devnet"]["lp_info"][0]["pair_info"][0];
pair["mint_a_decimals"] = Value::Null;
pair["mint_b_decimals"] = Value::Null;
let pairs = parse_api_pair_registry(&raw, Cluster::Devnet, None)
.await
.unwrap();
assert_eq!((pairs[0].quote_decimals, pairs[0].base_decimals), (7, 8));
let pair = &mut raw["devnet"]["lp_info"][0]["pair_info"][0];
pair["mint_a"] = json!(key(202).to_string());
pair["mint_b"] = json!(key(201).to_string());
let pairs = parse_api_pair_registry(&raw, Cluster::Devnet, None)
.await
.unwrap();
assert_eq!((pairs[0].quote_decimals, pairs[0].base_decimals), (8, 7));
assert_eq!(
(pairs[0].quote_mint, pairs[0].base_mint),
(key(202), key(201))
);
}
#[tokio::test]
async fn same_kind_pairs_ignore_ambiguous_semantic_decimals() {
for kind in ["rwa_assets", "stable_assets"] {
let mut raw = deployment(key(201), key(202));
raw["devnet"]["stable_assets"] = json!([]);
raw["devnet"]["rwa_assets"] = json!([]);
raw["devnet"][kind] = json!([
{"token": "A", "mint_address": key(201).to_string(), "decimals": 7},
{"token": "B", "mint_address": key(202).to_string(), "decimals": 9}
]);
let pair = &mut raw["devnet"]["lp_info"][0]["pair_info"][0];
pair["stable_decimals"] = json!(3);
pair["asset_decimals"] = json!(4);
pair["pair_name"] = json!(" A /B ");
let pairs = parse_api_pair_registry(&raw, Cluster::Devnet, None)
.await
.unwrap();
assert_eq!((pairs[0].quote_decimals, pairs[0].base_decimals), (7, 9));
assert_eq!(pairs[0].label.as_deref(), Some(" A / B "));
raw["devnet"]["lp_info"][0]["pair_info"][0]["mint_b_decimals"] = json!(5);
let pairs = parse_api_pair_registry(&raw, Cluster::Devnet, None)
.await
.unwrap();
assert_eq!((pairs[0].quote_decimals, pairs[0].base_decimals), (7, 5));
raw["devnet"][kind][0]["decimals"] = Value::Null;
assert!(parse_api_pair_registry(&raw, Cluster::Devnet, None)
.await
.is_err());
}
}
#[test]
fn metadata_rejects_ambiguous_missing_and_malformed_asset_definitions() {
let raw = deployment(key(201), key(202));
let mut missing = raw.clone();
missing["devnet"]["rwa_assets"] = json!([]);
let mut ambiguous = raw.clone();
ambiguous["devnet"]["stable_assets"]
.as_array_mut()
.unwrap()
.push(raw["devnet"]["rwa_assets"][0].clone());
let mut duplicate = raw.clone();
duplicate["devnet"]["stable_assets"]
.as_array_mut()
.unwrap()
.push(raw["devnet"]["stable_assets"][0].clone());
let mut same_mint = raw.clone();
same_mint["devnet"]["lp_info"][0]["pair_info"][0]["mint_b"] =
json!(key(201).to_string());
let mut bad_key = raw.clone();
bad_key["devnet"]["lp_info"][0]["admin_address"] = json!("not-an-address");
let mut blank = raw.clone();
blank["devnet"]["lp_info"][0]["admin_name"] = json!(" ");
for invalid in [
missing,
ambiguous,
duplicate,
same_mint,
bad_key,
blank,
Value::Null,
json!({"devnet": {"lp_info": []}}),
] {
assert!(matches!(
parse_api_pair_candidates(&invalid, Cluster::Devnet),
Err(SdkError::InvalidInput(_))
));
}
for decimals in [json!(-1), json!(256), json!(6.5), json!("6"), json!(true)] {
let mut invalid = raw.clone();
invalid["devnet"]["rwa_assets"][0]["decimals"] = decimals.clone();
assert!(parse_api_pair_candidates(&invalid, Cluster::Devnet).is_err());
invalid = raw.clone();
invalid["devnet"]["lp_info"][0]["pair_info"][0]["mint_a_decimals"] = json!(6);
invalid["devnet"]["lp_info"][0]["pair_info"][0]["stable_decimals"] = decimals;
assert!(parse_api_pair_candidates(&invalid, Cluster::Devnet).is_err());
}
}
#[tokio::test]
async fn missing_decimals_require_rpc_and_batch_only_unknown_mints() {
let stable = DEVNET_PAIRS[0].quote_mint;
let raw = deployment(stable, key(201));
assert!(matches!(
parse_api_pair_registry(&raw, Cluster::Devnet, None).await,
Err(SdkError::InvalidInput(_))
));
let empty_rpc = RegistryRpc::default();
assert!(matches!(
parse_api_pair_registry(&raw, Cluster::Devnet, Some(&empty_rpc)).await,
Err(SdkError::AccountNotFound(address)) if address == key(201)
));
let mut raw = raw;
raw["devnet"]["rwa_assets"] = json!([]);
raw["devnet"]["lp_info"][0]["pair_info"] = json!([]);
let mut rpc = RegistryRpc::default();
let mut expected_mints = Vec::new();
for index in 0..101_u8 {
let address = key(index + 100);
expected_mints.push(address);
rpc.accounts.insert(address, mint(index));
raw["devnet"]["rwa_assets"]
.as_array_mut()
.unwrap()
.push(json!({
"token": "NEW", "mint_address": address.to_string()
}));
raw["devnet"]["lp_info"][0]["pair_info"]
.as_array_mut()
.unwrap()
.push(json!({
"pair_name": "STABLE/NEW", "pair_address": key(12).to_string(),
"mint_a": address.to_string(), "mint_b": stable.to_string()
}));
}
let pairs = parse_api_pair_registry(&raw, Cluster::Devnet, Some(&rpc))
.await
.unwrap();
assert_eq!(
pairs
.iter()
.map(|pair| (pair.quote_mint, pair.quote_decimals, pair.base_decimals))
.collect::<Vec<_>>(),
expected_mints
.iter()
.enumerate()
.map(|(index, mint)| (*mint, index as u8, 6))
.collect::<Vec<_>>()
);
assert_eq!(
*rpc.mint_requests.lock(),
vec![
expected_mints[..100].to_vec(),
expected_mints[100..].to_vec()
]
);
}
#[tokio::test]
async fn later_metadata_can_resolve_a_missing_decimal_but_never_overrides_a_resolved_one() {
let mut raw = deployment(key(201), key(202));
raw["devnet"]["rwa_assets"][0]["decimals"] = json!(9);
let first = raw["devnet"]["lp_info"][0]["pair_info"][0].clone();
let mut second = first.clone();
second["mint_a_decimals"] = json!(7);
let mut third = first;
third["mint_a_decimals"] = json!(3);
raw["devnet"]["lp_info"][0]["pair_info"]
.as_array_mut()
.unwrap()
.extend([second, third]);
let pairs = parse_api_pair_registry(&raw, Cluster::Devnet, None)
.await
.unwrap();
assert_eq!(
pairs
.iter()
.map(|pair| pair.quote_decimals)
.collect::<Vec<_>>(),
[7, 7, 7]
);
}
#[cfg(feature = "http")]
mod http {
use parking_lot::Mutex;
use std::{
io::{BufRead, BufReader, Read, Write},
net::TcpListener,
sync::{
atomic::{AtomicUsize, Ordering},
mpsc, Arc,
},
thread::{self, JoinHandle},
time::Duration,
};
use super::*;
fn server(
status: u16,
body: Option<String>,
) -> (String, mpsc::Receiver<()>, JoinHandle<String>) {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let url = format!("http://{}", listener.local_addr().unwrap());
let (ready, received) = mpsc::channel();
let task = thread::spawn(move || {
let (mut stream, _) = listener.accept().unwrap();
stream
.set_read_timeout(Some(Duration::from_secs(5)))
.unwrap();
let mut reader = BufReader::new(stream.try_clone().unwrap());
let mut request = String::new();
loop {
let mut line = String::new();
assert_ne!(reader.read_line(&mut line).unwrap(), 0);
let done = line == "\r\n";
request.push_str(&line);
if done {
break;
}
}
let _ = ready.send(());
if let Some(body) = body {
write!(stream, "HTTP/1.1 {status} Test\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()).unwrap();
} else {
let mut remaining = Vec::new();
let _ = reader.read_to_end(&mut remaining);
}
request
});
(url, received, task)
}
#[tokio::test]
async fn http_normalizes_urls_and_does_not_fallback_on_valid_empty_results() {
for input in [
"https://example.test",
"https://example.test///",
"https://example.test/v1/info/svm///",
] {
assert_eq!(
build_svm_info_url(input).unwrap().as_str(),
"https://example.test/v1/info/svm"
);
}
assert_eq!(
build_svm_info_url("https://example.test/?a=1#fragment")
.unwrap()
.as_str(),
"https://example.test/v1/info/svm?a=1#fragment"
);
assert!(build_svm_info_url("https://example.test/other").is_err());
let raw = json!({"devnet": {"stable_assets": [], "rwa_assets": [], "lp_info": []}});
let (url, _, task) = server(200, Some(raw.to_string()));
let options = PairRegistryFetchOptions {
registry_api_url: Some(format!("{url}/v1/info/svm/?a=1")),
timeout_ms: Some(0),
on_error: Some(Arc::new(|_, _| {
panic!("valid empty metadata must not fall back")
})),
..PairRegistryFetchOptions::default()
};
assert!(get_pairs(Cluster::Devnet, None, &options)
.await
.unwrap()
.is_empty());
let request = task.join().unwrap().to_ascii_lowercase();
assert!(request.starts_with("get /v1/info/svm?a=1 http/1.1\r\n"));
assert!(request.contains("\r\naccept: application/json\r\n"));
}
#[tokio::test]
async fn http_returns_filtered_api_pairs_instead_of_static_entries() {
let known = &DEVNET_PAIRS[0];
let mut raw = deployment(known.quote_mint, known.base_mint);
let mut second = raw["devnet"]["lp_info"][0].clone();
second["admin_name"] = json!("Metalayer");
second["admin_address"] = json!(key(20).to_string());
second["pair_info"][0]["pair_address"] = json!(key(21).to_string());
raw["devnet"]["lp_info"]
.as_array_mut()
.unwrap()
.push(second);
let (url, _, task) = server(200, Some(raw.to_string()));
let options = PairRegistryFetchOptions {
registry_api_url: Some(url),
..PairRegistryFetchOptions::default()
};
let filters = PairFilters {
quote_mint: Some(known.quote_mint),
base_mint: Some(known.base_mint),
liquidity_provider: Some(key(20)),
};
let pairs = get_pairs(Cluster::Devnet, Some(&filters), &options)
.await
.unwrap();
task.join().unwrap();
assert_eq!(
pairs,
vec![PairRegistryEntry {
pair: key(21),
liquidity_provider: key(20),
vault_authority: Some(key(11)),
quote_mint: known.quote_mint,
base_mint: known.base_mint,
quote_decimals: 6,
base_decimals: 9,
label: Some("STABLE / RWA (Metalayer)".into()),
}]
);
}
#[tokio::test]
async fn http_metadata_rejection_and_transport_failures_report_then_apply_offline_filters(
) {
let mut invalid = deployment(DEVNET_PAIRS[0].quote_mint, DEVNET_PAIRS[0].base_mint);
invalid["devnet"]["rwa_assets"] = json!([]);
let filters = PairFilters {
liquidity_provider: Some(DEVNET_PAIRS[3].liquidity_provider),
..PairFilters::default()
};
for (status, body, metadata_error) in [
(200, invalid.to_string(), true),
(503, "{}".into(), false),
(200, "not-json".into(), false),
(200, deployment(key(201), key(202)).to_string(), true),
] {
let (url, _, task) = server(status, Some(body));
let failures = Arc::new(Mutex::new(Vec::new()));
let captured = failures.clone();
let options = PairRegistryFetchOptions {
registry_api_url: Some(url.clone()),
on_error: Some(Arc::new(move |error, context| {
captured
.lock()
.push((matches!(error, SdkError::InvalidInput(_)), context.clone()))
})),
..PairRegistryFetchOptions::default()
};
assert_eq!(
get_pairs(Cluster::Devnet, Some(&filters), &options)
.await
.unwrap(),
vec![DEVNET_PAIRS[3].clone()]
);
task.join().unwrap();
let failures = failures.lock();
assert_eq!(failures.len(), 1);
assert_eq!(
failures[0].1,
PairRegistryErrorContext {
cluster: Cluster::Devnet,
registry_api_url: url
}
);
assert_eq!(failures[0].0, metadata_error);
}
let options = PairRegistryFetchOptions {
registry_api_url: Some("https://example.test/not-the-api".into()),
on_error: Some(Arc::new(|_, _| panic!("observer failed"))),
..PairRegistryFetchOptions::default()
};
assert_eq!(
get_pairs(Cluster::Devnet, Some(&filters), &options)
.await
.unwrap(),
vec![DEVNET_PAIRS[3].clone()]
);
}
#[tokio::test]
async fn http_timeouts_fallback_but_caller_cancellation_does_not() {
let failures = Arc::new(AtomicUsize::new(0));
let captured = failures.clone();
let (url, _, task) = server(200, None);
let options = PairRegistryFetchOptions {
registry_api_url: Some(url),
timeout_ms: Some(500),
on_error: Some(Arc::new(move |_, _| {
captured.fetch_add(1, Ordering::SeqCst);
})),
..PairRegistryFetchOptions::default()
};
assert_eq!(
get_pairs(Cluster::Devnet, None, &options).await.unwrap(),
get_offline_pairs(Cluster::Devnet, None)
);
tokio::task::spawn_blocking(move || task.join().unwrap())
.await
.unwrap();
assert_eq!(failures.load(Ordering::SeqCst), 1);
let (url, received, task) = server(200, None);
let options = PairRegistryFetchOptions {
registry_api_url: Some(url),
timeout_ms: Some(0),
..options
};
let fetch =
tokio::spawn(async move { get_pairs(Cluster::Devnet, None, &options).await });
tokio::task::spawn_blocking(move || {
received.recv_timeout(Duration::from_secs(5)).unwrap()
})
.await
.unwrap();
fetch.abort();
assert!(fetch.await.unwrap_err().is_cancelled());
tokio::task::spawn_blocking(move || task.join().unwrap())
.await
.unwrap();
assert_eq!(failures.load(Ordering::SeqCst), 1);
}
}
}
}
#[cfg(test)]
mod tests {
use parking_lot::Mutex;
use async_trait::async_trait;
use solana_sdk::{account::Account, hash::Hash, transaction::VersionedTransaction};
use super::*;
use crate::{constants::SPL_TOKEN_PROGRAM_ADDRESS, rpc::SimulationResult};
pub(super) fn key(byte: u8) -> Pubkey {
Pubkey::new_from_array([byte; 32])
}
pub(super) fn mint(decimals: u8) -> Account {
let mut data = vec![0; 82];
data[44] = decimals;
data[45] = 1;
Account {
data,
owner: SPL_TOKEN_PROGRAM_ADDRESS,
..Account::default()
}
}
fn pair_account(program: Pubkey, quote: Pubkey, base: Pubkey, lp: Pubkey) -> Account {
let pair = PairAccount {
redemption_fee_bps: 0,
discount_rate_bps: 0,
quote_token_mint_address: quote,
base_token_mint_address: base,
liquidity_provider: lp,
paused: false,
bump: 0,
padding: [0; 128],
};
Account {
data: pair.encode().unwrap(),
owner: program,
..Account::default()
}
}
#[derive(Default)]
pub(super) struct RegistryRpc {
pub(super) accounts: HashMap<Pubkey, Account>,
pub(super) programs: Vec<(Pubkey, Account)>,
pub(super) mint_requests: Mutex<Vec<Vec<Pubkey>>>,
pub(super) program_requests: Mutex<Vec<(Pubkey, Vec<RpcFilter>)>>,
}
#[async_trait]
impl Rpc for RegistryRpc {
async fn get_account(&self, address: &Pubkey) -> Result<Option<Account>> {
Ok(self.accounts.get(address).cloned())
}
async fn get_multiple_accounts(
&self,
addresses: &[Pubkey],
) -> Result<Vec<Option<Account>>> {
if addresses.len() > 100 {
return Err(SdkError::Rpc(
"getMultipleAccounts accepts at most 100 keys".into(),
));
}
self.mint_requests.lock().push(addresses.to_vec());
Ok(addresses
.iter()
.map(|address| self.accounts.get(address).cloned())
.collect())
}
async fn get_program_accounts(
&self,
program_id: &Pubkey,
filters: &[RpcFilter],
) -> Result<Vec<(Pubkey, Account)>> {
self.program_requests
.lock()
.push((*program_id, filters.to_vec()));
Ok(self.programs.clone())
}
async fn get_slot(&self) -> Result<u64> {
unreachable!()
}
async fn get_block_time(&self, _: u64) -> Result<Option<i64>> {
unreachable!()
}
async fn get_latest_blockhash(&self) -> Result<Hash> {
unreachable!()
}
async fn get_transaction_logs(&self, _: &str) -> Result<Option<Vec<String>>> {
unreachable!()
}
async fn simulate_transaction(&self, _: &VersionedTransaction) -> Result<SimulationResult> {
unreachable!()
}
}
#[test]
fn offline_manifest_keeps_deployed_order_and_filters_all_sides() {
let devnet = get_offline_pairs(Cluster::Devnet, None);
assert_eq!(devnet.len(), 4);
assert_eq!(
devnet[0].pair.to_string(),
"CFdG1zintcNbQjGwUJ4ZJb86Ais7NucmGuXjGniZsNCV"
);
assert!(devnet[0].quote_mint.to_bytes() > devnet[0].base_mint.to_bytes());
assert_eq!((devnet[0].quote_decimals, devnet[0].base_decimals), (6, 9));
let filter = PairFilters {
quote_mint: Some(devnet[0].quote_mint),
base_mint: Some(devnet[0].base_mint),
liquidity_provider: Some(devnet[3].liquidity_provider),
};
assert_eq!(
get_offline_pairs(Cluster::Devnet, Some(&filter)),
vec![devnet[3].clone()]
);
let reversed = PairFilters {
quote_mint: filter.base_mint,
base_mint: filter.quote_mint,
liquidity_provider: None,
};
assert!(get_offline_pairs(Cluster::Devnet, Some(&reversed)).is_empty());
let mainnet = get_offline_pairs(Cluster::MainnetBeta, None);
assert_eq!(
mainnet
.iter()
.map(|entry| entry.label.as_deref().unwrap())
.collect::<Vec<_>>(),
[
"USDC / ACRED",
"USDC / BENJI",
"USDC / USTB",
"USDC / WTGXX",
"USDC / USCC",
"USDC / VBILL",
"USDC / WTGXX (Metalayer)",
"USDC / USTB (Metalayer)",
"USDC / USCC (Metalayer)",
]
);
assert_eq!(
MAINNET_RWA_TRANSFER_HOOKS
.iter()
.map(|hook| hook.label.as_deref().unwrap())
.collect::<Vec<_>>(),
["ACRED", "BENJI", "WTGXX", "VBILL",]
);
let hook = get_mainnet_rwa_transfer_hook(&mainnet[3].base_mint).unwrap();
assert_eq!(
hook.hook_program.to_string(),
"F4wFSShcdmaHWGRRXhCHinNTt8spgdh26Wi8hbN2Rzbh"
);
assert_eq!(
hook.extra_account_meta_list.to_string(),
"Jispa3UhmCTTKjJMmVAqrTqGD2YhU5BiJLxENSMkeJe"
);
assert!(get_mainnet_rwa_transfer_hook(&mainnet[2].base_mint).is_none());
}
#[tokio::test]
async fn discovery_filters_stored_sides_and_deduplicates_mints() {
let (program, quote, base, other, lp) = (key(1), key(250), key(2), key(3), key(4));
let rpc = RegistryRpc {
accounts: [(quote, mint(8)), (base, mint(6)), (other, mint(9))].into(),
programs: vec![
(key(10), pair_account(program, quote, base, lp)),
(key(11), pair_account(program, quote, other, lp)),
],
..RegistryRpc::default()
};
let filters = PairFilters {
quote_mint: Some(quote),
base_mint: Some(base),
liquidity_provider: Some(lp),
};
let pairs = discover_pairs(&rpc, &program, Some(&filters))
.await
.unwrap();
assert_eq!(
pairs,
vec![PairRegistryEntry {
pair: key(10),
liquidity_provider: lp,
vault_authority: None,
quote_mint: quote,
base_mint: base,
quote_decimals: 8,
base_decimals: 6,
label: None,
}]
);
assert_eq!(*rpc.mint_requests.lock(), vec![vec![quote, base, other]]);
assert_eq!(
*rpc.program_requests.lock(),
vec![(
program,
vec![
RpcFilter::Memcmp {
offset: 0,
bytes: DISCRIMINATOR_PAIR.to_vec()
},
RpcFilter::Memcmp {
offset: 12,
bytes: quote.to_bytes().to_vec()
},
RpcFilter::Memcmp {
offset: 44,
bytes: base.to_bytes().to_vec()
},
RpcFilter::Memcmp {
offset: 76,
bytes: lp.to_bytes().to_vec()
},
]
)]
);
let empty = RegistryRpc::default();
assert!(discover_pairs(&empty, &program, Some(&filters))
.await
.unwrap()
.is_empty());
assert!(empty.mint_requests.lock().is_empty());
}
#[tokio::test]
async fn discovery_rejects_untrusted_pairs_and_mint_accounts() {
let (program, quote, base, lp) = (key(1), key(2), key(3), key(4));
let valid = pair_account(program, quote, base, lp);
let mut wrong_owner = valid.clone();
wrong_owner.owner = key(99);
let mut wrong_discriminator = valid.clone();
wrong_discriminator.data[0] ^= 1;
let mut truncated = valid.clone();
truncated.data.pop();
let mut executable = valid.clone();
executable.executable = true;
for invalid in [
wrong_owner,
wrong_discriminator,
truncated,
executable,
pair_account(program, quote, quote, lp),
] {
let rpc = RegistryRpc {
programs: vec![(key(10), invalid)],
..RegistryRpc::default()
};
assert!(matches!(
discover_pairs(&rpc, &program, None).await,
Err(SdkError::InvalidAccount(_))
));
assert!(rpc.mint_requests.lock().is_empty());
}
let mut rpc = RegistryRpc {
programs: vec![(key(10), valid)],
accounts: [(base, mint(9))].into(),
..RegistryRpc::default()
};
assert!(
matches!(discover_pairs(&rpc, &program, None).await, Err(SdkError::AccountNotFound(address)) if address == quote)
);
let mut bad_mint = mint(6);
bad_mint.owner = key(99);
rpc.accounts.insert(quote, bad_mint);
assert!(matches!(
discover_pairs(&rpc, &program, None).await,
Err(SdkError::InvalidAccount(_))
));
let mut short_mint = mint(6);
short_mint.data.truncate(81);
rpc.accounts.insert(quote, short_mint);
assert!(matches!(
discover_pairs(&rpc, &program, None).await,
Err(SdkError::InvalidAccount(_))
));
}
}