Skip to main content

erpc_sdk/
solana.rs

1use std::{collections::HashMap, ops::Deref, sync::Arc};
2
3use serde::{Deserialize, Serialize, de::DeserializeOwned};
4use serde_json::Value;
5
6use crate::{
7    PendingRpcRequest, Result, RpcNamespace,
8    rpc::{BatchPolicy, HttpJsonRpcTransport},
9    subscriptions::{RpcSubscription, WebSocketJsonRpcTransport},
10};
11
12/// Solana commitment level.
13#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
14#[serde(rename_all = "lowercase")]
15pub enum SolanaCommitment {
16    /// Confirmed by a supermajority of the cluster.
17    Confirmed,
18    /// Finalized by the cluster.
19    Finalized,
20    /// Processed by the connected node.
21    Processed,
22}
23
24/// Solana account or transaction encoding.
25#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
26pub enum SolanaEncoding {
27    /// Base58 encoding.
28    #[serde(rename = "base58")]
29    Base58,
30    /// Base64 encoding.
31    #[serde(rename = "base64")]
32    Base64,
33    /// Zstandard-compressed base64 encoding.
34    #[serde(rename = "base64+zstd")]
35    Base64Zstd,
36    /// Parsed JSON encoding.
37    #[serde(rename = "jsonParsed")]
38    JsonParsed,
39}
40
41/// Standard Solana response context.
42#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
43#[serde(rename_all = "camelCase")]
44pub struct SolanaContext {
45    /// RPC software API version when supplied.
46    pub api_version: Option<String>,
47    /// Context slot.
48    pub slot: u64,
49}
50
51/// Value wrapped with a Solana response context.
52#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
53pub struct SolanaContextResult<T> {
54    /// Response context.
55    pub context: SolanaContext,
56    /// Method result.
57    pub value: T,
58}
59
60/// Priority fee estimate with forward-compatible additional fields.
61#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
62#[serde(rename_all = "camelCase")]
63pub struct PriorityFeeEstimate {
64    /// Estimated priority fee.
65    pub priority_fee_estimate: f64,
66    /// Forward-compatible response fields.
67    #[serde(flatten)]
68    pub additional: HashMap<String, Value>,
69}
70
71/// Named request for one indexed asset or proof.
72#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
73#[serde(rename_all = "camelCase")]
74pub struct AssetRequest {
75    /// Asset identifier.
76    pub id: String,
77    /// Optional display flags.
78    pub display_options: Option<HashMap<String, bool>>,
79}
80
81/// Named request for a batch of indexed assets or proofs.
82#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
83#[serde(rename_all = "camelCase")]
84pub struct AssetBatchRequest {
85    /// Asset identifiers.
86    pub ids: Vec<String>,
87    /// Optional display flags.
88    pub display_options: Option<HashMap<String, bool>>,
89}
90
91/// Shared indexed-asset pagination request.
92#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
93#[serde(rename_all = "camelCase")]
94pub struct AssetListRequest {
95    /// Cursor pagination token.
96    pub cursor: Option<String>,
97    /// Maximum item count.
98    pub limit: Option<u64>,
99    /// Page number.
100    pub page: Option<u64>,
101    /// Method-specific named parameters.
102    #[serde(flatten)]
103    pub additional: HashMap<String, Value>,
104}
105
106/// Forward-compatible indexed asset object.
107pub type IndexedAsset = HashMap<String, Value>;
108/// Forward-compatible indexed asset proof object.
109pub type IndexedAssetProof = HashMap<String, Value>;
110
111/// Paginated indexed-asset list.
112#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
113pub struct IndexedAssetList<T = IndexedAsset> {
114    /// Next cursor when available.
115    pub cursor: Option<String>,
116    /// Returned items.
117    pub items: Vec<T>,
118    /// Effective page limit.
119    pub limit: Option<u64>,
120    /// Effective page number.
121    pub page: Option<u64>,
122    /// Total item count when supplied.
123    pub total: Option<u64>,
124    /// Forward-compatible response fields.
125    #[serde(flatten)]
126    pub additional: HashMap<String, Value>,
127}
128
129/// Numeric range filter for indexed history.
130#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
131pub struct NumericFilter {
132    /// Equal to.
133    pub eq: Option<f64>,
134    /// Greater than.
135    pub gt: Option<f64>,
136    /// Greater than or equal to.
137    pub gte: Option<f64>,
138    /// Less than.
139    pub lt: Option<f64>,
140    /// Less than or equal to.
141    pub lte: Option<f64>,
142}
143
144/// Options for indexed address transactions.
145#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
146#[serde(rename_all = "camelCase")]
147pub struct AddressTransactionsOptions {
148    /// Return signatures before this signature.
149    pub before: Option<String>,
150    /// Requested commitment.
151    pub commitment: Option<SolanaCommitment>,
152    /// Transaction encoding.
153    pub encoding: Option<String>,
154    /// Additional indexed filters.
155    pub filters: Option<HashMap<String, Value>>,
156    /// Maximum item count.
157    pub limit: Option<u64>,
158    /// Maximum supported transaction version.
159    pub max_supported_transaction_version: Option<u64>,
160    /// Opaque pagination token.
161    pub pagination_token: Option<String>,
162    /// Sort order.
163    pub sort_order: Option<String>,
164    /// Transaction detail level.
165    pub transaction_details: Option<String>,
166    /// Return signatures up to this signature.
167    pub until: Option<String>,
168}
169
170/// One indexed address transaction.
171#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
172#[serde(rename_all = "camelCase")]
173pub struct AddressTransaction {
174    /// Block time.
175    pub block_time: Option<i64>,
176    /// Confirmation status.
177    pub confirmation_status: SolanaCommitment,
178    /// Transaction error.
179    pub err: Value,
180    /// Memo when present.
181    pub memo: Option<String>,
182    /// Transaction metadata when requested.
183    pub meta: Option<Value>,
184    /// Transaction signature.
185    pub signature: String,
186    /// Slot.
187    pub slot: u64,
188    /// Transaction body when requested.
189    pub transaction: Option<Value>,
190    /// Index within the block.
191    pub transaction_index: u64,
192    /// Transaction version when supplied.
193    pub version: Option<Value>,
194    /// Forward-compatible response fields.
195    #[serde(flatten)]
196    pub additional: HashMap<String, Value>,
197}
198
199/// Paginated indexed address transactions.
200#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
201#[serde(rename_all = "camelCase")]
202pub struct AddressTransactionPage {
203    /// Transactions.
204    pub data: Vec<AddressTransaction>,
205    /// Next pagination token.
206    pub pagination_token: Option<String>,
207    /// Earliest slot or time in the current window.
208    pub window_start: Option<i64>,
209}
210
211/// Direction for an indexed transfer query.
212#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
213#[serde(rename_all = "lowercase")]
214pub enum AddressTransferDirection {
215    /// Transfers in either direction.
216    Any,
217    /// Incoming transfers.
218    In,
219    /// Outgoing transfers.
220    Out,
221}
222
223/// Numeric filters for indexed transfers.
224#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
225#[serde(rename_all = "camelCase")]
226pub struct AddressTransferFilters {
227    /// Amount filter.
228    pub amount: Option<NumericFilter>,
229    /// Block-time filter.
230    pub block_time: Option<NumericFilter>,
231    /// Slot filter.
232    pub slot: Option<NumericFilter>,
233}
234
235/// Options for indexed address transfers.
236#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
237#[serde(rename_all = "camelCase")]
238pub struct AddressTransfersOptions {
239    /// Requested commitment.
240    pub commitment: Option<SolanaCommitment>,
241    /// Transfer direction.
242    pub direction: Option<AddressTransferDirection>,
243    /// Numeric filters.
244    pub filters: Option<AddressTransferFilters>,
245    /// Maximum item count.
246    pub limit: Option<u64>,
247    /// Optional mint filter.
248    pub mint: Option<String>,
249    /// Opaque pagination token.
250    pub pagination_token: Option<String>,
251    /// Native transfer projection mode.
252    pub sol_mode: Option<String>,
253    /// Sort order.
254    pub sort_order: Option<String>,
255    /// Counterparty filter.
256    pub with: Option<String>,
257}
258
259/// Indexed transfer operation.
260#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
261pub enum AddressTransferType {
262    /// Token burn.
263    #[serde(rename = "burn")]
264    Burn,
265    /// Account owner change.
266    #[serde(rename = "changeOwner")]
267    ChangeOwner,
268    /// Token mint.
269    #[serde(rename = "mint")]
270    Mint,
271    /// Token or native transfer.
272    #[serde(rename = "transfer")]
273    Transfer,
274    /// Native token unwrap.
275    #[serde(rename = "unwrap")]
276    Unwrap,
277    /// Withheld fee withdrawal.
278    #[serde(rename = "withdrawWithheldFee")]
279    WithdrawWithheldFee,
280    /// Native token wrap.
281    #[serde(rename = "wrap")]
282    Wrap,
283}
284
285/// One indexed address transfer.
286#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
287#[serde(rename_all = "camelCase")]
288pub struct AddressTransfer {
289    /// Integer amount string.
290    pub amount: String,
291    /// Block time.
292    pub block_time: Option<i64>,
293    /// Confirmation status.
294    pub confirmation_status: SolanaCommitment,
295    /// Mint decimals.
296    pub decimals: u8,
297    /// Integer fee amount.
298    pub fee_amount: Option<String>,
299    /// Display fee amount.
300    pub fee_ui_amount: Option<String>,
301    /// Source token account.
302    pub from_token_account: Option<String>,
303    /// Source user account.
304    pub from_user_account: Option<String>,
305    /// Inner instruction index.
306    pub inner_instruction_idx: u64,
307    /// Instruction index.
308    pub instruction_idx: u64,
309    /// Mint address for token transfers.
310    pub mint: Option<String>,
311    /// Transaction signature.
312    pub signature: String,
313    /// Slot.
314    pub slot: u64,
315    /// Destination token account.
316    pub to_token_account: Option<String>,
317    /// Destination user account.
318    pub to_user_account: Option<String>,
319    /// Transaction index.
320    pub transaction_idx: u64,
321    /// Transfer operation.
322    #[serde(rename = "type")]
323    pub transfer_type: AddressTransferType,
324    /// Display amount.
325    pub ui_amount: String,
326    /// Forward-compatible response fields.
327    #[serde(flatten)]
328    pub additional: HashMap<String, Value>,
329}
330
331/// Paginated indexed address transfers.
332#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
333#[serde(rename_all = "camelCase")]
334pub struct AddressTransferPage {
335    /// Transfers.
336    pub data: Vec<AddressTransfer>,
337    /// Next pagination token.
338    pub pagination_token: Option<String>,
339    /// Earliest slot or time in the current window.
340    pub window_start: Option<i64>,
341}
342
343/// One network measurement to a scheduled leader.
344#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
345#[serde(rename_all = "camelCase")]
346pub struct PingMeasurement {
347    /// City inferred from the target address.
348    pub city: Option<String>,
349    /// Country inferred from the target address.
350    pub country: Option<String>,
351    /// Measurement source address.
352    pub from_ip: Option<String>,
353    /// Whether ICMP replied.
354    pub icmp_replied: bool,
355    /// Latitude.
356    pub lat: Option<f64>,
357    /// Longitude.
358    pub lon: Option<f64>,
359    /// Measurement timestamp.
360    pub measured_at: Option<String>,
361    /// Round-trip milliseconds.
362    pub ms: Option<f64>,
363    /// Network organization.
364    pub org: Option<String>,
365    /// Postal code.
366    pub postal: Option<String>,
367    /// Region.
368    pub region: Option<String>,
369    /// Time zone.
370    pub timezone: Option<String>,
371    /// Forward-compatible response fields.
372    #[serde(flatten)]
373    pub additional: HashMap<String, Value>,
374}
375
376/// Scheduled leader and public network metadata.
377#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
378#[serde(rename_all = "camelCase")]
379pub struct LeaderSlot {
380    /// Epoch.
381    pub epoch: u64,
382    /// Feature-set identifier.
383    pub feature_set: Option<String>,
384    /// Gossip port.
385    pub gossip_port: Option<u16>,
386    /// Gossip observation timestamp.
387    pub gossip_updated_at: Option<String>,
388    /// Validator identity.
389    pub identity: String,
390    /// Public IP address.
391    pub ip_address: Option<String>,
392    /// Leader city.
393    pub leader_city: Option<String>,
394    /// Leader country.
395    pub leader_country: Option<String>,
396    /// Leader latitude.
397    pub leader_lat: Option<f64>,
398    /// Leader longitude.
399    pub leader_lon: Option<f64>,
400    /// Leader network organization.
401    pub leader_org: Option<String>,
402    /// Leader region.
403    pub leader_region: Option<String>,
404    /// Leader time zone.
405    pub leader_timezone: Option<String>,
406    /// Measurements to scheduled leaders.
407    pub ping_to_leaders: Vec<PingMeasurement>,
408    /// Public RPC address.
409    pub rpc_address: Option<String>,
410    /// Slot represented as a decimal string.
411    pub slot: String,
412    /// Stake weight.
413    pub stake_weight: f64,
414    /// TPU port.
415    pub tpu_port: Option<u16>,
416    /// QUIC TPU port.
417    pub tpu_quic_port: Option<u16>,
418    /// Validator software version.
419    pub version: Option<String>,
420    /// Forward-compatible response fields.
421    #[serde(flatten)]
422    pub additional: HashMap<String, Value>,
423}
424
425/// Leader slot response envelope.
426#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
427pub struct LeaderSlotsResult {
428    /// Leader slots.
429    pub data: Vec<LeaderSlot>,
430    /// Service message.
431    pub message: String,
432    /// Success flag.
433    pub success: bool,
434    /// Returned row count.
435    pub total: u64,
436    /// Forward-compatible response fields.
437    #[serde(flatten)]
438    pub additional: HashMap<String, Value>,
439}
440
441/// Validator information query.
442#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
443pub struct ValidatorsInformationOptions {
444    /// Country filter.
445    pub country: Option<String>,
446    /// Maximum validator count.
447    pub limit: Option<u64>,
448    /// Region filter.
449    pub region: Option<String>,
450}
451
452/// Validator information and public network metadata.
453#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
454#[serde(rename_all = "camelCase")]
455pub struct ValidatorInformation {
456    /// Feature-set identifier.
457    pub feature_set: Option<String>,
458    /// Gossip database row identifier.
459    pub gossip_node_id: Option<u64>,
460    /// Gossip port.
461    pub gossip_port: Option<u16>,
462    /// Gossip observation timestamp.
463    pub gossip_updated_at: Option<String>,
464    /// Validator identity.
465    pub identity: String,
466    /// Public IP address.
467    pub ip_address: Option<String>,
468    /// Validator city.
469    pub leader_city: Option<String>,
470    /// Validator country.
471    pub leader_country: Option<String>,
472    /// Validator latitude.
473    pub leader_lat: Option<f64>,
474    /// Validator longitude.
475    pub leader_lon: Option<f64>,
476    /// Validator network organization.
477    pub leader_org: Option<String>,
478    /// Validator region.
479    pub leader_region: Option<String>,
480    /// Validator time zone.
481    pub leader_timezone: Option<String>,
482    /// Measurements to scheduled leaders.
483    pub ping_to_leaders: Vec<PingMeasurement>,
484    /// Public RPC address.
485    pub rpc_address: Option<String>,
486    /// Scheduled slot count.
487    pub slot_count: u64,
488    /// Stake weight.
489    pub stake_weight: f64,
490    /// TPU port.
491    pub tpu_port: Option<u16>,
492    /// QUIC TPU port.
493    pub tpu_quic_port: Option<u16>,
494    /// Validator software version.
495    pub version: Option<String>,
496    /// Forward-compatible response fields.
497    #[serde(flatten)]
498    pub additional: HashMap<String, Value>,
499}
500
501/// Validator information response envelope.
502#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
503#[serde(rename_all = "camelCase")]
504pub struct ValidatorsInformationResult {
505    /// Validators.
506    pub data: Vec<ValidatorInformation>,
507    /// Epoch.
508    pub epoch: u64,
509    /// Service message.
510    pub message: String,
511    /// Success flag.
512    pub success: bool,
513    /// Returned row count.
514    pub total: u64,
515    /// Total validator count before limiting.
516    pub total_validators: u64,
517    /// Forward-compatible response fields.
518    #[serde(flatten)]
519    pub additional: HashMap<String, Value>,
520}
521
522/// Number or timestamp string accepted by analytics time bounds.
523#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
524#[serde(untagged)]
525pub enum AnalyticsTimeBound {
526    /// Numeric Unix timestamp.
527    Number(i64),
528    /// Server-supported timestamp string.
529    String(String),
530}
531
532/// Top-program analytics options.
533#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
534#[serde(rename_all = "camelCase")]
535pub struct TopProgramsOptions {
536    /// Include vote transactions.
537    pub include_votes: Option<bool>,
538    /// Maximum row count.
539    pub limit: Option<u64>,
540    /// Inclusive lower time bound.
541    pub since: Option<AnalyticsTimeBound>,
542    /// Exclusive upper time bound.
543    pub until: Option<AnalyticsTimeBound>,
544}
545
546/// One top-program analytics row.
547#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
548pub struct TopProgramRow {
549    /// Error count as a decimal string.
550    pub errors: String,
551    /// Invocation count as a decimal string.
552    pub invocations: String,
553    /// Program address.
554    pub program: String,
555    /// Total compute units as a decimal string.
556    pub total_cus: String,
557    /// Forward-compatible response fields.
558    #[serde(flatten)]
559    pub additional: HashMap<String, Value>,
560}
561
562/// Slot statistics query by one slot or inclusive range.
563#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
564#[serde(untagged)]
565pub enum SlotStatsOptions {
566    /// One slot.
567    Slot {
568        /// Slot number.
569        slot: u64,
570    },
571    /// Slot range.
572    Range {
573        /// First slot.
574        #[serde(rename = "fromSlot")]
575        from_slot: u64,
576        /// Last slot.
577        #[serde(rename = "toSlot")]
578        to_slot: u64,
579    },
580}
581
582/// One slot statistics row.
583#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
584pub struct SlotStatsRow {
585    /// Block time.
586    pub block_time: i64,
587    /// Non-vote transaction count.
588    pub non_vote_transaction_count: u64,
589    /// Slot.
590    pub slot: u64,
591    /// Total transaction count.
592    pub transaction_count: u64,
593    /// Vote transaction count.
594    pub vote_transaction_count: u64,
595    /// Forward-compatible response fields.
596    #[serde(flatten)]
597    pub additional: HashMap<String, Value>,
598}
599
600/// TPS time-series options.
601#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
602#[serde(rename_all = "camelCase")]
603pub struct TpsTimeseriesOptions {
604    /// Bucket width in seconds.
605    pub bucket_sec: Option<u64>,
606    /// Inclusive lower time bound.
607    pub from: AnalyticsTimeBound,
608    /// Exclusive upper time bound.
609    pub to: AnalyticsTimeBound,
610}
611
612/// One TPS time bucket.
613#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
614pub struct TpsBucket {
615    /// Bucket timestamp.
616    pub bucket: i64,
617    /// Non-vote TPS.
618    pub non_vote_tps: f64,
619    /// Total TPS.
620    pub total_tps: f64,
621    /// Forward-compatible response fields.
622    #[serde(flatten)]
623    pub additional: HashMap<String, Value>,
624}
625
626/// Epoch analytics summary.
627#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
628pub struct EpochSummary {
629    /// Distinct invoked programs.
630    pub distinct_programs: String,
631    /// Epoch.
632    pub epoch: u64,
633    /// First block time.
634    pub first_block_time: i64,
635    /// Last block time.
636    pub last_block_time: i64,
637    /// Non-vote transaction count.
638    pub non_vote_txs: String,
639    /// Program invocation count.
640    pub program_invocations: String,
641    /// Slot count.
642    pub slots: String,
643    /// Total transaction count.
644    pub total_txs: String,
645    /// Vote transaction count.
646    pub vote_txs: String,
647    /// Forward-compatible response fields.
648    #[serde(flatten)]
649    pub additional: HashMap<String, Value>,
650}
651
652/// Program statistics options.
653#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
654#[serde(rename_all = "camelCase")]
655pub struct ProgramStatsOptions {
656    /// Bucket width in seconds.
657    pub bucket_sec: Option<u64>,
658    /// Program address.
659    pub program_id_base58: String,
660    /// Inclusive lower time bound.
661    pub since: Option<AnalyticsTimeBound>,
662    /// Exclusive upper time bound.
663    pub until: Option<AnalyticsTimeBound>,
664}
665
666/// One program statistics time bucket.
667#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
668pub struct ProgramStatsBucket {
669    /// Bucket timestamp.
670    pub bucket: i64,
671    /// Error count as a decimal string.
672    pub errors: String,
673    /// Invocation count as a decimal string.
674    pub invocations: String,
675    /// Total compute units as a decimal string.
676    pub total_cus: String,
677    /// Forward-compatible response fields.
678    #[serde(flatten)]
679    pub additional: HashMap<String, Value>,
680}
681
682/// Standard Solana JSON-RPC methods represented by this release.
683pub const SOLANA_RPC_METHODS: &[&str] = &[
684    "getAccountInfo",
685    "getBalance",
686    "getBlock",
687    "getBlockCommitment",
688    "getBlockHeight",
689    "getBlockProduction",
690    "getBlockTime",
691    "getBlocks",
692    "getBlocksWithLimit",
693    "getClusterNodes",
694    "getEpochInfo",
695    "getEpochSchedule",
696    "getFeeForMessage",
697    "getFirstAvailableBlock",
698    "getGenesisHash",
699    "getHealth",
700    "getHighestSnapshotSlot",
701    "getIdentity",
702    "getInflationGovernor",
703    "getInflationRate",
704    "getInflationReward",
705    "getLargestAccounts",
706    "getLatestBlockhash",
707    "getLeaderSchedule",
708    "getMaxRetransmitSlot",
709    "getMaxShredInsertSlot",
710    "getMinimumBalanceForRentExemption",
711    "getMultipleAccounts",
712    "getParsedTransaction",
713    "getPriorityFeeEstimate",
714    "getProgramAccounts",
715    "getProgramAccountsV2",
716    "getRecentPerformanceSamples",
717    "getRecentPrioritizationFees",
718    "getSignatureStatuses",
719    "getSignaturesForAddress",
720    "getSlot",
721    "getSlotLeader",
722    "getSlotLeaders",
723    "getStakeMinimumDelegation",
724    "getSupply",
725    "getTokenAccountBalance",
726    "getTokenAccountsByDelegate",
727    "getTokenAccountsByOwner",
728    "getTokenLargestAccounts",
729    "getTokenSupply",
730    "getTransaction",
731    "getTransactionCount",
732    "getVersion",
733    "getVoteAccounts",
734    "isBlockhashValid",
735    "minimumLedgerSlot",
736    "requestAirdrop",
737    "sendTransaction",
738    "simulateTransaction",
739];
740
741/// Indexed asset RPC methods represented by this release.
742pub const SOLANA_DAS_METHODS: &[&str] = &[
743    "getAsset",
744    "getAssetBatch",
745    "getAssetProof",
746    "getAssetProofBatch",
747    "getAssetsByAuthority",
748    "getAssetsByCreator",
749    "getAssetsByGroup",
750    "getAssetsByOwner",
751    "getNftEditions",
752    "getSignaturesForAsset",
753    "getTokenAccounts",
754    "getTokensByDelegate",
755    "getTokensByOwner",
756    "searchAssets",
757];
758
759/// Indexed address history RPC methods represented by this release.
760pub const SOLANA_HISTORY_METHODS: &[&str] = &["getTransactionsForAddress", "getTransfersByAddress"];
761
762/// Leader information RPC methods represented by this release.
763pub const SOLANA_LEADER_METHODS: &[&str] = &["getLeaderSlots", "getValidatorsInformation"];
764
765/// Analytics RPC methods represented by this release.
766pub const SOLANA_ANALYTICS_METHODS: &[&str] = &[
767    "jetEpochSummary",
768    "jetProgramStats",
769    "jetSlotStats",
770    "jetTopPrograms",
771    "jetTpsTimeseries",
772];
773
774/// Standard Solana JSON-RPC namespace.
775#[derive(Clone)]
776pub struct SolanaRpcClient {
777    namespace: RpcNamespace,
778}
779
780impl SolanaRpcClient {
781    const fn new(transport: Arc<HttpJsonRpcTransport>) -> Self {
782        Self {
783            namespace: RpcNamespace::new(transport, BatchPolicy::SolanaStandard),
784        }
785    }
786}
787
788impl Deref for SolanaRpcClient {
789    type Target = RpcNamespace;
790
791    fn deref(&self) -> &Self::Target {
792        &self.namespace
793    }
794}
795
796macro_rules! solana_no_params {
797    ($(($name:ident, $wire:literal, $result:ty)),* $(,)?) => {
798        impl SolanaRpcClient {
799            $(
800                #[doc = concat!("Creates a pending `", $wire, "` request.")]
801                #[must_use]
802                pub fn $name(&self) -> PendingRpcRequest<$result> {
803                    self.namespace.request($wire, Vec::<Value>::new()).expect("empty parameters serialize")
804                }
805            )*
806        }
807    };
808}
809
810macro_rules! solana_with_params {
811    ($(($name:ident, $wire:literal, $result:ty)),* $(,)?) => {
812        impl SolanaRpcClient {
813            $(
814                #[doc = concat!("Creates a pending `", $wire, "` request from positional parameters.")]
815                pub fn $name<P: Serialize>(&self, params: P) -> Result<PendingRpcRequest<$result>> {
816                    self.namespace.request($wire, params)
817                }
818            )*
819        }
820    };
821}
822
823solana_no_params!(
824    (get_cluster_nodes, "getClusterNodes", Value),
825    (get_epoch_schedule, "getEpochSchedule", Value),
826    (get_first_available_block, "getFirstAvailableBlock", u64),
827    (get_genesis_hash, "getGenesisHash", String),
828    (get_health, "getHealth", String),
829    (get_highest_snapshot_slot, "getHighestSnapshotSlot", Value),
830    (get_identity, "getIdentity", Value),
831    (get_inflation_rate, "getInflationRate", Value),
832    (get_max_retransmit_slot, "getMaxRetransmitSlot", u64),
833    (get_max_shred_insert_slot, "getMaxShredInsertSlot", u64),
834    (get_version, "getVersion", Value),
835    (minimum_ledger_slot, "minimumLedgerSlot", u64),
836);
837
838solana_with_params!(
839    (get_account_info, "getAccountInfo", SolanaContextResult<Option<Value>>),
840    (get_balance, "getBalance", SolanaContextResult<u64>),
841    (get_block, "getBlock", Option<Value>),
842    (get_block_commitment, "getBlockCommitment", Value),
843    (get_block_height, "getBlockHeight", u64),
844    (get_block_production, "getBlockProduction", Value),
845    (get_block_time, "getBlockTime", Option<i64>),
846    (get_blocks, "getBlocks", Vec<u64>),
847    (get_blocks_with_limit, "getBlocksWithLimit", Vec<u64>),
848    (get_epoch_info, "getEpochInfo", Value),
849    (get_fee_for_message, "getFeeForMessage", SolanaContextResult<Option<u64>>),
850    (get_inflation_governor, "getInflationGovernor", Value),
851    (get_inflation_reward, "getInflationReward", Value),
852    (get_largest_accounts, "getLargestAccounts", Value),
853    (get_latest_blockhash, "getLatestBlockhash", Value),
854    (get_leader_schedule, "getLeaderSchedule", Option<Value>),
855    (
856        get_minimum_balance_for_rent_exemption,
857        "getMinimumBalanceForRentExemption",
858        u64
859    ),
860    (get_multiple_accounts, "getMultipleAccounts", SolanaContextResult<Value>),
861    (get_parsed_transaction, "getParsedTransaction", Option<Value>),
862    (
863        get_priority_fee_estimate,
864        "getPriorityFeeEstimate",
865        PriorityFeeEstimate
866    ),
867    (get_program_accounts, "getProgramAccounts", Value),
868    (get_program_accounts_v2, "getProgramAccountsV2", Value),
869    (get_recent_performance_samples, "getRecentPerformanceSamples", Value),
870    (
871        get_recent_prioritization_fees,
872        "getRecentPrioritizationFees",
873        Value
874    ),
875    (get_signature_statuses, "getSignatureStatuses", Value),
876    (get_signatures_for_address, "getSignaturesForAddress", Value),
877    (get_slot, "getSlot", u64),
878    (get_slot_leader, "getSlotLeader", String),
879    (get_slot_leaders, "getSlotLeaders", Vec<String>),
880    (
881        get_stake_minimum_delegation,
882        "getStakeMinimumDelegation",
883        SolanaContextResult<u64>
884    ),
885    (get_supply, "getSupply", Value),
886    (get_token_account_balance, "getTokenAccountBalance", Value),
887    (
888        get_token_accounts_by_delegate,
889        "getTokenAccountsByDelegate",
890        Value
891    ),
892    (get_token_accounts_by_owner, "getTokenAccountsByOwner", Value),
893    (get_token_largest_accounts, "getTokenLargestAccounts", Value),
894    (get_token_supply, "getTokenSupply", Value),
895    (get_transaction, "getTransaction", Option<Value>),
896    (get_transaction_count, "getTransactionCount", u64),
897    (get_vote_accounts, "getVoteAccounts", Value),
898    (
899        is_blockhash_valid,
900        "isBlockhashValid",
901        SolanaContextResult<bool>
902    ),
903    (request_airdrop, "requestAirdrop", String),
904    (send_transaction, "sendTransaction", String),
905    (simulate_transaction, "simulateTransaction", Value),
906);
907
908macro_rules! namespace_client {
909    ($name:ident, $policy:expr, $(($method:ident, $wire:literal, $result:ty)),* $(,)?) => {
910        #[doc = concat!(stringify!($name), " JSON-RPC namespace.")]
911        #[derive(Clone)]
912        pub struct $name {
913            namespace: RpcNamespace,
914        }
915
916        impl $name {
917            const fn new(transport: Arc<HttpJsonRpcTransport>) -> Self {
918                Self { namespace: RpcNamespace::new(transport, $policy) }
919            }
920
921            $(
922                #[doc = concat!("Creates a pending `", $wire, "` request.")]
923                pub fn $method<P: Serialize>(&self, params: P) -> Result<PendingRpcRequest<$result>> {
924                    self.namespace.request($wire, params)
925                }
926            )*
927        }
928
929        impl Deref for $name {
930            type Target = RpcNamespace;
931
932            fn deref(&self) -> &Self::Target {
933                &self.namespace
934            }
935        }
936    };
937}
938
939namespace_client!(
940    SolanaDasClient,
941    BatchPolicy::Any,
942    (get_asset, "getAsset", Option<IndexedAsset>),
943    (
944        get_asset_batch,
945        "getAssetBatch",
946        Vec<Option<IndexedAsset>>
947    ),
948    (get_asset_proof, "getAssetProof", Option<IndexedAssetProof>),
949    (
950        get_asset_proof_batch,
951        "getAssetProofBatch",
952        Vec<Option<IndexedAssetProof>>
953    ),
954    (
955        get_assets_by_authority,
956        "getAssetsByAuthority",
957        IndexedAssetList
958    ),
959    (
960        get_assets_by_creator,
961        "getAssetsByCreator",
962        IndexedAssetList
963    ),
964    (get_assets_by_group, "getAssetsByGroup", IndexedAssetList),
965    (get_assets_by_owner, "getAssetsByOwner", IndexedAssetList),
966    (get_nft_editions, "getNftEditions", HashMap<String, Value>),
967    (
968        get_signatures_for_asset,
969        "getSignaturesForAsset",
970        HashMap<String, Value>
971    ),
972    (
973        get_token_accounts,
974        "getTokenAccounts",
975        HashMap<String, Value>
976    ),
977    (
978        get_tokens_by_delegate,
979        "getTokensByDelegate",
980        HashMap<String, Value>
981    ),
982    (
983        get_tokens_by_owner,
984        "getTokensByOwner",
985        HashMap<String, Value>
986    ),
987    (search_assets, "searchAssets", IndexedAssetList),
988);
989
990namespace_client!(
991    SolanaHistoryClient,
992    BatchPolicy::Any,
993    (
994        get_transactions_for_address,
995        "getTransactionsForAddress",
996        Option<AddressTransactionPage>
997    ),
998    (
999        get_transfers_by_address,
1000        "getTransfersByAddress",
1001        AddressTransferPage
1002    ),
1003);
1004
1005namespace_client!(
1006    SolanaLeaderClient,
1007    BatchPolicy::Unsupported,
1008    (get_leader_slots, "getLeaderSlots", LeaderSlotsResult),
1009    (
1010        get_validators_information,
1011        "getValidatorsInformation",
1012        ValidatorsInformationResult
1013    ),
1014);
1015
1016namespace_client!(
1017    SolanaAnalyticsClient,
1018    BatchPolicy::Any,
1019    (jet_epoch_summary, "jetEpochSummary", Option<EpochSummary>),
1020    (
1021        jet_program_stats,
1022        "jetProgramStats",
1023        Vec<ProgramStatsBucket>
1024    ),
1025    (jet_slot_stats, "jetSlotStats", Vec<SlotStatsRow>),
1026    (jet_top_programs, "jetTopPrograms", Vec<TopProgramRow>),
1027    (jet_tps_timeseries, "jetTpsTimeseries", Vec<TpsBucket>),
1028);
1029
1030/// Solana enhanced WebSocket subscription methods.
1031pub const SOLANA_ENHANCED_SUBSCRIPTION_METHODS: &[&str] = &[
1032    "accountSubscribe",
1033    "accountUnsubscribe",
1034    "transactionSubscribe",
1035    "transactionUnsubscribe",
1036];
1037
1038/// Solana WebSocket subscription client.
1039#[derive(Clone)]
1040pub struct SolanaSubscriptions {
1041    transport: Arc<WebSocketJsonRpcTransport>,
1042}
1043
1044impl SolanaSubscriptions {
1045    pub(crate) const fn new(transport: Arc<WebSocketJsonRpcTransport>) -> Self {
1046        Self { transport }
1047    }
1048
1049    /// Credential-free WebSocket endpoint.
1050    #[must_use]
1051    pub fn endpoint(&self) -> &str {
1052        self.transport.endpoint()
1053    }
1054
1055    /// Starts an `accountSubscribe` subscription.
1056    pub async fn account_subscribe(
1057        &self,
1058        address: &str,
1059        options: Option<Value>,
1060    ) -> Result<RpcSubscription> {
1061        let mut params = vec![Value::String(address.to_owned())];
1062        if let Some(options) = options {
1063            params.push(options);
1064        }
1065        self.raw_subscribe(
1066            "accountSubscribe",
1067            Value::Array(params),
1068            "accountUnsubscribe",
1069        )
1070        .await
1071    }
1072
1073    /// Starts a `transactionSubscribe` subscription.
1074    pub async fn transaction_subscribe(
1075        &self,
1076        filter: Value,
1077        options: Option<Value>,
1078    ) -> Result<RpcSubscription> {
1079        let mut params = vec![filter];
1080        if let Some(options) = options {
1081            params.push(options);
1082        }
1083        self.raw_subscribe(
1084            "transactionSubscribe",
1085            Value::Array(params),
1086            "transactionUnsubscribe",
1087        )
1088        .await
1089    }
1090
1091    /// Starts an arbitrary subscribe/unsubscribe method pair.
1092    pub async fn raw_subscribe(
1093        &self,
1094        subscribe_method: &str,
1095        params: Value,
1096        unsubscribe_method: &str,
1097    ) -> Result<RpcSubscription> {
1098        let receiver = self.transport.subscribe_notifications();
1099        let id: crate::SubscriptionId = self
1100            .transport
1101            .request(subscribe_method, params, None)
1102            .await?;
1103        Ok(RpcSubscription::new(
1104            id,
1105            Arc::clone(&self.transport),
1106            unsubscribe_method,
1107            receiver,
1108        ))
1109    }
1110
1111    /// Sends an arbitrary request on the subscription connection.
1112    pub async fn raw<T: DeserializeOwned>(&self, method: &str, params: Value) -> Result<T> {
1113        self.transport.request(method, params, None).await
1114    }
1115
1116    /// Closes the WebSocket connection.
1117    pub async fn close(&self) {
1118        self.transport.close().await;
1119    }
1120}
1121
1122/// Standard and extended Solana APIs.
1123#[derive(Clone)]
1124pub struct SolanaClient {
1125    /// Standard Solana JSON-RPC.
1126    pub rpc: SolanaRpcClient,
1127    /// Indexed asset RPC using named parameters.
1128    pub das: SolanaDasClient,
1129    /// Indexed address history RPC.
1130    pub history: SolanaHistoryClient,
1131    /// Leader information RPC. Batching is rejected locally.
1132    pub leaders: SolanaLeaderClient,
1133    /// Analytics RPC.
1134    pub analytics: SolanaAnalyticsClient,
1135    /// Enhanced WebSocket subscriptions.
1136    pub subscriptions: SolanaSubscriptions,
1137}
1138
1139impl SolanaClient {
1140    pub(crate) fn new(
1141        transport: Arc<HttpJsonRpcTransport>,
1142        websocket: Arc<WebSocketJsonRpcTransport>,
1143    ) -> Self {
1144        Self {
1145            rpc: SolanaRpcClient::new(Arc::clone(&transport)),
1146            das: SolanaDasClient::new(Arc::clone(&transport)),
1147            history: SolanaHistoryClient::new(Arc::clone(&transport)),
1148            leaders: SolanaLeaderClient::new(Arc::clone(&transport)),
1149            analytics: SolanaAnalyticsClient::new(transport),
1150            subscriptions: SolanaSubscriptions::new(websocket),
1151        }
1152    }
1153}