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 process_transaction(
470 &mut self,
471 transaction: Transaction,
472 ) -> Result<Signature, RpcError> {
473 self.retry(|| async {
474 self.client
475 .send_and_confirm_transaction(&transaction)
476 .map_err(RpcError::from)
477 })
478 .await
479 }
480
481 async fn process_transaction_with_context(
482 &mut self,
483 transaction: Transaction,
484 ) -> Result<(Signature, Slot), RpcError> {
485 self.retry(|| async {
486 let signature = self.client.send_and_confirm_transaction(&transaction)?;
487 let sig_info = self.client.get_signature_statuses(&[signature])?;
488 let slot = sig_info
489 .value
490 .first()
491 .and_then(|s| s.as_ref())
492 .map(|s| s.slot)
493 .ok_or_else(|| RpcError::CustomError("Failed to get slot".into()))?;
494 Ok((signature, slot))
495 })
496 .await
497 }
498
499 async fn confirm_transaction(&self, signature: Signature) -> Result<bool, RpcError> {
500 self.retry(|| async {
501 self.client
502 .confirm_transaction(&signature)
503 .map_err(RpcError::from)
504 })
505 .await
506 }
507
508 async fn get_account(&self, address: Pubkey) -> Result<Option<Account>, RpcError> {
509 self.retry(|| async {
510 self.client
511 .get_account_with_commitment(&address, self.client.commitment())
512 .map(|response| response.value)
513 .map_err(RpcError::from)
514 })
515 .await
516 }
517
518 async fn get_multiple_accounts(
519 &self,
520 addresses: &[Pubkey],
521 ) -> Result<Vec<Option<Account>>, RpcError> {
522 self.retry(|| async {
523 self.client
524 .get_multiple_accounts(addresses)
525 .map_err(RpcError::from)
526 })
527 .await
528 }
529
530 async fn get_minimum_balance_for_rent_exemption(
531 &self,
532 data_len: usize,
533 ) -> Result<u64, RpcError> {
534 self.retry(|| async {
535 self.client
536 .get_minimum_balance_for_rent_exemption(data_len)
537 .map_err(RpcError::from)
538 })
539 .await
540 }
541
542 async fn airdrop_lamports(
543 &mut self,
544 to: &Pubkey,
545 lamports: u64,
546 ) -> Result<Signature, RpcError> {
547 self.retry(|| async {
548 let signature = self
549 .client
550 .request_airdrop(to, lamports)
551 .map_err(RpcError::ClientError)?;
552 self.retry(|| async {
553 if self
554 .client
555 .confirm_transaction_with_commitment(&signature, self.client.commitment())?
556 .value
557 {
558 Ok(())
559 } else {
560 Err(RpcError::CustomError("Airdrop not confirmed".into()))
561 }
562 })
563 .await?;
564
565 Ok(signature)
566 })
567 .await
568 }
569
570 async fn get_balance(&self, pubkey: &Pubkey) -> Result<u64, RpcError> {
571 self.retry(|| async { self.client.get_balance(pubkey).map_err(RpcError::from) })
572 .await
573 }
574
575 async fn get_latest_blockhash(&mut self) -> Result<(Hash, u64), RpcError> {
576 self.retry(|| async {
577 self.client
578 .get_latest_blockhash_with_commitment(CommitmentConfig::confirmed())
581 .map_err(RpcError::from)
582 })
583 .await
584 }
585
586 async fn get_slot(&self) -> Result<u64, RpcError> {
587 self.retry(|| async { self.client.get_slot().map_err(RpcError::from) })
588 .await
589 }
590
591 async fn send_transaction(&self, transaction: &Transaction) -> Result<Signature, RpcError> {
592 self.retry(|| async {
593 self.client
594 .send_transaction_with_config(
595 transaction,
596 RpcSendTransactionConfig {
597 skip_preflight: true,
598 max_retries: Some(self.retry_config.max_retries as usize),
599 ..Default::default()
600 },
601 )
602 .map_err(RpcError::from)
603 })
604 .await
605 }
606
607 async fn send_transaction_with_config(
608 &self,
609 transaction: &Transaction,
610 config: RpcSendTransactionConfig,
611 ) -> Result<Signature, RpcError> {
612 self.retry(|| async {
613 self.client
614 .send_transaction_with_config(transaction, config)
615 .map_err(RpcError::from)
616 })
617 .await
618 }
619
620 async fn get_transaction_slot(&self, signature: &Signature) -> Result<u64, RpcError> {
621 self.retry(|| async {
622 Ok(self
623 .client
624 .get_transaction_with_config(
625 signature,
626 RpcTransactionConfig {
627 encoding: Some(UiTransactionEncoding::Base64),
628 commitment: Some(self.client.commitment()),
629 ..Default::default()
630 },
631 )
632 .map_err(RpcError::from)?
633 .slot)
634 })
635 .await
636 }
637
638 async fn get_signature_statuses(
639 &self,
640 signatures: &[Signature],
641 ) -> Result<Vec<Option<TransactionStatus>>, RpcError> {
642 self.client
643 .get_signature_statuses(signatures)
644 .map(|response| response.value)
645 .map_err(RpcError::from)
646 }
647
648 async fn create_and_send_transaction_with_event<T>(
649 &mut self,
650 instructions: &[Instruction],
651 payer: &Pubkey,
652 signers: &[&Keypair],
653 ) -> Result<Option<(T, Signature, u64)>, RpcError>
654 where
655 T: BorshDeserialize + Send + Debug,
656 {
657 self._create_and_send_transaction_with_event::<T>(instructions, payer, signers)
658 .await
659 }
660
661 async fn create_and_send_transaction_with_public_event(
662 &mut self,
663 instructions: &[Instruction],
664 payer: &Pubkey,
665 signers: &[&Keypair],
666 ) -> Result<Option<(PublicTransactionEvent, Signature, Slot)>, RpcError> {
667 let parsed_event = self
668 ._create_and_send_transaction_with_batched_event(instructions, payer, signers)
669 .await?;
670
671 let event = parsed_event.map(|(e, signature, slot)| (e[0].event.clone(), signature, slot));
672 Ok(event)
673 }
674
675 async fn create_and_send_transaction_with_batched_event(
676 &mut self,
677 instructions: &[Instruction],
678 payer: &Pubkey,
679 signers: &[&Keypair],
680 ) -> Result<Option<(Vec<BatchPublicTransactionEvent>, Signature, Slot)>, RpcError> {
681 self._create_and_send_transaction_with_batched_event(instructions, payer, signers)
682 .await
683 }
684
685 async fn create_and_send_versioned_transaction<'a>(
694 &'a mut self,
695 instructions: &'a [Instruction],
696 payer: &'a Pubkey,
697 signers: &'a [&'a Keypair],
698 address_lookup_tables: &'a [AddressLookupTableAccount],
699 ) -> Result<Signature, RpcError> {
700 let blockhash = self.get_latest_blockhash().await?.0;
701
702 let message =
703 v0::Message::try_compile(payer, instructions, address_lookup_tables, blockhash)
704 .map_err(|e| {
705 RpcError::CustomError(format!("Failed to compile v0 message: {}", e))
706 })?;
707
708 let versioned_message = VersionedMessage::V0(message);
709
710 let transaction = VersionedTransaction::try_new(versioned_message, signers)
711 .map_err(|e| RpcError::SigningError(e.to_string()))?;
712
713 self.retry(|| async {
714 self.client
715 .send_and_confirm_transaction(&transaction)
716 .map_err(RpcError::from)
717 })
718 .await
719 }
720
721 fn indexer(&self) -> Result<&impl Indexer, RpcError> {
722 self.indexer.as_ref().ok_or(RpcError::IndexerNotInitialized)
723 }
724
725 fn indexer_mut(&mut self) -> Result<&mut impl Indexer, RpcError> {
726 self.indexer.as_mut().ok_or(RpcError::IndexerNotInitialized)
727 }
728
729 async fn get_latest_active_state_trees(&mut self) -> Result<Vec<TreeInfo>, RpcError> {
731 let network = self.detect_network();
732
733 if matches!(network, RpcUrl::Localnet) {
735 use light_compressed_account::TreeType;
736 use solana_pubkey::pubkey;
737
738 use crate::indexer::TreeInfo;
739
740 #[cfg(feature = "v2")]
741 let default_trees = vec![
742 TreeInfo {
743 tree: pubkey!("bmt1LryLZUMmF7ZtqESaw7wifBXLfXHQYoE4GAmrahU"),
744 queue: pubkey!("oq1na8gojfdUhsfCpyjNt6h4JaDWtHf1yQj4koBWfto"),
745 cpi_context: Some(pubkey!("cpi15BoVPKgEPw5o8wc2T816GE7b378nMXnhH3Xbq4y")),
746 next_tree_info: None,
747 tree_type: TreeType::StateV2,
748 },
749 TreeInfo {
750 tree: pubkey!("bmt2UxoBxB9xWev4BkLvkGdapsz6sZGkzViPNph7VFi"),
751 queue: pubkey!("oq2UkeMsJLfXt2QHzim242SUi3nvjJs8Pn7Eac9H9vg"),
752 cpi_context: Some(pubkey!("cpi2yGapXUR3As5SjnHBAVvmApNiLsbeZpF3euWnW6B")),
753 next_tree_info: None,
754 tree_type: TreeType::StateV2,
755 },
756 TreeInfo {
757 tree: pubkey!("bmt3ccLd4bqSVZVeCJnH1F6C8jNygAhaDfxDwePyyGb"),
758 queue: pubkey!("oq3AxjekBWgo64gpauB6QtuZNesuv19xrhaC1ZM1THQ"),
759 cpi_context: Some(pubkey!("cpi3mbwMpSX8FAGMZVP85AwxqCaQMfEk9Em1v8QK9Rf")),
760 next_tree_info: None,
761 tree_type: TreeType::StateV2,
762 },
763 TreeInfo {
764 tree: pubkey!("bmt4d3p1a4YQgk9PeZv5s4DBUmbF5NxqYpk9HGjQsd8"),
765 queue: pubkey!("oq4ypwvVGzCUMoiKKHWh4S1SgZJ9vCvKpcz6RT6A8dq"),
766 cpi_context: Some(pubkey!("cpi4yyPDc4bCgHAnsenunGA8Y77j3XEDyjgfyCKgcoc")),
767 next_tree_info: None,
768 tree_type: TreeType::StateV2,
769 },
770 TreeInfo {
771 tree: pubkey!("bmt5yU97jC88YXTuSukYHa8Z5Bi2ZDUtmzfkDTA2mG2"),
772 queue: pubkey!("oq5oh5ZR3yGomuQgFduNDzjtGvVWfDRGLuDVjv9a96P"),
773 cpi_context: Some(pubkey!("cpi5ZTjdgYpZ1Xr7B1cMLLUE81oTtJbNNAyKary2nV6")),
774 next_tree_info: None,
775 tree_type: TreeType::StateV2,
776 },
777 ];
778
779 #[cfg(not(feature = "v2"))]
780 let default_trees = vec![TreeInfo {
781 tree: pubkey!("smt1NamzXdq4AMqS2fS2F1i5KTYPZRhoHgWx38d8WsT"),
782 queue: pubkey!("nfq1NvQDJ2GEgnS8zt9prAe8rjjpAW1zFkrvZoBR148"),
783 cpi_context: Some(pubkey!("cpi1uHzrEhBG733DoEJNgHCyRS3XmmyVNZx5fonubE4")),
784 next_tree_info: None,
785 tree_type: TreeType::StateV1,
786 }];
787
788 self.state_merkle_trees = default_trees.clone();
789 return Ok(default_trees);
790 }
791
792 let (mainnet_tables, devnet_tables) = default_state_tree_lookup_tables();
793
794 let lookup_tables = match network {
795 RpcUrl::Devnet | RpcUrl::Testnet | RpcUrl::ZKTestnet => &devnet_tables,
796 _ => &mainnet_tables, };
798
799 let res = get_light_state_tree_infos(
800 self,
801 &lookup_tables[0].state_tree_lookup_table,
802 &lookup_tables[0].nullify_table,
803 )
804 .await?;
805 self.state_merkle_trees = res.clone();
806 Ok(res)
807 }
808
809 fn get_state_tree_infos(&self) -> Vec<TreeInfo> {
811 self.state_merkle_trees.to_vec()
812 }
813
814 fn get_random_state_tree_info(&self) -> Result<TreeInfo, RpcError> {
818 let mut rng = rand::thread_rng();
819
820 #[cfg(feature = "v2")]
821 let filtered_trees: Vec<TreeInfo> = self
822 .state_merkle_trees
823 .iter()
824 .filter(|tree| tree.tree_type == TreeType::StateV2)
825 .copied()
826 .collect();
827
828 #[cfg(not(feature = "v2"))]
829 let filtered_trees: Vec<TreeInfo> = self
830 .state_merkle_trees
831 .iter()
832 .filter(|tree| tree.tree_type == TreeType::StateV1)
833 .copied()
834 .collect();
835
836 select_state_tree_info(&mut rng, &filtered_trees)
837 }
838
839 fn get_random_state_tree_info_v1(&self) -> Result<TreeInfo, RpcError> {
842 let mut rng = rand::thread_rng();
843 let v1_trees: Vec<TreeInfo> = self
844 .state_merkle_trees
845 .iter()
846 .filter(|tree| tree.tree_type == TreeType::StateV1)
847 .copied()
848 .collect();
849 select_state_tree_info(&mut rng, &v1_trees)
850 }
851
852 fn get_address_tree_v1(&self) -> TreeInfo {
853 TreeInfo {
854 tree: pubkey!("amt1Ayt45jfbdw5YSo7iz6WZxUmnZsQTYXy82hVwyC2"),
855 queue: pubkey!("aq1S9z4reTSQAdgWHGD2zDaS39sjGrAxbR31vxJ2F4F"),
856 cpi_context: None,
857 next_tree_info: None,
858 tree_type: TreeType::AddressV1,
859 }
860 }
861
862 fn get_address_tree_v2(&self) -> TreeInfo {
863 TreeInfo {
864 tree: pubkey!("amt2kaJA14v3urZbZvnc5v2np8jqvc4Z8zDep5wbtzx"),
865 queue: pubkey!("amt2kaJA14v3urZbZvnc5v2np8jqvc4Z8zDep5wbtzx"),
866 cpi_context: None,
867 next_tree_info: None,
868 tree_type: TreeType::AddressV2,
869 }
870 }
871}
872
873impl MerkleTreeExt for LightClient {}
874
875pub fn select_state_tree_info<R: rand::Rng>(
898 rng: &mut R,
899 state_trees: &[TreeInfo],
900) -> Result<TreeInfo, RpcError> {
901 if state_trees.is_empty() {
902 return Err(RpcError::NoStateTreesAvailable);
903 }
904
905 Ok(state_trees[rng.gen_range(0..state_trees.len())])
906}