1use std::{
2 fmt::{Debug, Display, Formatter},
3 time::Duration,
4};
5
6use async_trait::async_trait;
7use borsh::BorshDeserialize;
8use bs58;
9use light_compressed_account::TreeType;
10use light_event::{
11 event::{BatchPublicTransactionEvent, PublicTransactionEvent},
12 parse::event_from_light_transaction,
13};
14use solana_account::Account;
15use solana_clock::Slot;
16use solana_commitment_config::CommitmentConfig;
17use solana_hash::Hash;
18use solana_instruction::Instruction;
19use solana_keypair::Keypair;
20use solana_message::{v0, AddressLookupTableAccount, VersionedMessage};
21use solana_pubkey::{pubkey, Pubkey};
22use solana_rpc_client::rpc_client::RpcClient;
23use solana_rpc_client_api::config::{RpcSendTransactionConfig, RpcTransactionConfig};
24use solana_signature::Signature;
25use solana_transaction::{versioned::VersionedTransaction, Transaction};
26use solana_transaction_status_client_types::{
27 option_serializer::OptionSerializer, TransactionStatus, UiInstruction, UiTransactionEncoding,
28};
29use tokio::time::{sleep, Instant};
30use tracing::warn;
31
32use super::LightClientConfig;
33use crate::{
34 indexer::{photon_indexer::PhotonIndexer, Indexer, TreeInfo},
35 rpc::{
36 errors::RpcError,
37 get_light_state_tree_infos::{
38 default_state_tree_lookup_tables, get_light_state_tree_infos,
39 },
40 merkle_tree::MerkleTreeExt,
41 Rpc,
42 },
43};
44
45pub enum RpcUrl {
46 Testnet,
47 Devnet,
48 Localnet,
49 ZKTestnet,
50 Custom(String),
51}
52
53impl Display for RpcUrl {
54 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
55 let str = match self {
56 RpcUrl::Testnet => "https://api.testnet.solana.com".to_string(),
57 RpcUrl::Devnet => "https://api.devnet.solana.com".to_string(),
58 RpcUrl::Localnet => "http://localhost:8899".to_string(),
59 RpcUrl::ZKTestnet => "https://zk-testnet.helius.dev:8899".to_string(),
60 RpcUrl::Custom(url) => url.clone(),
61 };
62 write!(f, "{}", str)
63 }
64}
65
66#[derive(Clone, Debug, Copy)]
67pub struct RetryConfig {
68 pub max_retries: u32,
69 pub retry_delay: Duration,
70 pub timeout: Duration,
73}
74
75impl Default for RetryConfig {
76 fn default() -> Self {
77 RetryConfig {
78 max_retries: 10,
79 retry_delay: Duration::from_secs(1),
80 timeout: Duration::from_secs(60),
81 }
82 }
83}
84
85#[allow(dead_code)]
86pub struct LightClient {
87 pub client: RpcClient,
88 pub payer: Keypair,
89 pub retry_config: RetryConfig,
90 pub indexer: Option<PhotonIndexer>,
91 pub state_merkle_trees: Vec<TreeInfo>,
92}
93
94impl Debug for LightClient {
95 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
96 write!(f, "LightClient {{ client: {:?} }}", self.client.url())
97 }
98}
99
100impl LightClient {
101 pub async fn new_with_retry(
102 config: LightClientConfig,
103 retry_config: Option<RetryConfig>,
104 ) -> Result<Self, RpcError> {
105 let payer = Keypair::new();
106 let commitment_config = config
107 .commitment_config
108 .unwrap_or(CommitmentConfig::confirmed());
109 let client = RpcClient::new_with_commitment(config.url.to_string(), commitment_config);
110 let retry_config = retry_config.unwrap_or_default();
111
112 let indexer = config
113 .photon_url
114 .map(|path| PhotonIndexer::new(path, config.api_key));
115
116 let mut new = Self {
117 client,
118 payer,
119 retry_config,
120 indexer,
121 state_merkle_trees: Vec::new(),
122 };
123 if config.fetch_active_tree {
124 new.get_latest_active_state_trees().await?;
125 }
126 Ok(new)
127 }
128
129 pub fn add_indexer(&mut self, path: String, api_key: Option<String>) {
130 self.indexer = Some(PhotonIndexer::new(path, api_key));
131 }
132
133 fn detect_network(&self) -> RpcUrl {
135 let url = self.client.url();
136
137 if url.contains("devnet") {
138 RpcUrl::Devnet
139 } else if url.contains("testnet") {
140 RpcUrl::Testnet
141 } else if url.contains("localhost") || url.contains("127.0.0.1") {
142 RpcUrl::Localnet
143 } else if url.contains("zk-testnet") {
144 RpcUrl::ZKTestnet
145 } else {
146 RpcUrl::Custom(url.to_string())
148 }
149 }
150
151 async fn retry<F, Fut, T>(&self, operation: F) -> Result<T, RpcError>
152 where
153 F: Fn() -> Fut,
154 Fut: std::future::Future<Output = Result<T, RpcError>>,
155 {
156 let mut attempts = 0;
157 let start_time = Instant::now();
158 loop {
159 match operation().await {
160 Ok(result) => return Ok(result),
161 Err(e) => {
162 let retry = self.should_retry(&e);
163 if retry {
164 attempts += 1;
165 if attempts >= self.retry_config.max_retries
166 || start_time.elapsed() >= self.retry_config.timeout
167 {
168 return Err(e);
169 }
170 warn!(
171 "Operation failed, retrying in {:?} (attempt {}/{}): {:?}",
172 self.retry_config.retry_delay,
173 attempts,
174 self.retry_config.max_retries,
175 e
176 );
177 sleep(self.retry_config.retry_delay).await;
178 } else {
179 return Err(e);
180 }
181 }
182 }
183 }
184 }
185
186 async fn _create_and_send_transaction_with_batched_event(
187 &mut self,
188 instructions: &[Instruction],
189 payer: &Pubkey,
190 signers: &[&Keypair],
191 ) -> Result<Option<(Vec<BatchPublicTransactionEvent>, Signature, Slot)>, RpcError> {
192 let latest_blockhash = self.client.get_latest_blockhash()?;
193
194 let mut instructions_vec = vec![
195 solana_compute_budget_interface::ComputeBudgetInstruction::set_compute_unit_limit(
196 1_000_000,
197 ),
198 ];
199 instructions_vec.extend_from_slice(instructions);
200
201 let transaction = Transaction::new_signed_with_payer(
202 instructions_vec.as_slice(),
203 Some(payer),
204 signers,
205 latest_blockhash,
206 );
207
208 let (signature, slot) = self
209 .process_transaction_with_context(transaction.clone())
210 .await?;
211
212 let mut vec = Vec::new();
213 let mut vec_accounts = Vec::new();
214 let mut program_ids = Vec::new();
215 instructions_vec.iter().for_each(|x| {
216 program_ids.push(light_compressed_account::Pubkey::new_from_array(
217 x.program_id.to_bytes(),
218 ));
219 vec.push(x.data.clone());
220 vec_accounts.push(
221 x.accounts
222 .iter()
223 .map(|x| light_compressed_account::Pubkey::new_from_array(x.pubkey.to_bytes()))
224 .collect(),
225 );
226 });
227 {
228 let rpc_transaction_config = RpcTransactionConfig {
229 encoding: Some(UiTransactionEncoding::Base64),
230 commitment: Some(self.client.commitment()),
231 ..Default::default()
232 };
233 let transaction = self
234 .client
235 .get_transaction_with_config(&signature, rpc_transaction_config)
236 .map_err(|e| RpcError::CustomError(e.to_string()))?;
237 let decoded_transaction = transaction
238 .transaction
239 .transaction
240 .decode()
241 .clone()
242 .unwrap();
243 let account_keys = decoded_transaction.message.static_account_keys();
244 let meta = transaction.transaction.meta.as_ref().ok_or_else(|| {
245 RpcError::CustomError("Transaction missing metadata information".to_string())
246 })?;
247 if meta.status.is_err() {
248 return Err(RpcError::CustomError(
249 "Transaction status indicates an error".to_string(),
250 ));
251 }
252
253 let inner_instructions = match &meta.inner_instructions {
254 OptionSerializer::Some(i) => i,
255 OptionSerializer::None => {
256 return Err(RpcError::CustomError(
257 "No inner instructions found".to_string(),
258 ));
259 }
260 OptionSerializer::Skip => {
261 return Err(RpcError::CustomError(
262 "No inner instructions found".to_string(),
263 ));
264 }
265 };
266
267 for ix in inner_instructions.iter() {
268 for ui_instruction in ix.instructions.iter() {
269 match ui_instruction {
270 UiInstruction::Compiled(ui_compiled_instruction) => {
271 let accounts = &ui_compiled_instruction.accounts;
272 let data = bs58::decode(&ui_compiled_instruction.data)
273 .into_vec()
274 .map_err(|_| {
275 RpcError::CustomError(
276 "Failed to decode instruction data".to_string(),
277 )
278 })?;
279 vec.push(data);
280 program_ids.push(light_compressed_account::Pubkey::new_from_array(
281 account_keys[ui_compiled_instruction.program_id_index as usize]
282 .to_bytes(),
283 ));
284 vec_accounts.push(
285 accounts
286 .iter()
287 .map(|x| {
288 light_compressed_account::Pubkey::new_from_array(
289 account_keys[(*x) as usize].to_bytes(),
290 )
291 })
292 .collect(),
293 );
294 }
295 UiInstruction::Parsed(_) => {
296 println!("Parsed instructions are not implemented yet");
297 }
298 }
299 }
300 }
301 }
302 let parsed_event =
303 event_from_light_transaction(program_ids.as_slice(), vec.as_slice(), vec_accounts)
304 .map_err(|e| RpcError::CustomError(format!("Failed to parse event: {e:?}")))?;
305 let event = parsed_event.map(|e| (e, signature, slot));
306 Ok(event)
307 }
308
309 async fn _create_and_send_transaction_with_event<T>(
310 &mut self,
311 instructions: &[Instruction],
312 payer: &Pubkey,
313 signers: &[&Keypair],
314 ) -> Result<Option<(T, Signature, u64)>, RpcError>
315 where
316 T: BorshDeserialize + Send + Debug,
317 {
318 let latest_blockhash = self.client.get_latest_blockhash()?;
319
320 let mut instructions_vec = vec![
321 solana_compute_budget_interface::ComputeBudgetInstruction::set_compute_unit_limit(
322 1_000_000,
323 ),
324 ];
325 instructions_vec.extend_from_slice(instructions);
326
327 let transaction = Transaction::new_signed_with_payer(
328 instructions_vec.as_slice(),
329 Some(payer),
330 signers,
331 latest_blockhash,
332 );
333
334 let (signature, slot) = self
335 .process_transaction_with_context(transaction.clone())
336 .await?;
337
338 let mut parsed_event = None;
339 for instruction in &transaction.message.instructions {
340 let ix_data = instruction.data.clone();
341 match T::deserialize(&mut &instruction.data[..]) {
342 Ok(e) => {
343 parsed_event = Some(e);
344 break;
345 }
346 Err(e) => {
347 warn!(
348 "Failed to parse event: {:?}, type: {:?}, ix data: {:?}",
349 e,
350 std::any::type_name::<T>(),
351 ix_data
352 );
353 }
354 }
355 }
356
357 if parsed_event.is_none() {
358 parsed_event = self.parse_inner_instructions::<T>(signature).ok();
359 }
360
361 let result = parsed_event.map(|e| (e, signature, slot));
362 Ok(result)
363 }
364}
365
366impl LightClient {
367 #[allow(clippy::result_large_err)]
368 fn parse_inner_instructions<T: BorshDeserialize>(
369 &self,
370 signature: Signature,
371 ) -> Result<T, RpcError> {
372 let rpc_transaction_config = RpcTransactionConfig {
373 encoding: Some(UiTransactionEncoding::Base64),
374 commitment: Some(self.client.commitment()),
375 ..Default::default()
376 };
377 let transaction = self
378 .client
379 .get_transaction_with_config(&signature, rpc_transaction_config)
380 .map_err(|e| RpcError::CustomError(e.to_string()))?;
381 let meta = transaction.transaction.meta.as_ref().ok_or_else(|| {
382 RpcError::CustomError("Transaction missing metadata information".to_string())
383 })?;
384 if meta.status.is_err() {
385 return Err(RpcError::CustomError(
386 "Transaction status indicates an error".to_string(),
387 ));
388 }
389
390 let inner_instructions = match &meta.inner_instructions {
391 OptionSerializer::Some(i) => i,
392 OptionSerializer::None => {
393 return Err(RpcError::CustomError(
394 "No inner instructions found".to_string(),
395 ));
396 }
397 OptionSerializer::Skip => {
398 return Err(RpcError::CustomError(
399 "No inner instructions found".to_string(),
400 ));
401 }
402 };
403
404 for ix in inner_instructions.iter() {
405 for ui_instruction in ix.instructions.iter() {
406 match ui_instruction {
407 UiInstruction::Compiled(ui_compiled_instruction) => {
408 let data = bs58::decode(&ui_compiled_instruction.data)
409 .into_vec()
410 .map_err(|_| {
411 RpcError::CustomError(
412 "Failed to decode instruction data".to_string(),
413 )
414 })?;
415
416 match T::try_from_slice(data.as_slice()) {
417 Ok(parsed_data) => return Ok(parsed_data),
418 Err(e) => {
419 warn!("Failed to parse inner instruction: {:?}", e);
420 }
421 }
422 }
423 UiInstruction::Parsed(_) => {
424 println!("Parsed instructions are not implemented yet");
425 }
426 }
427 }
428 }
429 Err(RpcError::CustomError(
430 "Failed to find any parseable inner instructions".to_string(),
431 ))
432 }
433}
434
435#[async_trait]
436impl Rpc for LightClient {
437 async fn new(config: LightClientConfig) -> Result<Self, RpcError>
438 where
439 Self: Sized,
440 {
441 Self::new_with_retry(config, None).await
442 }
443
444 fn get_payer(&self) -> &Keypair {
445 &self.payer
446 }
447
448 fn get_url(&self) -> String {
449 self.client.url()
450 }
451
452 async fn health(&self) -> Result<(), RpcError> {
453 self.retry(|| async { self.client.get_health().map_err(RpcError::from) })
454 .await
455 }
456
457 async fn get_program_accounts(
458 &self,
459 program_id: &Pubkey,
460 ) -> Result<Vec<(Pubkey, Account)>, RpcError> {
461 self.retry(|| async {
462 self.client
463 .get_program_accounts(program_id)
464 .map_err(RpcError::from)
465 })
466 .await
467 }
468
469 async fn get_program_accounts_with_discriminator(
470 &self,
471 program_id: &Pubkey,
472 discriminator: &[u8],
473 ) -> Result<Vec<(Pubkey, Account)>, RpcError> {
474 use solana_rpc_client_api::{
475 config::{RpcAccountInfoConfig, RpcProgramAccountsConfig},
476 filter::{Memcmp, RpcFilterType},
477 };
478
479 let discriminator = discriminator.to_vec();
480 self.retry(|| async {
481 let config = RpcProgramAccountsConfig {
482 filters: Some(vec![RpcFilterType::Memcmp(Memcmp::new_base58_encoded(
483 0,
484 &discriminator,
485 ))]),
486 account_config: RpcAccountInfoConfig {
487 encoding: Some(solana_account_decoder_client_types::UiAccountEncoding::Base64),
488 commitment: Some(self.client.commitment()),
489 ..Default::default()
490 },
491 ..Default::default()
492 };
493 self.client
494 .get_program_accounts_with_config(program_id, config)
495 .map_err(RpcError::from)
496 })
497 .await
498 }
499
500 async fn process_transaction(
501 &mut self,
502 transaction: Transaction,
503 ) -> Result<Signature, RpcError> {
504 self.retry(|| async {
505 self.client
506 .send_and_confirm_transaction(&transaction)
507 .map_err(RpcError::from)
508 })
509 .await
510 }
511
512 async fn process_transaction_with_context(
513 &mut self,
514 transaction: Transaction,
515 ) -> Result<(Signature, Slot), RpcError> {
516 self.retry(|| async {
517 let signature = self.client.send_and_confirm_transaction(&transaction)?;
518 let sig_info = self.client.get_signature_statuses(&[signature])?;
519 let slot = sig_info
520 .value
521 .first()
522 .and_then(|s| s.as_ref())
523 .map(|s| s.slot)
524 .ok_or_else(|| RpcError::CustomError("Failed to get slot".into()))?;
525 Ok((signature, slot))
526 })
527 .await
528 }
529
530 async fn confirm_transaction(&self, signature: Signature) -> Result<bool, RpcError> {
531 self.retry(|| async {
532 self.client
533 .confirm_transaction(&signature)
534 .map_err(RpcError::from)
535 })
536 .await
537 }
538
539 async fn get_account(&self, address: Pubkey) -> Result<Option<Account>, RpcError> {
540 self.retry(|| async {
541 self.client
542 .get_account_with_commitment(&address, self.client.commitment())
543 .map(|response| response.value)
544 .map_err(RpcError::from)
545 })
546 .await
547 }
548
549 async fn get_multiple_accounts(
550 &self,
551 addresses: &[Pubkey],
552 ) -> Result<Vec<Option<Account>>, RpcError> {
553 self.retry(|| async {
554 self.client
555 .get_multiple_accounts(addresses)
556 .map_err(RpcError::from)
557 })
558 .await
559 }
560
561 async fn get_minimum_balance_for_rent_exemption(
562 &self,
563 data_len: usize,
564 ) -> Result<u64, RpcError> {
565 self.retry(|| async {
566 self.client
567 .get_minimum_balance_for_rent_exemption(data_len)
568 .map_err(RpcError::from)
569 })
570 .await
571 }
572
573 async fn airdrop_lamports(
574 &mut self,
575 to: &Pubkey,
576 lamports: u64,
577 ) -> Result<Signature, RpcError> {
578 self.retry(|| async {
579 let signature = self
580 .client
581 .request_airdrop(to, lamports)
582 .map_err(RpcError::ClientError)?;
583 self.retry(|| async {
584 if self
585 .client
586 .confirm_transaction_with_commitment(&signature, self.client.commitment())?
587 .value
588 {
589 Ok(())
590 } else {
591 Err(RpcError::CustomError("Airdrop not confirmed".into()))
592 }
593 })
594 .await?;
595
596 Ok(signature)
597 })
598 .await
599 }
600
601 async fn get_balance(&self, pubkey: &Pubkey) -> Result<u64, RpcError> {
602 self.retry(|| async { self.client.get_balance(pubkey).map_err(RpcError::from) })
603 .await
604 }
605
606 async fn get_latest_blockhash(&mut self) -> Result<(Hash, u64), RpcError> {
607 self.retry(|| async {
608 self.client
609 .get_latest_blockhash_with_commitment(CommitmentConfig::confirmed())
612 .map_err(RpcError::from)
613 })
614 .await
615 }
616
617 async fn get_slot(&self) -> Result<u64, RpcError> {
618 self.retry(|| async { self.client.get_slot().map_err(RpcError::from) })
619 .await
620 }
621
622 async fn send_transaction(&self, transaction: &Transaction) -> Result<Signature, RpcError> {
623 self.retry(|| async {
624 self.client
625 .send_transaction_with_config(
626 transaction,
627 RpcSendTransactionConfig {
628 skip_preflight: true,
629 max_retries: Some(self.retry_config.max_retries as usize),
630 ..Default::default()
631 },
632 )
633 .map_err(RpcError::from)
634 })
635 .await
636 }
637
638 async fn send_transaction_with_config(
639 &self,
640 transaction: &Transaction,
641 config: RpcSendTransactionConfig,
642 ) -> Result<Signature, RpcError> {
643 self.retry(|| async {
644 self.client
645 .send_transaction_with_config(transaction, config)
646 .map_err(RpcError::from)
647 })
648 .await
649 }
650
651 async fn get_transaction_slot(&self, signature: &Signature) -> Result<u64, RpcError> {
652 self.retry(|| async {
653 Ok(self
654 .client
655 .get_transaction_with_config(
656 signature,
657 RpcTransactionConfig {
658 encoding: Some(UiTransactionEncoding::Base64),
659 commitment: Some(self.client.commitment()),
660 ..Default::default()
661 },
662 )
663 .map_err(RpcError::from)?
664 .slot)
665 })
666 .await
667 }
668
669 async fn get_signature_statuses(
670 &self,
671 signatures: &[Signature],
672 ) -> Result<Vec<Option<TransactionStatus>>, RpcError> {
673 self.client
674 .get_signature_statuses(signatures)
675 .map(|response| response.value)
676 .map_err(RpcError::from)
677 }
678
679 async fn create_and_send_transaction_with_event<T>(
680 &mut self,
681 instructions: &[Instruction],
682 payer: &Pubkey,
683 signers: &[&Keypair],
684 ) -> Result<Option<(T, Signature, u64)>, RpcError>
685 where
686 T: BorshDeserialize + Send + Debug,
687 {
688 self._create_and_send_transaction_with_event::<T>(instructions, payer, signers)
689 .await
690 }
691
692 async fn create_and_send_transaction_with_public_event(
693 &mut self,
694 instructions: &[Instruction],
695 payer: &Pubkey,
696 signers: &[&Keypair],
697 ) -> Result<Option<(PublicTransactionEvent, Signature, Slot)>, RpcError> {
698 let parsed_event = self
699 ._create_and_send_transaction_with_batched_event(instructions, payer, signers)
700 .await?;
701
702 let event = parsed_event.map(|(e, signature, slot)| (e[0].event.clone(), signature, slot));
703 Ok(event)
704 }
705
706 async fn create_and_send_transaction_with_batched_event(
707 &mut self,
708 instructions: &[Instruction],
709 payer: &Pubkey,
710 signers: &[&Keypair],
711 ) -> Result<Option<(Vec<BatchPublicTransactionEvent>, Signature, Slot)>, RpcError> {
712 self._create_and_send_transaction_with_batched_event(instructions, payer, signers)
713 .await
714 }
715
716 async fn create_and_send_versioned_transaction<'a>(
725 &'a mut self,
726 instructions: &'a [Instruction],
727 payer: &'a Pubkey,
728 signers: &'a [&'a Keypair],
729 address_lookup_tables: &'a [AddressLookupTableAccount],
730 ) -> Result<Signature, RpcError> {
731 let blockhash = self.get_latest_blockhash().await?.0;
732
733 let message =
734 v0::Message::try_compile(payer, instructions, address_lookup_tables, blockhash)
735 .map_err(|e| {
736 RpcError::CustomError(format!("Failed to compile v0 message: {}", e))
737 })?;
738
739 let versioned_message = VersionedMessage::V0(message);
740
741 let transaction = VersionedTransaction::try_new(versioned_message, signers)
742 .map_err(|e| RpcError::SigningError(e.to_string()))?;
743
744 self.retry(|| async {
745 self.client
746 .send_and_confirm_transaction(&transaction)
747 .map_err(RpcError::from)
748 })
749 .await
750 }
751
752 fn indexer(&self) -> Result<&impl Indexer, RpcError> {
753 self.indexer.as_ref().ok_or(RpcError::IndexerNotInitialized)
754 }
755
756 fn indexer_mut(&mut self) -> Result<&mut impl Indexer, RpcError> {
757 self.indexer.as_mut().ok_or(RpcError::IndexerNotInitialized)
758 }
759
760 async fn get_latest_active_state_trees(&mut self) -> Result<Vec<TreeInfo>, RpcError> {
762 let network = self.detect_network();
763
764 if matches!(network, RpcUrl::Localnet) {
766 use light_compressed_account::TreeType;
767 use solana_pubkey::pubkey;
768
769 use crate::indexer::TreeInfo;
770
771 #[cfg(feature = "v2")]
772 let default_trees = vec![
773 TreeInfo {
774 tree: pubkey!("bmt1LryLZUMmF7ZtqESaw7wifBXLfXHQYoE4GAmrahU"),
775 queue: pubkey!("oq1na8gojfdUhsfCpyjNt6h4JaDWtHf1yQj4koBWfto"),
776 cpi_context: Some(pubkey!("cpi15BoVPKgEPw5o8wc2T816GE7b378nMXnhH3Xbq4y")),
777 next_tree_info: None,
778 tree_type: TreeType::StateV2,
779 },
780 TreeInfo {
781 tree: pubkey!("bmt2UxoBxB9xWev4BkLvkGdapsz6sZGkzViPNph7VFi"),
782 queue: pubkey!("oq2UkeMsJLfXt2QHzim242SUi3nvjJs8Pn7Eac9H9vg"),
783 cpi_context: Some(pubkey!("cpi2yGapXUR3As5SjnHBAVvmApNiLsbeZpF3euWnW6B")),
784 next_tree_info: None,
785 tree_type: TreeType::StateV2,
786 },
787 TreeInfo {
788 tree: pubkey!("bmt3ccLd4bqSVZVeCJnH1F6C8jNygAhaDfxDwePyyGb"),
789 queue: pubkey!("oq3AxjekBWgo64gpauB6QtuZNesuv19xrhaC1ZM1THQ"),
790 cpi_context: Some(pubkey!("cpi3mbwMpSX8FAGMZVP85AwxqCaQMfEk9Em1v8QK9Rf")),
791 next_tree_info: None,
792 tree_type: TreeType::StateV2,
793 },
794 TreeInfo {
795 tree: pubkey!("bmt4d3p1a4YQgk9PeZv5s4DBUmbF5NxqYpk9HGjQsd8"),
796 queue: pubkey!("oq4ypwvVGzCUMoiKKHWh4S1SgZJ9vCvKpcz6RT6A8dq"),
797 cpi_context: Some(pubkey!("cpi4yyPDc4bCgHAnsenunGA8Y77j3XEDyjgfyCKgcoc")),
798 next_tree_info: None,
799 tree_type: TreeType::StateV2,
800 },
801 TreeInfo {
802 tree: pubkey!("bmt5yU97jC88YXTuSukYHa8Z5Bi2ZDUtmzfkDTA2mG2"),
803 queue: pubkey!("oq5oh5ZR3yGomuQgFduNDzjtGvVWfDRGLuDVjv9a96P"),
804 cpi_context: Some(pubkey!("cpi5ZTjdgYpZ1Xr7B1cMLLUE81oTtJbNNAyKary2nV6")),
805 next_tree_info: None,
806 tree_type: TreeType::StateV2,
807 },
808 ];
809
810 #[cfg(not(feature = "v2"))]
811 let default_trees = vec![TreeInfo {
812 tree: pubkey!("smt1NamzXdq4AMqS2fS2F1i5KTYPZRhoHgWx38d8WsT"),
813 queue: pubkey!("nfq1NvQDJ2GEgnS8zt9prAe8rjjpAW1zFkrvZoBR148"),
814 cpi_context: Some(pubkey!("cpi1uHzrEhBG733DoEJNgHCyRS3XmmyVNZx5fonubE4")),
815 next_tree_info: None,
816 tree_type: TreeType::StateV1,
817 }];
818
819 self.state_merkle_trees = default_trees.clone();
820 return Ok(default_trees);
821 }
822
823 let (mainnet_tables, devnet_tables) = default_state_tree_lookup_tables();
824
825 let lookup_tables = match network {
826 RpcUrl::Devnet | RpcUrl::Testnet | RpcUrl::ZKTestnet => &devnet_tables,
827 _ => &mainnet_tables, };
829
830 let res = get_light_state_tree_infos(
831 self,
832 &lookup_tables[0].state_tree_lookup_table,
833 &lookup_tables[0].nullify_table,
834 )
835 .await?;
836 self.state_merkle_trees = res.clone();
837 Ok(res)
838 }
839
840 fn get_state_tree_infos(&self) -> Vec<TreeInfo> {
842 self.state_merkle_trees.to_vec()
843 }
844
845 fn get_random_state_tree_info(&self) -> Result<TreeInfo, RpcError> {
849 let mut rng = rand::thread_rng();
850
851 #[cfg(feature = "v2")]
852 let filtered_trees: Vec<TreeInfo> = self
853 .state_merkle_trees
854 .iter()
855 .filter(|tree| tree.tree_type == TreeType::StateV2)
856 .copied()
857 .collect();
858
859 #[cfg(not(feature = "v2"))]
860 let filtered_trees: Vec<TreeInfo> = self
861 .state_merkle_trees
862 .iter()
863 .filter(|tree| tree.tree_type == TreeType::StateV1)
864 .copied()
865 .collect();
866
867 select_state_tree_info(&mut rng, &filtered_trees)
868 }
869
870 fn get_random_state_tree_info_v1(&self) -> Result<TreeInfo, RpcError> {
873 let mut rng = rand::thread_rng();
874 let v1_trees: Vec<TreeInfo> = self
875 .state_merkle_trees
876 .iter()
877 .filter(|tree| tree.tree_type == TreeType::StateV1)
878 .copied()
879 .collect();
880 select_state_tree_info(&mut rng, &v1_trees)
881 }
882
883 fn get_address_tree_v1(&self) -> TreeInfo {
884 TreeInfo {
885 tree: pubkey!("amt1Ayt45jfbdw5YSo7iz6WZxUmnZsQTYXy82hVwyC2"),
886 queue: pubkey!("aq1S9z4reTSQAdgWHGD2zDaS39sjGrAxbR31vxJ2F4F"),
887 cpi_context: None,
888 next_tree_info: None,
889 tree_type: TreeType::AddressV1,
890 }
891 }
892
893 fn get_address_tree_v2(&self) -> TreeInfo {
894 TreeInfo {
895 tree: pubkey!("amt2kaJA14v3urZbZvnc5v2np8jqvc4Z8zDep5wbtzx"),
896 queue: pubkey!("amt2kaJA14v3urZbZvnc5v2np8jqvc4Z8zDep5wbtzx"),
897 cpi_context: None,
898 next_tree_info: None,
899 tree_type: TreeType::AddressV2,
900 }
901 }
902}
903
904impl MerkleTreeExt for LightClient {}
905
906pub fn select_state_tree_info<R: rand::Rng>(
929 rng: &mut R,
930 state_trees: &[TreeInfo],
931) -> Result<TreeInfo, RpcError> {
932 if state_trees.is_empty() {
933 return Err(RpcError::NoStateTreesAvailable);
934 }
935
936 Ok(state_trees[rng.gen_range(0..state_trees.len())])
937}