use async_trait::async_trait;
use solana_sdk::{account::Account, hash::Hash, pubkey::Pubkey, transaction::VersionedTransaction};
use crate::error::Result;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RpcFilter {
DataSize(u64),
Memcmp { offset: usize, bytes: Vec<u8> },
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SimulationResult {
pub logs: Vec<String>,
pub error: Option<serde_json::Value>,
pub units_consumed: Option<u64>,
}
#[async_trait]
pub trait Rpc: Send + Sync {
async fn get_account(&self, address: &Pubkey) -> Result<Option<Account>>;
async fn get_multiple_accounts(&self, addresses: &[Pubkey]) -> Result<Vec<Option<Account>>> {
let mut accounts = Vec::with_capacity(addresses.len());
for address in addresses {
accounts.push(self.get_account(address).await?);
}
Ok(accounts)
}
async fn get_program_accounts(
&self,
program_id: &Pubkey,
filters: &[RpcFilter],
) -> Result<Vec<(Pubkey, Account)>>;
async fn get_slot(&self) -> Result<u64>;
async fn get_block_time(&self, slot: u64) -> Result<Option<i64>>;
async fn get_latest_blockhash(&self) -> Result<Hash>;
async fn get_transaction_logs(&self, signature: &str) -> Result<Option<Vec<String>>>;
async fn simulate_transaction(
&self,
transaction: &VersionedTransaction,
) -> Result<SimulationResult>;
}
#[cfg(feature = "http")]
pub use http::HttpRpcClient;
#[cfg(feature = "http")]
mod http {
use std::sync::{
atomic::{AtomicU64, Ordering},
Arc,
};
use base64::{engine::general_purpose::STANDARD, Engine};
use serde::{de::DeserializeOwned, Deserialize};
use serde_json::{json, Value};
use solana_sdk::commitment_config::{CommitmentConfig, CommitmentLevel};
use super::*;
use crate::error::SdkError;
#[derive(Debug, Clone)]
pub struct HttpRpcClient {
endpoint: String,
commitment: CommitmentConfig,
client: reqwest::Client,
next_id: Arc<AtomicU64>,
}
impl HttpRpcClient {
pub fn new(endpoint: impl Into<String>, commitment: CommitmentConfig) -> Self {
Self::with_client(endpoint, commitment, reqwest::Client::new())
}
pub fn with_client(
endpoint: impl Into<String>,
commitment: CommitmentConfig,
client: reqwest::Client,
) -> Self {
Self {
endpoint: endpoint.into(),
commitment,
client,
next_id: Arc::new(AtomicU64::new(1)),
}
}
pub fn endpoint(&self) -> &str {
&self.endpoint
}
pub fn commitment(&self) -> CommitmentConfig {
self.commitment
}
async fn request<T: DeserializeOwned>(&self, method: &str, params: Value) -> Result<T> {
let id = self.next_id.fetch_add(1, Ordering::Relaxed);
let response = self
.client
.post(&self.endpoint)
.json(&json!({
"jsonrpc": "2.0",
"id": id,
"method": method,
"params": params,
}))
.send()
.await
.map_err(|error| SdkError::Rpc(format!("{method}: {error}")))?
.error_for_status()
.map_err(|error| SdkError::Rpc(format!("{method}: {error}")))?;
let mut envelope: Value = response.json().await.map_err(|error| {
SdkError::Rpc(format!("{method}: invalid JSON response: {error}"))
})?;
if envelope.get("jsonrpc").and_then(Value::as_str) != Some("2.0")
|| envelope.get("id").and_then(Value::as_u64) != Some(id)
{
return Err(SdkError::Rpc(format!(
"{method}: invalid JSON-RPC response envelope"
)));
}
if let Some(error) = envelope.get("error").filter(|error| !error.is_null()) {
return Err(SdkError::Rpc(format!("{method}: {error}")));
}
let result = envelope
.as_object_mut()
.and_then(|object| object.remove("result"))
.ok_or_else(|| SdkError::Rpc(format!("{method}: response is missing result")))?;
decode_result(method, result)
}
async fn request_value<T: DeserializeOwned>(
&self,
method: &str,
params: Value,
) -> Result<T> {
let mut result: Value = self.request(method, params).await?;
let value = result
.as_object_mut()
.and_then(|object| object.remove("value"))
.ok_or_else(|| SdkError::Rpc(format!("{method}: response is missing value")))?;
decode_result(method, value)
}
}
fn decode_result<T: DeserializeOwned>(method: &str, value: Value) -> Result<T> {
serde_json::from_value(value)
.map_err(|error| SdkError::Rpc(format!("{method}: invalid response data: {error}")))
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct WireAccount {
lamports: u64,
data: [String; 2],
owner: String,
executable: bool,
rent_epoch: u64,
}
impl WireAccount {
fn decode(self) -> Result<Account> {
let [encoded, encoding] = self.data;
if encoding != "base64" {
return Err(SdkError::Rpc(format!(
"unsupported account encoding: {encoding}"
)));
}
let data = STANDARD
.decode(encoded)
.map_err(|error| SdkError::Rpc(format!("invalid base64 account data: {error}")))?;
let owner = self.owner.parse().map_err(|error| {
SdkError::Rpc(format!("invalid account owner {}: {error}", self.owner))
})?;
Ok(Account {
lamports: self.lamports,
data,
owner,
executable: self.executable,
rent_epoch: self.rent_epoch,
})
}
}
#[derive(Deserialize)]
struct ProgramAccount {
pubkey: String,
account: WireAccount,
}
#[derive(Deserialize)]
struct BlockhashValue {
blockhash: String,
}
#[derive(Deserialize)]
struct TransactionValue {
meta: Option<TransactionMeta>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct TransactionMeta {
log_messages: Option<Vec<String>>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct SimulationValue {
err: Value,
logs: Option<Vec<String>>,
units_consumed: Option<u64>,
}
#[async_trait]
impl Rpc for HttpRpcClient {
async fn get_account(&self, address: &Pubkey) -> Result<Option<Account>> {
let account: Option<WireAccount> = self
.request_value(
"getAccountInfo",
json!([address.to_string(), {
"encoding": "base64",
"commitment": self.commitment.commitment,
}]),
)
.await?;
account.map(WireAccount::decode).transpose()
}
async fn get_multiple_accounts(
&self,
addresses: &[Pubkey],
) -> Result<Vec<Option<Account>>> {
if addresses.is_empty() {
return Ok(Vec::new());
}
let accounts: Vec<Option<WireAccount>> = self
.request_value(
"getMultipleAccounts",
json!([addresses.iter().map(ToString::to_string).collect::<Vec<_>>(), {
"encoding": "base64",
"commitment": self.commitment.commitment,
}]),
)
.await?;
if accounts.len() != addresses.len() {
return Err(SdkError::Rpc(format!(
"getMultipleAccounts: expected {} accounts, received {}",
addresses.len(),
accounts.len()
)));
}
accounts
.into_iter()
.map(|account| account.map(WireAccount::decode).transpose())
.collect()
}
async fn get_program_accounts(
&self,
program_id: &Pubkey,
filters: &[RpcFilter],
) -> Result<Vec<(Pubkey, Account)>> {
let filters: Vec<Value> = filters
.iter()
.map(|filter| match filter {
RpcFilter::DataSize(size) => json!({"dataSize": size}),
RpcFilter::Memcmp { offset, bytes } => json!({"memcmp": {
"offset": offset,
"bytes": STANDARD.encode(bytes),
"encoding": "base64",
}}),
})
.collect();
let accounts: Vec<ProgramAccount> = self
.request(
"getProgramAccounts",
json!([program_id.to_string(), {
"encoding": "base64",
"commitment": self.commitment.commitment,
"filters": filters,
}]),
)
.await?;
accounts
.into_iter()
.map(|entry| {
let address = entry.pubkey.parse().map_err(|error| {
SdkError::Rpc(format!(
"invalid program account address {}: {error}",
entry.pubkey
))
})?;
Ok((address, entry.account.decode()?))
})
.collect()
}
async fn get_slot(&self) -> Result<u64> {
self.request(
"getSlot",
json!([{"commitment": self.commitment.commitment}]),
)
.await
}
async fn get_block_time(&self, slot: u64) -> Result<Option<i64>> {
self.request("getBlockTime", json!([slot])).await
}
async fn get_latest_blockhash(&self) -> Result<Hash> {
let value: BlockhashValue = self
.request_value(
"getLatestBlockhash",
json!([{"commitment": self.commitment.commitment}]),
)
.await?;
value
.blockhash
.parse()
.map_err(|error| SdkError::Rpc(format!("invalid latest blockhash: {error}")))
}
async fn get_transaction_logs(&self, signature: &str) -> Result<Option<Vec<String>>> {
let finality = match self.commitment.commitment {
CommitmentLevel::Finalized => CommitmentLevel::Finalized,
_ => CommitmentLevel::Confirmed,
};
let transaction: Option<TransactionValue> = self
.request(
"getTransaction",
json!([signature, {
"encoding": "json",
"commitment": finality,
"maxSupportedTransactionVersion": 0,
}]),
)
.await?;
Ok(transaction
.and_then(|transaction| transaction.meta)
.and_then(|meta| meta.log_messages))
}
async fn simulate_transaction(
&self,
transaction: &VersionedTransaction,
) -> Result<SimulationResult> {
let serialized = bincode::serialize(transaction).map_err(|error| {
SdkError::Simulation(format!("cannot serialize transaction: {error}"))
})?;
let simulation: SimulationValue = self
.request_value(
"simulateTransaction",
json!([STANDARD.encode(serialized), {
"encoding": "base64",
"sigVerify": false,
"commitment": self.commitment.commitment,
"innerInstructions": true,
}]),
)
.await?;
Ok(SimulationResult {
logs: simulation.logs.unwrap_or_default(),
error: (!simulation.err.is_null()).then_some(simulation.err),
units_consumed: simulation.units_consumed,
})
}
}
}
#[cfg(all(test, feature = "http"))]
mod tests {
use std::{
io::{BufRead, BufReader, Read, Write},
net::TcpListener,
thread::{self, JoinHandle},
time::Duration,
};
use base64::{engine::general_purpose::STANDARD, Engine};
use serde_json::{json, Value};
use solana_sdk::{
commitment_config::CommitmentConfig,
message::{v0, VersionedMessage},
signature::Signature,
};
use super::*;
fn server(status: u16, response: Value) -> (HttpRpcClient, JoinHandle<Value>) {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let endpoint = format!("http://{}", listener.local_addr().unwrap());
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 length = None;
loop {
let mut line = String::new();
assert_ne!(reader.read_line(&mut line).unwrap(), 0);
if line == "\r\n" {
break;
}
if let Some((name, value)) = line.split_once(':') {
if name.eq_ignore_ascii_case("content-length") {
length = Some(value.trim().parse::<usize>().unwrap());
}
}
}
let mut body = vec![0; length.unwrap()];
reader.read_exact(&mut body).unwrap();
let request = serde_json::from_slice(&body).unwrap();
let response = response.to_string();
write!(
stream,
"HTTP/1.1 {status} Test\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{response}",
response.len()
)
.unwrap();
request
});
let client = reqwest::Client::builder()
.timeout(Duration::from_secs(5))
.build()
.unwrap();
(
HttpRpcClient::with_client(endpoint, CommitmentConfig::confirmed(), client),
task,
)
}
fn result(value: Value) -> Value {
json!({"jsonrpc": "2.0", "id": 1, "result": value})
}
fn account(owner: Pubkey) -> Value {
json!({
"lamports": 123,
"data": ["AAEC/w==", "base64"],
"owner": owner.to_string(),
"executable": false,
"rentEpoch": u64::MAX,
})
}
#[tokio::test]
async fn account_absence_is_not_transport_or_decoding_failure() {
let address = Pubkey::new_unique();
let (client, request) = server(200, result(json!({"value": null})));
let rpc: &dyn Rpc = &client;
assert_eq!(rpc.get_account(&address).await.unwrap(), None);
let request = request.join().unwrap();
assert_eq!(request["method"], "getAccountInfo");
assert_eq!(request["params"][0], address.to_string());
assert_eq!(request["params"][1]["encoding"], "base64");
assert_eq!(request["params"][1]["commitment"], "confirmed");
for (status, response) in [
(503, result(json!({"value": null}))),
(
200,
json!({"jsonrpc": "2.0", "id": 1, "error": {"code": -32000, "message": "unavailable"}}),
),
(200, result(json!({}))),
(200, result(json!({"value": {"owner": "invalid"}}))),
] {
let (client, request) = server(status, response);
assert!(matches!(
client.get_account(&address).await,
Err(crate::SdkError::Rpc(_))
));
request.join().unwrap();
}
}
#[tokio::test]
async fn multiple_accounts_preserve_positions_and_reject_incomplete_responses() {
let owner = Pubkey::new_unique();
let addresses = [Pubkey::new_unique(), Pubkey::new_unique()];
let (client, request) = server(200, result(json!({"value": [null, account(owner)]})));
let accounts = client.get_multiple_accounts(&addresses).await.unwrap();
assert_eq!(accounts[0], None);
assert_eq!(
accounts[1],
Some(Account {
lamports: 123,
data: vec![0, 1, 2, 255],
owner,
executable: false,
rent_epoch: u64::MAX,
})
);
let request = request.join().unwrap();
assert_eq!(request["method"], "getMultipleAccounts");
assert_eq!(
request["params"][0],
json!(addresses.map(|address| address.to_string()))
);
let (client, request) = server(200, result(json!({"value": [null]})));
assert!(matches!(
client.get_multiple_accounts(&addresses).await,
Err(crate::SdkError::Rpc(_))
));
request.join().unwrap();
}
#[tokio::test]
async fn program_filters_use_explicit_base64_and_return_native_accounts() {
let program = Pubkey::new_unique();
let address = Pubkey::new_unique();
let (client, request) = server(
200,
result(json!([{
"pubkey": address.to_string(),
"account": account(program),
}])),
);
let accounts = client
.get_program_accounts(
&program,
&[
RpcFilter::DataSize(64),
RpcFilter::Memcmp {
offset: 8,
bytes: vec![0, 255],
},
],
)
.await
.unwrap();
assert_eq!(accounts[0].0, address);
assert_eq!(accounts[0].1.owner, program);
assert_eq!(accounts[0].1.data, [0, 1, 2, 255]);
let request = request.join().unwrap();
assert_eq!(request["method"], "getProgramAccounts");
assert_eq!(
request["params"][1]["filters"],
json!([
{"dataSize": 64},
{"memcmp": {"offset": 8, "bytes": "AP8=", "encoding": "base64"}},
])
);
}
#[tokio::test]
async fn simulation_preserves_execution_errors_logs_and_native_wire_transaction() {
let message =
v0::Message::try_compile(&Pubkey::new_unique(), &[], &[], Hash::new_unique()).unwrap();
let transaction = VersionedTransaction {
signatures: vec![Signature::default(); message.header.num_required_signatures as usize],
message: VersionedMessage::V0(message),
};
let error = json!({"InstructionError": [0, {"Custom": 6001}]});
let (client, request) = server(
200,
result(json!({"value": {
"err": error,
"logs": ["Program failed: custom program error: 0x1771"],
"unitsConsumed": 42,
}})),
);
let simulation = client.simulate_transaction(&transaction).await.unwrap();
assert_eq!(simulation.error, Some(error));
assert_eq!(
simulation.logs,
["Program failed: custom program error: 0x1771"]
);
assert_eq!(simulation.units_consumed, Some(42));
let request = request.join().unwrap();
assert_eq!(request["method"], "simulateTransaction");
assert_eq!(request["params"][1]["sigVerify"], false);
assert_eq!(request["params"][1]["innerInstructions"], true);
let wire = STANDARD
.decode(request["params"][0].as_str().unwrap())
.unwrap();
let decoded: VersionedTransaction = bincode::deserialize(&wire).unwrap();
assert_eq!(decoded, transaction);
}
#[tokio::test]
async fn transaction_logs_accept_missing_transactions_and_v0_metadata() {
let (client, request) = server(200, result(Value::Null));
assert_eq!(
client.get_transaction_logs("signature").await.unwrap(),
None
);
request.join().unwrap();
let (client, request) = server(
200,
result(json!({
"meta": {"logMessages": ["Program log: hello"]},
"version": 0,
})),
);
assert_eq!(
client.get_transaction_logs("signature").await.unwrap(),
Some(vec!["Program log: hello".to_string()])
);
let request = request.join().unwrap();
assert_eq!(request["method"], "getTransaction");
assert_eq!(request["params"][1]["maxSupportedTransactionVersion"], 0);
assert_eq!(request["params"][1]["commitment"], "confirmed");
}
}