Files
khadhroony-solana-project/crates/ksp-onchain-transport-lib/unit_tests/rpc_tokens.rs
2026-08-18 08:09:20 +02:00

258 lines
14 KiB
Rust

// file: crates/ksp-onchain-transport-lib/unit_tests/rpc_tokens.rs
// version: 3
#[test]
fn token_selector_is_exclusive_by_construction() {
let mint = "11111111111111111111111111111111".parse::<ksp_core_lib::Pubkey>().expect("fixture pubkey must parse");
assert_eq!(crate::SolanaTokenAccountSelector::Mint(mint).to_json_value(), serde_json::json!({"mint":"11111111111111111111111111111111"}));
assert_eq!(crate::SolanaTokenAccountSelector::ProgramId(mint).to_json_value(), serde_json::json!({"programId":"11111111111111111111111111111111"}));
}
#[test]
fn token_amount_fixture_preserves_nullable_ui_amount() {
let value: serde_json::Value = serde_json::from_str(include_str!("../fixtures/http/token_amount.null_ui.json")).expect("fixture must decode");
let amount = crate::SolanaTokenAmount::decode_wire("fixture", value).expect("token amount must decode");
assert_eq!(amount.amount(), "18446744073709551615");
assert_eq!(amount.decimals(), 9);
assert_eq!(amount.ui_amount(), std::option::Option::None);
assert_eq!(amount.ui_amount_string(), "18446744073.709551615");
}
#[test]
fn staged_token_account_balance_helper_preserves_address_and_amount() {
let value = serde_json::json!({
"address":"11111111111111111111111111111111",
"amount":"10",
"decimals":2,
"uiAmount":0.1,
"uiAmountString":"0.1"
});
let balance = crate::SolanaTokenAccountBalance::decode_wire("fixture", value).expect("token account balance must decode");
assert_eq!(balance.address().to_string(), "11111111111111111111111111111111");
assert_eq!(balance.amount().amount(), "10");
}
fn pool_for_url(url: &str) -> crate::HttpTransportPool {
let role = crate::HttpEndpointRoleSettings::new(
crate::HttpRoleName::new("default"),
true,
std::vec![crate::HttpRequestKind::wildcard()],
10,
crate::HttpRoleLimits::new(std::option::Option::None, std::option::Option::None, std::option::Option::None, std::option::Option::None),
);
let endpoint = crate::HttpEndpointSettings::new(
"fixture",
true,
crate::HttpProviderName::new("fixture"),
crate::HttpClusterName::new("local"),
crate::HttpEndpointUrl::parse(url).expect("fixture URL must parse"),
std::time::Duration::from_secs(1),
std::time::Duration::from_secs(1),
std::option::Option::Some(1),
std::vec![role],
);
let settings = crate::HttpTransportSettings::new(
std::vec![endpoint],
crate::HttpRetrySettings::new(0, std::time::Duration::from_millis(1), std::time::Duration::from_millis(1)),
);
return crate::HttpTransportPool::new(settings).expect("fixture pool must build");
}
fn serve_once(body: &'static str) -> (std::string::String, std::thread::JoinHandle<std::string::String>) {
let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("fixture listener must bind");
let address = listener.local_addr().expect("fixture listener address must resolve");
let handle = std::thread::spawn(move || {
let (mut stream, _) = listener.accept().expect("fixture server must accept one request");
let request = read_request(&mut stream);
let response = format!("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", body.len(), body);
std::io::Write::write_all(&mut stream, response.as_bytes()).expect("fixture response must write");
return request;
});
return (format!("http://{address}"), handle);
}
fn read_request(stream: &mut std::net::TcpStream) -> std::string::String {
let mut bytes = std::vec::Vec::new();
let mut buffer = [0_u8; 1024];
loop {
let count = std::io::Read::read(stream, &mut buffer).expect("fixture request must read");
if count == 0 {
break;
}
bytes.extend_from_slice(&buffer[..count]);
if request_complete(bytes.as_slice()) {
break;
}
}
return std::string::String::from_utf8(bytes).expect("fixture request must be UTF-8");
}
fn request_complete(bytes: &[u8]) -> bool {
let text = match std::str::from_utf8(bytes) {
std::result::Result::Ok(text) => text,
std::result::Result::Err(_) => return false,
};
let header_end = match text.find("\r\n\r\n") {
std::option::Option::Some(value) => value,
std::option::Option::None => return false,
};
let mut content_length = 0_usize;
for line in text[..header_end].lines() {
let (name, value) = match line.split_once(':') {
std::option::Option::Some(parts) => parts,
std::option::Option::None => continue,
};
if name.eq_ignore_ascii_case("content-length") {
content_length = value.trim().parse::<usize>().expect("content length must parse");
}
}
return bytes.len() >= header_end.saturating_add(4).saturating_add(content_length);
}
fn request_body(request: &str) -> serde_json::Value {
let body = request.split("\r\n\r\n").nth(1).expect("fixture request body must exist");
return serde_json::from_str(body).expect("fixture request body must be JSON");
}
fn fixture_pubkey(value: &str) -> ksp_core_lib::Pubkey {
return value.parse::<ksp_core_lib::Pubkey>().expect("fixture pubkey must parse");
}
#[tokio::test(flavor = "current_thread")]
async fn typed_get_token_account_balance_serializes_commitment_and_preserves_nullable_ui_amount() {
let (url, handle) = serve_once(include_str!("../fixtures/http/get_token_account_balance.success.json"));
let pool = pool_for_url(url.as_str());
let account = fixture_pubkey("11111111111111111111111111111111");
let config = crate::SolanaCommitmentConfig::new(std::option::Option::Some(crate::SolanaCommitment::Finalized));
let response = pool
.get_token_account_balance(&crate::HttpRoleName::new("default"), &account, std::option::Option::Some(&config))
.await
.expect("token balance fixture must succeed");
assert_eq!(response.context().slot(), 420_000_001);
assert_eq!(response.value().amount(), "18446744073709551615");
assert_eq!(response.value().ui_amount(), std::option::Option::None);
let request = handle.join().expect("fixture server must join");
let body = request_body(request.as_str());
assert_eq!(body["method"], serde_json::json!("getTokenAccountBalance"));
assert_eq!(body["params"], serde_json::json!([account.to_string(),{"commitment":"finalized"}]));
}
#[tokio::test(flavor = "current_thread")]
async fn typed_get_token_account_balance_preserves_rpc_application_error() {
let (url, handle) = serve_once(include_str!("../fixtures/http/get_token_account_balance.error.json"));
let pool = pool_for_url(url.as_str());
let account = fixture_pubkey("11111111111111111111111111111111");
let result = pool.get_token_account_balance(&crate::HttpRoleName::new("default"), &account, std::option::Option::None).await;
let error = result.expect_err("remote invalid token account must remain an RPC application error");
assert_eq!(error.code(), crate::ERROR_CODE_RPC_APPLICATION_ERROR);
handle.join().expect("fixture server must join");
}
#[tokio::test(flavor = "current_thread")]
async fn typed_get_token_accounts_by_delegate_serializes_program_selector_and_config() {
let (url, handle) = serve_once(include_str!("../fixtures/http/get_token_accounts_by_delegate.success.json"));
let pool = pool_for_url(url.as_str());
let delegate = fixture_pubkey("11111111111111111111111111111111");
let program_id = fixture_pubkey("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA");
let selector = crate::SolanaTokenAccountSelector::ProgramId(program_id);
let config = crate::SolanaAccountInfoConfig::new(
std::option::Option::Some(crate::SolanaAccountEncoding::JsonParsed),
std::option::Option::None,
std::option::Option::Some(crate::SolanaCommitment::Finalized),
std::option::Option::Some(420_000_000),
);
let response = pool
.get_token_accounts_by_delegate(&crate::HttpRoleName::new("default"), &delegate, &selector, std::option::Option::Some(&config))
.await
.expect("delegate token accounts fixture must succeed");
assert_eq!(response.context().slot(), 420_000_002);
assert_eq!(response.value().len(), 1);
assert!(matches!(response.value()[0].account().data(), crate::SolanaAccountData::JsonParsed(_)));
let request = handle.join().expect("fixture server must join");
let body = request_body(request.as_str());
assert_eq!(body["method"], serde_json::json!("getTokenAccountsByDelegate"));
assert_eq!(body["params"][0], serde_json::json!(delegate.to_string()));
assert_eq!(body["params"][1], serde_json::json!({"programId":"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"}));
assert_eq!(body["params"][2], serde_json::json!({"encoding":"jsonParsed","commitment":"finalized","minContextSlot":420000000}));
}
#[tokio::test(flavor = "current_thread")]
async fn typed_get_token_accounts_by_owner_serializes_mint_selector_and_omits_empty_config() {
let (url, handle) = serve_once(include_str!("../fixtures/http/get_token_accounts_by_owner.success.json"));
let pool = pool_for_url(url.as_str());
let owner = fixture_pubkey("11111111111111111111111111111111");
let mint = fixture_pubkey("ComputeBudget111111111111111111111111111111");
let selector = crate::SolanaTokenAccountSelector::Mint(mint);
let config = crate::SolanaAccountInfoConfig::default();
let response = pool
.get_token_accounts_by_owner(&crate::HttpRoleName::new("default"), &owner, &selector, std::option::Option::Some(&config))
.await
.expect("owner token accounts fixture must succeed");
assert_eq!(response.context().api_version(), std::option::Option::None);
assert_eq!(response.value().len(), 1);
assert_eq!(response.value()[0].pubkey().to_string(), "Stake11111111111111111111111111111111111111");
let request = handle.join().expect("fixture server must join");
let body = request_body(request.as_str());
assert_eq!(body["method"], serde_json::json!("getTokenAccountsByOwner"));
assert_eq!(body["params"], serde_json::json!([owner.to_string(),{"mint":"ComputeBudget111111111111111111111111111111"}]));
}
#[tokio::test(flavor = "current_thread")]
async fn typed_get_token_accounts_by_owner_rejects_invalid_account_pubkey_response() {
let (url, handle) = serve_once(include_str!("../fixtures/http/get_token_accounts_by_owner.invalid_pubkey.json"));
let pool = pool_for_url(url.as_str());
let owner = fixture_pubkey("11111111111111111111111111111111");
let mint = fixture_pubkey("ComputeBudget111111111111111111111111111111");
let selector = crate::SolanaTokenAccountSelector::Mint(mint);
let result = pool.get_token_accounts_by_owner(&crate::HttpRoleName::new("default"), &owner, &selector, std::option::Option::None).await;
let error = result.expect_err("invalid account pubkey must reject the typed response");
assert_eq!(error.code(), crate::ERROR_CODE_INVALID_RESPONSE);
handle.join().expect("fixture server must join");
}
#[tokio::test(flavor = "current_thread")]
async fn typed_get_token_largest_accounts_decodes_order_and_commitment() {
let (url, handle) = serve_once(include_str!("../fixtures/http/get_token_largest_accounts.success.json"));
let pool = pool_for_url(url.as_str());
let mint = fixture_pubkey("11111111111111111111111111111111");
let config = crate::SolanaCommitmentConfig::new(std::option::Option::Some(crate::SolanaCommitment::Confirmed));
let response = pool
.get_token_largest_accounts(&crate::HttpRoleName::new("default"), &mint, std::option::Option::Some(&config))
.await
.expect("largest token accounts fixture must succeed");
assert_eq!(response.value().len(), 2);
assert_eq!(response.value()[0].amount().amount(), "9000");
assert_eq!(response.value()[1].amount().amount(), "8000");
let request = handle.join().expect("fixture server must join");
assert_eq!(request_body(request.as_str())["params"], serde_json::json!([mint.to_string(),{"commitment":"confirmed"}]));
}
#[tokio::test(flavor = "current_thread")]
async fn typed_get_token_largest_accounts_rejects_invalid_address() {
let (url, handle) = serve_once(include_str!("../fixtures/http/get_token_largest_accounts.invalid_address.json"));
let pool = pool_for_url(url.as_str());
let mint = fixture_pubkey("11111111111111111111111111111111");
let result = pool.get_token_largest_accounts(&crate::HttpRoleName::new("default"), &mint, std::option::Option::None).await;
let error = result.expect_err("invalid token-account address must reject the typed response");
assert_eq!(error.code(), crate::ERROR_CODE_INVALID_RESPONSE);
handle.join().expect("fixture server must join");
}
#[tokio::test(flavor = "current_thread")]
async fn typed_get_token_supply_preserves_exact_amount_and_omits_absent_config() {
let (url, handle) = serve_once(include_str!("../fixtures/http/get_token_supply.success.json"));
let pool = pool_for_url(url.as_str());
let mint = fixture_pubkey("11111111111111111111111111111111");
let response = pool
.get_token_supply(&crate::HttpRoleName::new("default"), &mint, std::option::Option::None)
.await
.expect("token supply fixture must succeed");
assert_eq!(response.context().slot(), 420_000_007);
assert_eq!(response.value().amount(), "1000000000000000000000000");
assert_eq!(response.value().ui_amount_string(), "1000000000000000000");
let request = handle.join().expect("fixture server must join");
let body = request_body(request.as_str());
assert_eq!(body["method"], serde_json::json!("getTokenSupply"));
assert_eq!(body["params"], serde_json::json!([mint.to_string()]));
}