use std::{collections::HashMap, ops::Deref, sync::Arc};
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use serde_json::Value;
use crate::{
PendingRpcRequest, Result, RpcNamespace,
rpc::{BatchPolicy, HttpJsonRpcTransport},
subscriptions::{RpcSubscription, WebSocketJsonRpcTransport},
};
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum SolanaCommitment {
Confirmed,
Finalized,
Processed,
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub enum SolanaEncoding {
#[serde(rename = "base58")]
Base58,
#[serde(rename = "base64")]
Base64,
#[serde(rename = "base64+zstd")]
Base64Zstd,
#[serde(rename = "jsonParsed")]
JsonParsed,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SolanaContext {
pub api_version: Option<String>,
pub slot: u64,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct SolanaContextResult<T> {
pub context: SolanaContext,
pub value: T,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PriorityFeeEstimate {
pub priority_fee_estimate: f64,
#[serde(flatten)]
pub additional: HashMap<String, Value>,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AssetRequest {
pub id: String,
pub display_options: Option<HashMap<String, bool>>,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AssetBatchRequest {
pub ids: Vec<String>,
pub display_options: Option<HashMap<String, bool>>,
}
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AssetListRequest {
pub cursor: Option<String>,
pub limit: Option<u64>,
pub page: Option<u64>,
#[serde(flatten)]
pub additional: HashMap<String, Value>,
}
pub type IndexedAsset = HashMap<String, Value>;
pub type IndexedAssetProof = HashMap<String, Value>;
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct IndexedAssetList<T = IndexedAsset> {
pub cursor: Option<String>,
pub items: Vec<T>,
pub limit: Option<u64>,
pub page: Option<u64>,
pub total: Option<u64>,
#[serde(flatten)]
pub additional: HashMap<String, Value>,
}
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
pub struct NumericFilter {
pub eq: Option<f64>,
pub gt: Option<f64>,
pub gte: Option<f64>,
pub lt: Option<f64>,
pub lte: Option<f64>,
}
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AddressTransactionsOptions {
pub before: Option<String>,
pub commitment: Option<SolanaCommitment>,
pub encoding: Option<String>,
pub filters: Option<HashMap<String, Value>>,
pub limit: Option<u64>,
pub max_supported_transaction_version: Option<u64>,
pub pagination_token: Option<String>,
pub sort_order: Option<String>,
pub transaction_details: Option<String>,
pub until: Option<String>,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AddressTransaction {
pub block_time: Option<i64>,
pub confirmation_status: SolanaCommitment,
pub err: Value,
pub memo: Option<String>,
pub meta: Option<Value>,
pub signature: String,
pub slot: u64,
pub transaction: Option<Value>,
pub transaction_index: u64,
pub version: Option<Value>,
#[serde(flatten)]
pub additional: HashMap<String, Value>,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AddressTransactionPage {
pub data: Vec<AddressTransaction>,
pub pagination_token: Option<String>,
pub window_start: Option<i64>,
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum AddressTransferDirection {
Any,
In,
Out,
}
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AddressTransferFilters {
pub amount: Option<NumericFilter>,
pub block_time: Option<NumericFilter>,
pub slot: Option<NumericFilter>,
}
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AddressTransfersOptions {
pub commitment: Option<SolanaCommitment>,
pub direction: Option<AddressTransferDirection>,
pub filters: Option<AddressTransferFilters>,
pub limit: Option<u64>,
pub mint: Option<String>,
pub pagination_token: Option<String>,
pub sol_mode: Option<String>,
pub sort_order: Option<String>,
pub with: Option<String>,
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub enum AddressTransferType {
#[serde(rename = "burn")]
Burn,
#[serde(rename = "changeOwner")]
ChangeOwner,
#[serde(rename = "mint")]
Mint,
#[serde(rename = "transfer")]
Transfer,
#[serde(rename = "unwrap")]
Unwrap,
#[serde(rename = "withdrawWithheldFee")]
WithdrawWithheldFee,
#[serde(rename = "wrap")]
Wrap,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AddressTransfer {
pub amount: String,
pub block_time: Option<i64>,
pub confirmation_status: SolanaCommitment,
pub decimals: u8,
pub fee_amount: Option<String>,
pub fee_ui_amount: Option<String>,
pub from_token_account: Option<String>,
pub from_user_account: Option<String>,
pub inner_instruction_idx: u64,
pub instruction_idx: u64,
pub mint: Option<String>,
pub signature: String,
pub slot: u64,
pub to_token_account: Option<String>,
pub to_user_account: Option<String>,
pub transaction_idx: u64,
#[serde(rename = "type")]
pub transfer_type: AddressTransferType,
pub ui_amount: String,
#[serde(flatten)]
pub additional: HashMap<String, Value>,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AddressTransferPage {
pub data: Vec<AddressTransfer>,
pub pagination_token: Option<String>,
pub window_start: Option<i64>,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PingMeasurement {
pub city: Option<String>,
pub country: Option<String>,
pub from_ip: Option<String>,
pub icmp_replied: bool,
pub lat: Option<f64>,
pub lon: Option<f64>,
pub measured_at: Option<String>,
pub ms: Option<f64>,
pub org: Option<String>,
pub postal: Option<String>,
pub region: Option<String>,
pub timezone: Option<String>,
#[serde(flatten)]
pub additional: HashMap<String, Value>,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct LeaderSlot {
pub epoch: u64,
pub feature_set: Option<String>,
pub gossip_port: Option<u16>,
pub gossip_updated_at: Option<String>,
pub identity: String,
pub ip_address: Option<String>,
pub leader_city: Option<String>,
pub leader_country: Option<String>,
pub leader_lat: Option<f64>,
pub leader_lon: Option<f64>,
pub leader_org: Option<String>,
pub leader_region: Option<String>,
pub leader_timezone: Option<String>,
pub ping_to_leaders: Vec<PingMeasurement>,
pub rpc_address: Option<String>,
pub slot: String,
pub stake_weight: f64,
pub tpu_port: Option<u16>,
pub tpu_quic_port: Option<u16>,
pub version: Option<String>,
#[serde(flatten)]
pub additional: HashMap<String, Value>,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct LeaderSlotsResult {
pub data: Vec<LeaderSlot>,
pub message: String,
pub success: bool,
pub total: u64,
#[serde(flatten)]
pub additional: HashMap<String, Value>,
}
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
pub struct ValidatorsInformationOptions {
pub country: Option<String>,
pub limit: Option<u64>,
pub region: Option<String>,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ValidatorInformation {
pub feature_set: Option<String>,
pub gossip_node_id: Option<u64>,
pub gossip_port: Option<u16>,
pub gossip_updated_at: Option<String>,
pub identity: String,
pub ip_address: Option<String>,
pub leader_city: Option<String>,
pub leader_country: Option<String>,
pub leader_lat: Option<f64>,
pub leader_lon: Option<f64>,
pub leader_org: Option<String>,
pub leader_region: Option<String>,
pub leader_timezone: Option<String>,
pub ping_to_leaders: Vec<PingMeasurement>,
pub rpc_address: Option<String>,
pub slot_count: u64,
pub stake_weight: f64,
pub tpu_port: Option<u16>,
pub tpu_quic_port: Option<u16>,
pub version: Option<String>,
#[serde(flatten)]
pub additional: HashMap<String, Value>,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ValidatorsInformationResult {
pub data: Vec<ValidatorInformation>,
pub epoch: u64,
pub message: String,
pub success: bool,
pub total: u64,
pub total_validators: u64,
#[serde(flatten)]
pub additional: HashMap<String, Value>,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(untagged)]
pub enum AnalyticsTimeBound {
Number(i64),
String(String),
}
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TopProgramsOptions {
pub include_votes: Option<bool>,
pub limit: Option<u64>,
pub since: Option<AnalyticsTimeBound>,
pub until: Option<AnalyticsTimeBound>,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct TopProgramRow {
pub errors: String,
pub invocations: String,
pub program: String,
pub total_cus: String,
#[serde(flatten)]
pub additional: HashMap<String, Value>,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(untagged)]
pub enum SlotStatsOptions {
Slot {
slot: u64,
},
Range {
#[serde(rename = "fromSlot")]
from_slot: u64,
#[serde(rename = "toSlot")]
to_slot: u64,
},
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct SlotStatsRow {
pub block_time: i64,
pub non_vote_transaction_count: u64,
pub slot: u64,
pub transaction_count: u64,
pub vote_transaction_count: u64,
#[serde(flatten)]
pub additional: HashMap<String, Value>,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TpsTimeseriesOptions {
pub bucket_sec: Option<u64>,
pub from: AnalyticsTimeBound,
pub to: AnalyticsTimeBound,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct TpsBucket {
pub bucket: i64,
pub non_vote_tps: f64,
pub total_tps: f64,
#[serde(flatten)]
pub additional: HashMap<String, Value>,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct EpochSummary {
pub distinct_programs: String,
pub epoch: u64,
pub first_block_time: i64,
pub last_block_time: i64,
pub non_vote_txs: String,
pub program_invocations: String,
pub slots: String,
pub total_txs: String,
pub vote_txs: String,
#[serde(flatten)]
pub additional: HashMap<String, Value>,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ProgramStatsOptions {
pub bucket_sec: Option<u64>,
pub program_id_base58: String,
pub since: Option<AnalyticsTimeBound>,
pub until: Option<AnalyticsTimeBound>,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct ProgramStatsBucket {
pub bucket: i64,
pub errors: String,
pub invocations: String,
pub total_cus: String,
#[serde(flatten)]
pub additional: HashMap<String, Value>,
}
pub const SOLANA_RPC_METHODS: &[&str] = &[
"getAccountInfo",
"getBalance",
"getBlock",
"getBlockCommitment",
"getBlockHeight",
"getBlockProduction",
"getBlockTime",
"getBlocks",
"getBlocksWithLimit",
"getClusterNodes",
"getEpochInfo",
"getEpochSchedule",
"getFeeForMessage",
"getFirstAvailableBlock",
"getGenesisHash",
"getHealth",
"getHighestSnapshotSlot",
"getIdentity",
"getInflationGovernor",
"getInflationRate",
"getInflationReward",
"getLargestAccounts",
"getLatestBlockhash",
"getLeaderSchedule",
"getMaxRetransmitSlot",
"getMaxShredInsertSlot",
"getMinimumBalanceForRentExemption",
"getMultipleAccounts",
"getParsedTransaction",
"getPriorityFeeEstimate",
"getProgramAccounts",
"getProgramAccountsV2",
"getRecentPerformanceSamples",
"getRecentPrioritizationFees",
"getSignatureStatuses",
"getSignaturesForAddress",
"getSlot",
"getSlotLeader",
"getSlotLeaders",
"getStakeMinimumDelegation",
"getSupply",
"getTokenAccountBalance",
"getTokenAccountsByDelegate",
"getTokenAccountsByOwner",
"getTokenLargestAccounts",
"getTokenSupply",
"getTransaction",
"getTransactionCount",
"getVersion",
"getVoteAccounts",
"isBlockhashValid",
"minimumLedgerSlot",
"requestAirdrop",
"sendTransaction",
"simulateTransaction",
];
pub const SOLANA_DAS_METHODS: &[&str] = &[
"getAsset",
"getAssetBatch",
"getAssetProof",
"getAssetProofBatch",
"getAssetsByAuthority",
"getAssetsByCreator",
"getAssetsByGroup",
"getAssetsByOwner",
"getNftEditions",
"getSignaturesForAsset",
"getTokenAccounts",
"getTokensByDelegate",
"getTokensByOwner",
"searchAssets",
];
pub const SOLANA_HISTORY_METHODS: &[&str] = &["getTransactionsForAddress", "getTransfersByAddress"];
pub const SOLANA_LEADER_METHODS: &[&str] = &["getLeaderSlots", "getValidatorsInformation"];
pub const SOLANA_ANALYTICS_METHODS: &[&str] = &[
"jetEpochSummary",
"jetProgramStats",
"jetSlotStats",
"jetTopPrograms",
"jetTpsTimeseries",
];
#[derive(Clone)]
pub struct SolanaRpcClient {
namespace: RpcNamespace,
}
impl SolanaRpcClient {
const fn new(transport: Arc<HttpJsonRpcTransport>) -> Self {
Self {
namespace: RpcNamespace::new(transport, BatchPolicy::SolanaStandard),
}
}
}
impl Deref for SolanaRpcClient {
type Target = RpcNamespace;
fn deref(&self) -> &Self::Target {
&self.namespace
}
}
macro_rules! solana_no_params {
($(($name:ident, $wire:literal, $result:ty)),* $(,)?) => {
impl SolanaRpcClient {
$(
#[doc = concat!("Creates a pending `", $wire, "` request.")]
#[must_use]
pub fn $name(&self) -> PendingRpcRequest<$result> {
self.namespace.request($wire, Vec::<Value>::new()).expect("empty parameters serialize")
}
)*
}
};
}
macro_rules! solana_with_params {
($(($name:ident, $wire:literal, $result:ty)),* $(,)?) => {
impl SolanaRpcClient {
$(
#[doc = concat!("Creates a pending `", $wire, "` request from positional parameters.")]
pub fn $name<P: Serialize>(&self, params: P) -> Result<PendingRpcRequest<$result>> {
self.namespace.request($wire, params)
}
)*
}
};
}
solana_no_params!(
(get_cluster_nodes, "getClusterNodes", Value),
(get_epoch_schedule, "getEpochSchedule", Value),
(get_first_available_block, "getFirstAvailableBlock", u64),
(get_genesis_hash, "getGenesisHash", String),
(get_health, "getHealth", String),
(get_highest_snapshot_slot, "getHighestSnapshotSlot", Value),
(get_identity, "getIdentity", Value),
(get_inflation_rate, "getInflationRate", Value),
(get_max_retransmit_slot, "getMaxRetransmitSlot", u64),
(get_max_shred_insert_slot, "getMaxShredInsertSlot", u64),
(get_version, "getVersion", Value),
(minimum_ledger_slot, "minimumLedgerSlot", u64),
);
solana_with_params!(
(get_account_info, "getAccountInfo", SolanaContextResult<Option<Value>>),
(get_balance, "getBalance", SolanaContextResult<u64>),
(get_block, "getBlock", Option<Value>),
(get_block_commitment, "getBlockCommitment", Value),
(get_block_height, "getBlockHeight", u64),
(get_block_production, "getBlockProduction", Value),
(get_block_time, "getBlockTime", Option<i64>),
(get_blocks, "getBlocks", Vec<u64>),
(get_blocks_with_limit, "getBlocksWithLimit", Vec<u64>),
(get_epoch_info, "getEpochInfo", Value),
(get_fee_for_message, "getFeeForMessage", SolanaContextResult<Option<u64>>),
(get_inflation_governor, "getInflationGovernor", Value),
(get_inflation_reward, "getInflationReward", Value),
(get_largest_accounts, "getLargestAccounts", Value),
(get_latest_blockhash, "getLatestBlockhash", Value),
(get_leader_schedule, "getLeaderSchedule", Option<Value>),
(
get_minimum_balance_for_rent_exemption,
"getMinimumBalanceForRentExemption",
u64
),
(get_multiple_accounts, "getMultipleAccounts", SolanaContextResult<Value>),
(get_parsed_transaction, "getParsedTransaction", Option<Value>),
(
get_priority_fee_estimate,
"getPriorityFeeEstimate",
PriorityFeeEstimate
),
(get_program_accounts, "getProgramAccounts", Value),
(get_program_accounts_v2, "getProgramAccountsV2", Value),
(get_recent_performance_samples, "getRecentPerformanceSamples", Value),
(
get_recent_prioritization_fees,
"getRecentPrioritizationFees",
Value
),
(get_signature_statuses, "getSignatureStatuses", Value),
(get_signatures_for_address, "getSignaturesForAddress", Value),
(get_slot, "getSlot", u64),
(get_slot_leader, "getSlotLeader", String),
(get_slot_leaders, "getSlotLeaders", Vec<String>),
(
get_stake_minimum_delegation,
"getStakeMinimumDelegation",
SolanaContextResult<u64>
),
(get_supply, "getSupply", Value),
(get_token_account_balance, "getTokenAccountBalance", Value),
(
get_token_accounts_by_delegate,
"getTokenAccountsByDelegate",
Value
),
(get_token_accounts_by_owner, "getTokenAccountsByOwner", Value),
(get_token_largest_accounts, "getTokenLargestAccounts", Value),
(get_token_supply, "getTokenSupply", Value),
(get_transaction, "getTransaction", Option<Value>),
(get_transaction_count, "getTransactionCount", u64),
(get_vote_accounts, "getVoteAccounts", Value),
(
is_blockhash_valid,
"isBlockhashValid",
SolanaContextResult<bool>
),
(request_airdrop, "requestAirdrop", String),
(send_transaction, "sendTransaction", String),
(simulate_transaction, "simulateTransaction", Value),
);
macro_rules! namespace_client {
($name:ident, $policy:expr, $(($method:ident, $wire:literal, $result:ty)),* $(,)?) => {
#[doc = concat!(stringify!($name), " JSON-RPC namespace.")]
#[derive(Clone)]
pub struct $name {
namespace: RpcNamespace,
}
impl $name {
const fn new(transport: Arc<HttpJsonRpcTransport>) -> Self {
Self { namespace: RpcNamespace::new(transport, $policy) }
}
$(
#[doc = concat!("Creates a pending `", $wire, "` request.")]
pub fn $method<P: Serialize>(&self, params: P) -> Result<PendingRpcRequest<$result>> {
self.namespace.request($wire, params)
}
)*
}
impl Deref for $name {
type Target = RpcNamespace;
fn deref(&self) -> &Self::Target {
&self.namespace
}
}
};
}
namespace_client!(
SolanaDasClient,
BatchPolicy::Any,
(get_asset, "getAsset", Option<IndexedAsset>),
(
get_asset_batch,
"getAssetBatch",
Vec<Option<IndexedAsset>>
),
(get_asset_proof, "getAssetProof", Option<IndexedAssetProof>),
(
get_asset_proof_batch,
"getAssetProofBatch",
Vec<Option<IndexedAssetProof>>
),
(
get_assets_by_authority,
"getAssetsByAuthority",
IndexedAssetList
),
(
get_assets_by_creator,
"getAssetsByCreator",
IndexedAssetList
),
(get_assets_by_group, "getAssetsByGroup", IndexedAssetList),
(get_assets_by_owner, "getAssetsByOwner", IndexedAssetList),
(get_nft_editions, "getNftEditions", HashMap<String, Value>),
(
get_signatures_for_asset,
"getSignaturesForAsset",
HashMap<String, Value>
),
(
get_token_accounts,
"getTokenAccounts",
HashMap<String, Value>
),
(
get_tokens_by_delegate,
"getTokensByDelegate",
HashMap<String, Value>
),
(
get_tokens_by_owner,
"getTokensByOwner",
HashMap<String, Value>
),
(search_assets, "searchAssets", IndexedAssetList),
);
namespace_client!(
SolanaHistoryClient,
BatchPolicy::Any,
(
get_transactions_for_address,
"getTransactionsForAddress",
Option<AddressTransactionPage>
),
(
get_transfers_by_address,
"getTransfersByAddress",
AddressTransferPage
),
);
namespace_client!(
SolanaLeaderClient,
BatchPolicy::Unsupported,
(get_leader_slots, "getLeaderSlots", LeaderSlotsResult),
(
get_validators_information,
"getValidatorsInformation",
ValidatorsInformationResult
),
);
namespace_client!(
SolanaAnalyticsClient,
BatchPolicy::Any,
(jet_epoch_summary, "jetEpochSummary", Option<EpochSummary>),
(
jet_program_stats,
"jetProgramStats",
Vec<ProgramStatsBucket>
),
(jet_slot_stats, "jetSlotStats", Vec<SlotStatsRow>),
(jet_top_programs, "jetTopPrograms", Vec<TopProgramRow>),
(jet_tps_timeseries, "jetTpsTimeseries", Vec<TpsBucket>),
);
pub const SOLANA_ENHANCED_SUBSCRIPTION_METHODS: &[&str] = &[
"accountSubscribe",
"accountUnsubscribe",
"transactionSubscribe",
"transactionUnsubscribe",
];
#[derive(Clone)]
pub struct SolanaSubscriptions {
transport: Arc<WebSocketJsonRpcTransport>,
}
impl SolanaSubscriptions {
pub(crate) const fn new(transport: Arc<WebSocketJsonRpcTransport>) -> Self {
Self { transport }
}
#[must_use]
pub fn endpoint(&self) -> &str {
self.transport.endpoint()
}
pub async fn account_subscribe(
&self,
address: &str,
options: Option<Value>,
) -> Result<RpcSubscription> {
let mut params = vec![Value::String(address.to_owned())];
if let Some(options) = options {
params.push(options);
}
self.raw_subscribe(
"accountSubscribe",
Value::Array(params),
"accountUnsubscribe",
)
.await
}
pub async fn transaction_subscribe(
&self,
filter: Value,
options: Option<Value>,
) -> Result<RpcSubscription> {
let mut params = vec![filter];
if let Some(options) = options {
params.push(options);
}
self.raw_subscribe(
"transactionSubscribe",
Value::Array(params),
"transactionUnsubscribe",
)
.await
}
pub async fn raw_subscribe(
&self,
subscribe_method: &str,
params: Value,
unsubscribe_method: &str,
) -> Result<RpcSubscription> {
let receiver = self.transport.subscribe_notifications();
let id: crate::SubscriptionId = self
.transport
.request(subscribe_method, params, None)
.await?;
Ok(RpcSubscription::new(
id,
Arc::clone(&self.transport),
unsubscribe_method,
receiver,
))
}
pub async fn raw<T: DeserializeOwned>(&self, method: &str, params: Value) -> Result<T> {
self.transport.request(method, params, None).await
}
pub async fn close(&self) {
self.transport.close().await;
}
}
#[derive(Clone)]
pub struct SolanaClient {
pub rpc: SolanaRpcClient,
pub das: SolanaDasClient,
pub history: SolanaHistoryClient,
pub leaders: SolanaLeaderClient,
pub analytics: SolanaAnalyticsClient,
pub subscriptions: SolanaSubscriptions,
}
impl SolanaClient {
pub(crate) fn new(
transport: Arc<HttpJsonRpcTransport>,
websocket: Arc<WebSocketJsonRpcTransport>,
) -> Self {
Self {
rpc: SolanaRpcClient::new(Arc::clone(&transport)),
das: SolanaDasClient::new(Arc::clone(&transport)),
history: SolanaHistoryClient::new(Arc::clone(&transport)),
leaders: SolanaLeaderClient::new(Arc::clone(&transport)),
analytics: SolanaAnalyticsClient::new(transport),
subscriptions: SolanaSubscriptions::new(websocket),
}
}
}