light-client 0.23.0

Client library for Light Protocol
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
use std::{
    fmt::{Debug, Display, Formatter},
    time::Duration,
};

use async_trait::async_trait;
use borsh::BorshDeserialize;
use bs58;
use light_compressed_account::TreeType;
use light_event::{
    event::{BatchPublicTransactionEvent, PublicTransactionEvent},
    parse::event_from_light_transaction,
};
use solana_account::Account;
use solana_clock::Slot;
use solana_commitment_config::CommitmentConfig;
use solana_hash::Hash;
use solana_instruction::Instruction;
use solana_keypair::Keypair;
use solana_message::{v0, AddressLookupTableAccount, VersionedMessage};
use solana_pubkey::{pubkey, Pubkey};
use solana_rpc_client::rpc_client::RpcClient;
use solana_rpc_client_api::config::{RpcSendTransactionConfig, RpcTransactionConfig};
use solana_signature::Signature;
use solana_transaction::{versioned::VersionedTransaction, Transaction};
use solana_transaction_status_client_types::{
    option_serializer::OptionSerializer, TransactionStatus, UiInstruction, UiTransactionEncoding,
};
use tokio::time::{sleep, Instant};
use tracing::warn;

use super::LightClientConfig;
#[cfg(not(feature = "v2"))]
use crate::rpc::get_light_state_tree_infos::{
    default_state_tree_lookup_tables, get_light_state_tree_infos,
};
use crate::{
    indexer::{
        photon_indexer::PhotonIndexer, AccountInterface as IndexerAccountInterface, Indexer,
        IndexerRpcConfig, Response, TokenAccountInterface as IndexerTokenAccountInterface,
        TreeInfo,
    },
    interface::{AccountInterface, MintInterface, MintState, TokenAccountInterface},
    rpc::{errors::RpcError, merkle_tree::MerkleTreeExt, Rpc},
};

/// V2 batched state trees.
#[cfg(feature = "v2")]
pub(crate) fn default_v2_state_trees() -> [TreeInfo; 5] {
    [
        TreeInfo {
            tree: pubkey!("bmt1LryLZUMmF7ZtqESaw7wifBXLfXHQYoE4GAmrahU"),
            queue: pubkey!("oq1na8gojfdUhsfCpyjNt6h4JaDWtHf1yQj4koBWfto"),
            cpi_context: Some(pubkey!("cpi15BoVPKgEPw5o8wc2T816GE7b378nMXnhH3Xbq4y")),
            next_tree_info: None,
            tree_type: TreeType::StateV2,
        },
        TreeInfo {
            tree: pubkey!("bmt2UxoBxB9xWev4BkLvkGdapsz6sZGkzViPNph7VFi"),
            queue: pubkey!("oq2UkeMsJLfXt2QHzim242SUi3nvjJs8Pn7Eac9H9vg"),
            cpi_context: Some(pubkey!("cpi2yGapXUR3As5SjnHBAVvmApNiLsbeZpF3euWnW6B")),
            next_tree_info: None,
            tree_type: TreeType::StateV2,
        },
        TreeInfo {
            tree: pubkey!("bmt3ccLd4bqSVZVeCJnH1F6C8jNygAhaDfxDwePyyGb"),
            queue: pubkey!("oq3AxjekBWgo64gpauB6QtuZNesuv19xrhaC1ZM1THQ"),
            cpi_context: Some(pubkey!("cpi3mbwMpSX8FAGMZVP85AwxqCaQMfEk9Em1v8QK9Rf")),
            next_tree_info: None,
            tree_type: TreeType::StateV2,
        },
        TreeInfo {
            tree: pubkey!("bmt4d3p1a4YQgk9PeZv5s4DBUmbF5NxqYpk9HGjQsd8"),
            queue: pubkey!("oq4ypwvVGzCUMoiKKHWh4S1SgZJ9vCvKpcz6RT6A8dq"),
            cpi_context: Some(pubkey!("cpi4yyPDc4bCgHAnsenunGA8Y77j3XEDyjgfyCKgcoc")),
            next_tree_info: None,
            tree_type: TreeType::StateV2,
        },
        TreeInfo {
            tree: pubkey!("bmt5yU97jC88YXTuSukYHa8Z5Bi2ZDUtmzfkDTA2mG2"),
            queue: pubkey!("oq5oh5ZR3yGomuQgFduNDzjtGvVWfDRGLuDVjv9a96P"),
            cpi_context: Some(pubkey!("cpi5ZTjdgYpZ1Xr7B1cMLLUE81oTtJbNNAyKary2nV6")),
            next_tree_info: None,
            tree_type: TreeType::StateV2,
        },
    ]
}

pub enum RpcUrl {
    Testnet,
    Devnet,
    Localnet,
    ZKTestnet,
    Custom(String),
}

impl Display for RpcUrl {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let str = match self {
            RpcUrl::Testnet => "https://api.testnet.solana.com".to_string(),
            RpcUrl::Devnet => "https://api.devnet.solana.com".to_string(),
            RpcUrl::Localnet => "http://localhost:8899".to_string(),
            RpcUrl::ZKTestnet => "https://zk-testnet.helius.dev:8899".to_string(),
            RpcUrl::Custom(url) => url.clone(),
        };
        write!(f, "{}", str)
    }
}

#[derive(Clone, Debug, Copy)]
pub struct RetryConfig {
    pub max_retries: u32,
    pub retry_delay: Duration,
    /// Max Light slot timeout in time based on solana slot length and light
    /// slot length.
    pub timeout: Duration,
}

impl Default for RetryConfig {
    fn default() -> Self {
        RetryConfig {
            max_retries: 10,
            retry_delay: Duration::from_secs(1),
            timeout: Duration::from_secs(60),
        }
    }
}

#[allow(dead_code)]
pub struct LightClient {
    pub client: RpcClient,
    pub payer: Keypair,
    pub retry_config: RetryConfig,
    pub indexer: Option<PhotonIndexer>,
    pub state_merkle_trees: Vec<TreeInfo>,
}

impl Debug for LightClient {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "LightClient {{ client: {:?} }}", self.client.url())
    }
}

impl LightClient {
    pub async fn new_with_retry(
        config: LightClientConfig,
        retry_config: Option<RetryConfig>,
    ) -> Result<Self, RpcError> {
        let payer = Keypair::new();
        let commitment_config = config
            .commitment_config
            .unwrap_or(CommitmentConfig::confirmed());
        let client = RpcClient::new_with_commitment(config.url.to_string(), commitment_config);
        let retry_config = retry_config.unwrap_or_default();

        let indexer = config.photon_url.map(PhotonIndexer::new);

        let mut new = Self {
            client,
            payer,
            retry_config,
            indexer,
            state_merkle_trees: Vec::new(),
        };
        if config.fetch_active_tree {
            new.get_latest_active_state_trees().await?;
        }
        Ok(new)
    }

    pub fn add_indexer(&mut self, url: String) {
        self.indexer = Some(PhotonIndexer::new(url));
    }

    /// Detects the network type based on the RPC URL. V1 only.
    #[cfg(not(feature = "v2"))]
    fn detect_network(&self) -> RpcUrl {
        let url = self.client.url();

        if url.contains("devnet") {
            RpcUrl::Devnet
        } else if url.contains("testnet") {
            RpcUrl::Testnet
        } else if url.contains("localhost") || url.contains("127.0.0.1") {
            RpcUrl::Localnet
        } else if url.contains("zk-testnet") {
            RpcUrl::ZKTestnet
        } else {
            // Default to mainnet for production URLs and custom URLs
            RpcUrl::Custom(url.to_string())
        }
    }

    async fn retry<F, Fut, T>(&self, operation: F) -> Result<T, RpcError>
    where
        F: Fn() -> Fut,
        Fut: std::future::Future<Output = Result<T, RpcError>>,
    {
        let mut attempts = 0;
        let start_time = Instant::now();
        loop {
            match operation().await {
                Ok(result) => return Ok(result),
                Err(e) => {
                    let retry = self.should_retry(&e);
                    if retry {
                        attempts += 1;
                        if attempts >= self.retry_config.max_retries
                            || start_time.elapsed() >= self.retry_config.timeout
                        {
                            return Err(e);
                        }
                        warn!(
                            "Operation failed, retrying in {:?} (attempt {}/{}): {:?}",
                            self.retry_config.retry_delay,
                            attempts,
                            self.retry_config.max_retries,
                            e
                        );
                        sleep(self.retry_config.retry_delay).await;
                    } else {
                        return Err(e);
                    }
                }
            }
        }
    }

    async fn _create_and_send_transaction_with_batched_event(
        &mut self,
        instructions: &[Instruction],
        payer: &Pubkey,
        signers: &[&Keypair],
    ) -> Result<Option<(Vec<BatchPublicTransactionEvent>, Signature, Slot)>, RpcError> {
        let latest_blockhash = self.client.get_latest_blockhash()?;

        let mut instructions_vec = vec![
            solana_compute_budget_interface::ComputeBudgetInstruction::set_compute_unit_limit(
                1_000_000,
            ),
        ];
        instructions_vec.extend_from_slice(instructions);

        let transaction = Transaction::new_signed_with_payer(
            instructions_vec.as_slice(),
            Some(payer),
            signers,
            latest_blockhash,
        );

        let (signature, slot) = self
            .process_transaction_with_context(transaction.clone())
            .await?;

        let mut vec = Vec::new();
        let mut vec_accounts = Vec::new();
        let mut program_ids = Vec::new();
        instructions_vec.iter().for_each(|x| {
            program_ids.push(light_compressed_account::Pubkey::new_from_array(
                x.program_id.to_bytes(),
            ));
            vec.push(x.data.clone());
            vec_accounts.push(
                x.accounts
                    .iter()
                    .map(|x| light_compressed_account::Pubkey::new_from_array(x.pubkey.to_bytes()))
                    .collect(),
            );
        });
        {
            let rpc_transaction_config = RpcTransactionConfig {
                encoding: Some(UiTransactionEncoding::Base64),
                commitment: Some(self.client.commitment()),
                ..Default::default()
            };
            let transaction = self
                .client
                .get_transaction_with_config(&signature, rpc_transaction_config)
                .map_err(|e| RpcError::CustomError(e.to_string()))?;
            let decoded_transaction = transaction
                .transaction
                .transaction
                .decode()
                .clone()
                .unwrap();
            let account_keys = decoded_transaction.message.static_account_keys();
            let meta = transaction.transaction.meta.as_ref().ok_or_else(|| {
                RpcError::CustomError("Transaction missing metadata information".to_string())
            })?;
            if meta.status.is_err() {
                return Err(RpcError::CustomError(
                    "Transaction status indicates an error".to_string(),
                ));
            }

            let inner_instructions = match &meta.inner_instructions {
                OptionSerializer::Some(i) => i,
                OptionSerializer::None => {
                    return Err(RpcError::CustomError(
                        "No inner instructions found".to_string(),
                    ));
                }
                OptionSerializer::Skip => {
                    return Err(RpcError::CustomError(
                        "No inner instructions found".to_string(),
                    ));
                }
            };

            for ix in inner_instructions.iter() {
                for ui_instruction in ix.instructions.iter() {
                    match ui_instruction {
                        UiInstruction::Compiled(ui_compiled_instruction) => {
                            let accounts = &ui_compiled_instruction.accounts;
                            let data = bs58::decode(&ui_compiled_instruction.data)
                                .into_vec()
                                .map_err(|_| {
                                    RpcError::CustomError(
                                        "Failed to decode instruction data".to_string(),
                                    )
                                })?;
                            vec.push(data);
                            program_ids.push(light_compressed_account::Pubkey::new_from_array(
                                account_keys[ui_compiled_instruction.program_id_index as usize]
                                    .to_bytes(),
                            ));
                            vec_accounts.push(
                                accounts
                                    .iter()
                                    .map(|x| {
                                        light_compressed_account::Pubkey::new_from_array(
                                            account_keys[(*x) as usize].to_bytes(),
                                        )
                                    })
                                    .collect(),
                            );
                        }
                        UiInstruction::Parsed(_) => {
                            println!("Parsed instructions are not implemented yet");
                        }
                    }
                }
            }
        }
        let parsed_event =
            event_from_light_transaction(program_ids.as_slice(), vec.as_slice(), vec_accounts)
                .map_err(|e| RpcError::CustomError(format!("Failed to parse event: {e:?}")))?;
        let event = parsed_event.map(|e| (e, signature, slot));
        Ok(event)
    }

    async fn _create_and_send_transaction_with_event<T>(
        &mut self,
        instructions: &[Instruction],
        payer: &Pubkey,
        signers: &[&Keypair],
    ) -> Result<Option<(T, Signature, u64)>, RpcError>
    where
        T: BorshDeserialize + Send + Debug,
    {
        let latest_blockhash = self.client.get_latest_blockhash()?;

        let mut instructions_vec = vec![
            solana_compute_budget_interface::ComputeBudgetInstruction::set_compute_unit_limit(
                1_000_000,
            ),
        ];
        instructions_vec.extend_from_slice(instructions);

        let transaction = Transaction::new_signed_with_payer(
            instructions_vec.as_slice(),
            Some(payer),
            signers,
            latest_blockhash,
        );

        let (signature, slot) = self
            .process_transaction_with_context(transaction.clone())
            .await?;

        let mut parsed_event = None;
        for instruction in &transaction.message.instructions {
            let ix_data = instruction.data.clone();
            match T::deserialize(&mut &instruction.data[..]) {
                Ok(e) => {
                    parsed_event = Some(e);
                    break;
                }
                Err(e) => {
                    warn!(
                        "Failed to parse event: {:?}, type: {:?}, ix data: {:?}",
                        e,
                        std::any::type_name::<T>(),
                        ix_data
                    );
                }
            }
        }

        if parsed_event.is_none() {
            parsed_event = self.parse_inner_instructions::<T>(signature).ok();
        }

        let result = parsed_event.map(|e| (e, signature, slot));
        Ok(result)
    }
}

impl LightClient {
    #[allow(clippy::result_large_err)]
    fn parse_inner_instructions<T: BorshDeserialize>(
        &self,
        signature: Signature,
    ) -> Result<T, RpcError> {
        let rpc_transaction_config = RpcTransactionConfig {
            encoding: Some(UiTransactionEncoding::Base64),
            commitment: Some(self.client.commitment()),
            ..Default::default()
        };
        let transaction = self
            .client
            .get_transaction_with_config(&signature, rpc_transaction_config)
            .map_err(|e| RpcError::CustomError(e.to_string()))?;
        let meta = transaction.transaction.meta.as_ref().ok_or_else(|| {
            RpcError::CustomError("Transaction missing metadata information".to_string())
        })?;
        if meta.status.is_err() {
            return Err(RpcError::CustomError(
                "Transaction status indicates an error".to_string(),
            ));
        }

        let inner_instructions = match &meta.inner_instructions {
            OptionSerializer::Some(i) => i,
            OptionSerializer::None => {
                return Err(RpcError::CustomError(
                    "No inner instructions found".to_string(),
                ));
            }
            OptionSerializer::Skip => {
                return Err(RpcError::CustomError(
                    "No inner instructions found".to_string(),
                ));
            }
        };

        for ix in inner_instructions.iter() {
            for ui_instruction in ix.instructions.iter() {
                match ui_instruction {
                    UiInstruction::Compiled(ui_compiled_instruction) => {
                        let data = bs58::decode(&ui_compiled_instruction.data)
                            .into_vec()
                            .map_err(|_| {
                                RpcError::CustomError(
                                    "Failed to decode instruction data".to_string(),
                                )
                            })?;

                        match T::try_from_slice(data.as_slice()) {
                            Ok(parsed_data) => return Ok(parsed_data),
                            Err(e) => {
                                warn!("Failed to parse inner instruction: {:?}", e);
                            }
                        }
                    }
                    UiInstruction::Parsed(_) => {
                        println!("Parsed instructions are not implemented yet");
                    }
                }
            }
        }
        Err(RpcError::CustomError(
            "Failed to find any parseable inner instructions".to_string(),
        ))
    }

    /// Instantly advances the validator to the given slot using surfpool's
    /// `surfnet_timeTravel` RPC method. This is much faster than polling
    /// `get_slot` in a loop and is intended for testing against surfpool.
    ///
    /// Returns the `EpochInfo` after the time travel, or an error if the
    /// RPC call fails (e.g. when not running against surfpool).
    pub async fn warp_to_slot(&self, slot: Slot) -> Result<serde_json::Value, RpcError> {
        let url = self.client.url();
        let body = serde_json::json!({
            "jsonrpc": "2.0",
            "id": 1,
            "method": "surfnet_timeTravel",
            "params": [{ "absoluteSlot": slot }]
        });
        let response = reqwest::Client::new()
            .post(url)
            .json(&body)
            .send()
            .await
            .map_err(|e| RpcError::CustomError(format!("warp_to_slot failed: {e}")))?;
        let result: serde_json::Value = response
            .json()
            .await
            .map_err(|e| RpcError::CustomError(format!("warp_to_slot response error: {e}")))?;
        Ok(result)
    }
}

// Conversion helpers from indexer types to interface types

use crate::indexer::ColdContext as IndexerColdContext;

fn cold_context_to_compressed_account(
    cold: &IndexerColdContext,
    lamports: u64,
    owner: Pubkey,
) -> crate::indexer::CompressedAccount {
    use light_compressed_account::compressed_account::CompressedAccountData;

    crate::indexer::CompressedAccount {
        address: cold.address,
        data: Some(CompressedAccountData {
            discriminator: cold.data.discriminator,
            data: cold.data.data.clone(),
            data_hash: cold.data.data_hash,
        }),
        hash: cold.hash,
        lamports,
        leaf_index: cold.leaf_index as u32,
        owner,
        prove_by_index: cold.prove_by_index,
        seq: cold.tree_info.seq,
        slot_created: cold.tree_info.slot_created,
        tree_info: TreeInfo {
            tree: cold.tree_info.tree,
            queue: cold.tree_info.queue,
            cpi_context: None,
            next_tree_info: None,
            tree_type: cold.tree_info.tree_type,
        },
    }
}

fn convert_account_interface(
    indexer_ai: IndexerAccountInterface,
) -> Result<AccountInterface, RpcError> {
    let account = Account {
        lamports: indexer_ai.account.lamports,
        data: indexer_ai.account.data,
        owner: indexer_ai.account.owner,
        executable: indexer_ai.account.executable,
        rent_epoch: indexer_ai.account.rent_epoch,
    };

    match indexer_ai.cold {
        None => Ok(AccountInterface::hot(indexer_ai.key, account)),
        Some(cold) => {
            let compressed = cold_context_to_compressed_account(
                &cold,
                indexer_ai.account.lamports,
                indexer_ai.account.owner,
            );
            Ok(AccountInterface::cold(
                indexer_ai.key,
                compressed,
                indexer_ai.account.owner,
            ))
        }
    }
}

fn convert_token_account_interface(
    indexer_tai: IndexerTokenAccountInterface,
) -> Result<TokenAccountInterface, RpcError> {
    use crate::indexer::CompressedTokenAccount;

    let account = Account {
        lamports: indexer_tai.account.account.lamports,
        data: indexer_tai.account.account.data.clone(),
        owner: indexer_tai.account.account.owner,
        executable: indexer_tai.account.account.executable,
        rent_epoch: indexer_tai.account.account.rent_epoch,
    };

    match indexer_tai.account.cold {
        None => TokenAccountInterface::hot(indexer_tai.account.key, account)
            .map_err(|e| RpcError::CustomError(format!("parse error: {}", e))),
        Some(cold) => {
            let compressed_account = cold_context_to_compressed_account(
                &cold,
                indexer_tai.account.account.lamports,
                indexer_tai.account.account.owner,
            );
            let token_owner = indexer_tai.token.owner;
            let compressed_token = CompressedTokenAccount {
                token: indexer_tai.token,
                account: compressed_account,
            };
            Ok(TokenAccountInterface::cold(
                indexer_tai.account.key,
                compressed_token,
                token_owner,
                indexer_tai.account.account.owner,
            ))
        }
    }
}

#[async_trait]
impl Rpc for LightClient {
    async fn new(config: LightClientConfig) -> Result<Self, RpcError>
    where
        Self: Sized,
    {
        Self::new_with_retry(config, None).await
    }

    fn get_payer(&self) -> &Keypair {
        &self.payer
    }

    fn get_url(&self) -> String {
        self.client.url()
    }

    async fn health(&self) -> Result<(), RpcError> {
        self.retry(|| async { self.client.get_health().map_err(RpcError::from) })
            .await
    }

    async fn get_program_accounts(
        &self,
        program_id: &Pubkey,
    ) -> Result<Vec<(Pubkey, Account)>, RpcError> {
        self.retry(|| async {
            self.client
                .get_program_accounts(program_id)
                .map_err(RpcError::from)
        })
        .await
    }

    async fn get_program_accounts_with_discriminator(
        &self,
        program_id: &Pubkey,
        discriminator: &[u8],
    ) -> Result<Vec<(Pubkey, Account)>, RpcError> {
        use solana_rpc_client_api::{
            config::{RpcAccountInfoConfig, RpcProgramAccountsConfig},
            filter::{Memcmp, RpcFilterType},
        };

        let discriminator = discriminator.to_vec();
        self.retry(|| async {
            let config = RpcProgramAccountsConfig {
                filters: Some(vec![RpcFilterType::Memcmp(Memcmp::new_base58_encoded(
                    0,
                    &discriminator,
                ))]),
                account_config: RpcAccountInfoConfig {
                    encoding: Some(solana_account_decoder_client_types::UiAccountEncoding::Base64),
                    commitment: Some(self.client.commitment()),
                    ..Default::default()
                },
                ..Default::default()
            };
            self.client
                .get_program_accounts_with_config(program_id, config)
                .map_err(RpcError::from)
        })
        .await
    }

    async fn process_transaction(
        &mut self,
        transaction: Transaction,
    ) -> Result<Signature, RpcError> {
        self.retry(|| async {
            self.client
                .send_and_confirm_transaction(&transaction)
                .map_err(RpcError::from)
        })
        .await
    }

    async fn process_transaction_with_context(
        &mut self,
        transaction: Transaction,
    ) -> Result<(Signature, Slot), RpcError> {
        self.retry(|| async {
            let signature = self.client.send_and_confirm_transaction(&transaction)?;
            let sig_info = self.client.get_signature_statuses(&[signature])?;
            let slot = sig_info
                .value
                .first()
                .and_then(|s| s.as_ref())
                .map(|s| s.slot)
                .ok_or_else(|| RpcError::CustomError("Failed to get slot".into()))?;
            Ok((signature, slot))
        })
        .await
    }

    async fn confirm_transaction(&self, signature: Signature) -> Result<bool, RpcError> {
        self.retry(|| async {
            self.client
                .confirm_transaction(&signature)
                .map_err(RpcError::from)
        })
        .await
    }

    async fn get_account(&self, address: Pubkey) -> Result<Option<Account>, RpcError> {
        self.retry(|| async {
            self.client
                .get_account_with_commitment(&address, self.client.commitment())
                .map(|response| response.value)
                .map_err(RpcError::from)
        })
        .await
    }

    async fn get_multiple_accounts(
        &self,
        addresses: &[Pubkey],
    ) -> Result<Vec<Option<Account>>, RpcError> {
        self.retry(|| async {
            self.client
                .get_multiple_accounts(addresses)
                .map_err(RpcError::from)
        })
        .await
    }

    async fn get_minimum_balance_for_rent_exemption(
        &self,
        data_len: usize,
    ) -> Result<u64, RpcError> {
        self.retry(|| async {
            self.client
                .get_minimum_balance_for_rent_exemption(data_len)
                .map_err(RpcError::from)
        })
        .await
    }

    async fn airdrop_lamports(
        &mut self,
        to: &Pubkey,
        lamports: u64,
    ) -> Result<Signature, RpcError> {
        self.retry(|| async {
            let signature = self
                .client
                .request_airdrop(to, lamports)
                .map_err(RpcError::ClientError)?;
            self.retry(|| async {
                if self
                    .client
                    .confirm_transaction_with_commitment(&signature, self.client.commitment())?
                    .value
                {
                    Ok(())
                } else {
                    Err(RpcError::CustomError("Airdrop not confirmed".into()))
                }
            })
            .await?;

            Ok(signature)
        })
        .await
    }

    async fn get_balance(&self, pubkey: &Pubkey) -> Result<u64, RpcError> {
        self.retry(|| async { self.client.get_balance(pubkey).map_err(RpcError::from) })
            .await
    }

    async fn get_latest_blockhash(&mut self) -> Result<(Hash, u64), RpcError> {
        self.retry(|| async {
            self.client
                // Confirmed commitments land more reliably than finalized
                // https://www.helius.dev/blog/how-to-deal-with-blockhash-errors-on-solana#how-to-deal-with-blockhash-errors
                .get_latest_blockhash_with_commitment(CommitmentConfig::confirmed())
                .map_err(RpcError::from)
        })
        .await
    }

    async fn get_slot(&self) -> Result<u64, RpcError> {
        self.retry(|| async { self.client.get_slot().map_err(RpcError::from) })
            .await
    }

    async fn send_transaction(&self, transaction: &Transaction) -> Result<Signature, RpcError> {
        self.retry(|| async {
            self.client
                .send_transaction_with_config(
                    transaction,
                    RpcSendTransactionConfig {
                        skip_preflight: true,
                        max_retries: Some(self.retry_config.max_retries as usize),
                        ..Default::default()
                    },
                )
                .map_err(RpcError::from)
        })
        .await
    }

    async fn send_transaction_with_config(
        &self,
        transaction: &Transaction,
        config: RpcSendTransactionConfig,
    ) -> Result<Signature, RpcError> {
        self.retry(|| async {
            self.client
                .send_transaction_with_config(transaction, config)
                .map_err(RpcError::from)
        })
        .await
    }

    async fn get_transaction_slot(&self, signature: &Signature) -> Result<u64, RpcError> {
        self.retry(|| async {
            Ok(self
                .client
                .get_transaction_with_config(
                    signature,
                    RpcTransactionConfig {
                        encoding: Some(UiTransactionEncoding::Base64),
                        commitment: Some(self.client.commitment()),
                        ..Default::default()
                    },
                )
                .map_err(RpcError::from)?
                .slot)
        })
        .await
    }

    async fn get_signature_statuses(
        &self,
        signatures: &[Signature],
    ) -> Result<Vec<Option<TransactionStatus>>, RpcError> {
        self.client
            .get_signature_statuses(signatures)
            .map(|response| response.value)
            .map_err(RpcError::from)
    }

    async fn create_and_send_transaction_with_event<T>(
        &mut self,
        instructions: &[Instruction],
        payer: &Pubkey,
        signers: &[&Keypair],
    ) -> Result<Option<(T, Signature, u64)>, RpcError>
    where
        T: BorshDeserialize + Send + Debug,
    {
        self._create_and_send_transaction_with_event::<T>(instructions, payer, signers)
            .await
    }

    async fn create_and_send_transaction_with_public_event(
        &mut self,
        instructions: &[Instruction],
        payer: &Pubkey,
        signers: &[&Keypair],
    ) -> Result<Option<(PublicTransactionEvent, Signature, Slot)>, RpcError> {
        let parsed_event = self
            ._create_and_send_transaction_with_batched_event(instructions, payer, signers)
            .await?;

        let event = parsed_event.map(|(e, signature, slot)| (e[0].event.clone(), signature, slot));
        Ok(event)
    }

    async fn create_and_send_transaction_with_batched_event(
        &mut self,
        instructions: &[Instruction],
        payer: &Pubkey,
        signers: &[&Keypair],
    ) -> Result<Option<(Vec<BatchPublicTransactionEvent>, Signature, Slot)>, RpcError> {
        self._create_and_send_transaction_with_batched_event(instructions, payer, signers)
            .await
    }

    /// Creates and sends a versioned transaction with address lookup tables.
    ///
    /// `address_lookup_tables` must contain pre-fetched `AddressLookupTableAccount` values
    /// loaded from the chain. Callers are responsible for resolving these accounts before
    /// calling this method. Unresolved or missing lookup tables will cause compilation to fail.
    ///
    /// Returns `RpcError::CustomError` on message compilation failure,
    /// `RpcError::SigningError` on signing failure.
    async fn create_and_send_versioned_transaction<'a>(
        &'a mut self,
        instructions: &'a [Instruction],
        payer: &'a Pubkey,
        signers: &'a [&'a Keypair],
        address_lookup_tables: &'a [AddressLookupTableAccount],
    ) -> Result<Signature, RpcError> {
        let blockhash = self.get_latest_blockhash().await?.0;

        let message =
            v0::Message::try_compile(payer, instructions, address_lookup_tables, blockhash)
                .map_err(|e| {
                    RpcError::CustomError(format!("Failed to compile v0 message: {}", e))
                })?;

        let versioned_message = VersionedMessage::V0(message);

        let transaction = VersionedTransaction::try_new(versioned_message, signers)
            .map_err(|e| RpcError::SigningError(e.to_string()))?;

        self.retry(|| async {
            self.client
                .send_and_confirm_transaction(&transaction)
                .map_err(RpcError::from)
        })
        .await
    }

    fn indexer(&self) -> Result<&impl Indexer, RpcError> {
        self.indexer.as_ref().ok_or(RpcError::IndexerNotInitialized)
    }

    fn indexer_mut(&mut self) -> Result<&mut impl Indexer, RpcError> {
        self.indexer.as_mut().ok_or(RpcError::IndexerNotInitialized)
    }

    /// Fetch the latest state tree addresses from the cluster.
    ///
    /// When the `v2` feature is enabled, returns the default V2
    /// batched state trees.
    /// When `v2` is disabled, uses V1 lookup-table resolution or
    /// localnet defaults.
    async fn get_latest_active_state_trees(&mut self) -> Result<Vec<TreeInfo>, RpcError> {
        // V2: the default batched state trees are the same on every network.
        #[cfg(feature = "v2")]
        {
            let trees = default_v2_state_trees().to_vec();
            self.state_merkle_trees = trees.clone();
            return Ok(trees);
        }

        // V1 path: network-dependent resolution.
        #[cfg(not(feature = "v2"))]
        {
            let network = self.detect_network();

            if matches!(network, RpcUrl::Localnet) {
                let default_trees = vec![TreeInfo {
                    tree: pubkey!("smt1NamzXdq4AMqS2fS2F1i5KTYPZRhoHgWx38d8WsT"),
                    queue: pubkey!("nfq1NvQDJ2GEgnS8zt9prAe8rjjpAW1zFkrvZoBR148"),
                    cpi_context: Some(pubkey!("cpi1uHzrEhBG733DoEJNgHCyRS3XmmyVNZx5fonubE4")),
                    next_tree_info: None,
                    tree_type: TreeType::StateV1,
                }];
                self.state_merkle_trees = default_trees.clone();
                return Ok(default_trees);
            }

            let (mainnet_tables, devnet_tables) = default_state_tree_lookup_tables();

            let lookup_tables = match network {
                RpcUrl::Devnet | RpcUrl::Testnet | RpcUrl::ZKTestnet => &devnet_tables,
                _ => &mainnet_tables,
            };

            let res = get_light_state_tree_infos(
                self,
                &lookup_tables[0].state_tree_lookup_table,
                &lookup_tables[0].nullify_table,
            )
            .await?;
            self.state_merkle_trees = res.clone();
            Ok(res)
        }
    }

    /// Returns list of state tree infos.
    fn get_state_tree_infos(&self) -> Vec<TreeInfo> {
        #[cfg(feature = "v2")]
        {
            default_v2_state_trees().to_vec()
        }
        #[cfg(not(feature = "v2"))]
        {
            self.state_merkle_trees.to_vec()
        }
    }

    /// Gets a random active state tree.
    fn get_random_state_tree_info(&self) -> Result<TreeInfo, RpcError> {
        #[cfg(feature = "v2")]
        {
            use rand::Rng;
            let mut rng = rand::thread_rng();
            let trees = default_v2_state_trees();
            Ok(trees[rng.gen_range(0..trees.len())])
        }

        #[cfg(not(feature = "v2"))]
        {
            let mut rng = rand::thread_rng();
            let filtered_trees: Vec<TreeInfo> = self
                .state_merkle_trees
                .iter()
                .filter(|tree| tree.tree_type == TreeType::StateV1)
                .copied()
                .collect();
            select_state_tree_info(&mut rng, &filtered_trees)
        }
    }

    /// Gets a random v1 state tree.
    /// State trees are cached and have to be fetched or set.
    fn get_random_state_tree_info_v1(&self) -> Result<TreeInfo, RpcError> {
        let mut rng = rand::thread_rng();
        let v1_trees: Vec<TreeInfo> = self
            .state_merkle_trees
            .iter()
            .filter(|tree| tree.tree_type == TreeType::StateV1)
            .copied()
            .collect();
        select_state_tree_info(&mut rng, &v1_trees)
    }

    fn get_address_tree_v1(&self) -> TreeInfo {
        TreeInfo {
            tree: pubkey!("amt1Ayt45jfbdw5YSo7iz6WZxUmnZsQTYXy82hVwyC2"),
            queue: pubkey!("aq1S9z4reTSQAdgWHGD2zDaS39sjGrAxbR31vxJ2F4F"),
            cpi_context: None,
            next_tree_info: None,
            tree_type: TreeType::AddressV1,
        }
    }

    fn get_address_tree_v2(&self) -> TreeInfo {
        TreeInfo {
            tree: pubkey!("amt2kaJA14v3urZbZvnc5v2np8jqvc4Z8zDep5wbtzx"),
            queue: pubkey!("amt2kaJA14v3urZbZvnc5v2np8jqvc4Z8zDep5wbtzx"),
            cpi_context: None,
            next_tree_info: None,
            tree_type: TreeType::AddressV2,
        }
    }

    async fn get_account_interface(
        &self,
        address: &Pubkey,
        config: Option<IndexerRpcConfig>,
    ) -> Result<Response<Option<AccountInterface>>, RpcError> {
        let indexer = self
            .indexer
            .as_ref()
            .ok_or(RpcError::IndexerNotInitialized)?;
        let resp = indexer
            .get_account_interface(address, config)
            .await
            .map_err(|e| RpcError::CustomError(format!("Indexer error: {e}")))?;

        let value = resp.value.map(convert_account_interface).transpose()?;
        Ok(Response {
            context: resp.context,
            value,
        })
    }

    async fn get_token_account_interface(
        &self,
        address: &Pubkey,
        config: Option<IndexerRpcConfig>,
    ) -> Result<Response<Option<TokenAccountInterface>>, RpcError> {
        let indexer = self
            .indexer
            .as_ref()
            .ok_or(RpcError::IndexerNotInitialized)?;
        let resp = indexer
            .get_token_account_interface(address, config)
            .await
            .map_err(|e| RpcError::CustomError(format!("Indexer error: {e}")))?;

        let value = match resp.value {
            Some(tai) => Some(convert_token_account_interface(tai)?),
            None => None,
        };

        Ok(Response {
            context: resp.context,
            value,
        })
    }

    async fn get_associated_token_account_interface(
        &self,
        owner: &Pubkey,
        mint: &Pubkey,
        config: Option<IndexerRpcConfig>,
    ) -> Result<Response<Option<TokenAccountInterface>>, RpcError> {
        let indexer = self
            .indexer
            .as_ref()
            .ok_or(RpcError::IndexerNotInitialized)?;
        let resp = indexer
            .get_associated_token_account_interface(owner, mint, config)
            .await
            .map_err(|e| RpcError::CustomError(format!("Indexer error: {e}")))?;

        let value = match resp.value {
            Some(tai) => {
                let mut iface = convert_token_account_interface(tai)?;
                // For cold ATAs, the compressed token stores token.owner =
                // ATA pubkey (for hash verification). Override parsed.owner
                // with the wallet owner so ata_bump() derivation succeeds.
                if iface.is_cold() {
                    iface.parsed.owner = *owner;
                }
                Some(iface)
            }
            None => None,
        };

        Ok(Response {
            context: resp.context,
            value,
        })
    }

    async fn get_multiple_account_interfaces(
        &self,
        addresses: Vec<&Pubkey>,
        config: Option<IndexerRpcConfig>,
    ) -> Result<Response<Vec<Option<AccountInterface>>>, RpcError> {
        let indexer = self
            .indexer
            .as_ref()
            .ok_or(RpcError::IndexerNotInitialized)?;
        let resp = indexer
            .get_multiple_account_interfaces(addresses, config)
            .await
            .map_err(|e| RpcError::CustomError(format!("Indexer error: {e}")))?;

        let value: Result<Vec<Option<AccountInterface>>, RpcError> = resp
            .value
            .into_iter()
            .map(|opt| opt.map(convert_account_interface).transpose())
            .collect();

        Ok(Response {
            context: resp.context,
            value: value?,
        })
    }

    async fn get_mint_interface(
        &self,
        address: &Pubkey,
        config: Option<IndexerRpcConfig>,
    ) -> Result<Response<Option<MintInterface>>, RpcError> {
        use light_compressed_account::address::derive_address;
        use light_token_interface::{state::Mint, MINT_ADDRESS_TREE};

        let address_tree = Pubkey::new_from_array(MINT_ADDRESS_TREE);
        let compressed_address = derive_address(
            &address.to_bytes(),
            &address_tree.to_bytes(),
            &light_token_interface::LIGHT_TOKEN_PROGRAM_ID,
        );

        let indexer = self
            .indexer
            .as_ref()
            .ok_or(RpcError::IndexerNotInitialized)?;

        // Use get_account_interface to check hot/cold (Photon handles derived address fallback)
        let resp = indexer
            .get_account_interface(address, config.clone())
            .await
            .map_err(|e| RpcError::CustomError(format!("Indexer error: {e}")))?;

        let value = match resp.value {
            Some(ai) => {
                let state = if ai.is_cold() {
                    let cold = ai.cold.as_ref().ok_or_else(|| {
                        RpcError::CustomError("Cold mint missing cold context".into())
                    })?;

                    // Build CompressedAccount from indexer ColdContext
                    let mut compressed = cold_context_to_compressed_account(
                        cold,
                        ai.account.lamports,
                        ai.account.owner,
                    );

                    if compressed.address.is_none() {
                        compressed.address = Some(compressed_address);
                    }

                    // Parse mint data from cold data bytes
                    let mint_data = if cold.data.data.is_empty() {
                        None
                    } else {
                        Mint::try_from_slice(&cold.data.data).ok()
                    }
                    .ok_or_else(|| {
                        RpcError::CustomError(
                            "Missing or invalid mint data in compressed account".into(),
                        )
                    })?;

                    MintState::Cold {
                        compressed,
                        mint_data,
                    }
                } else {
                    let expected_owner =
                        Pubkey::new_from_array(light_token_interface::LIGHT_TOKEN_PROGRAM_ID);
                    if ai.account.owner != expected_owner {
                        return Err(RpcError::CustomError(format!(
                            "Invalid mint account owner: expected {}, got {}",
                            expected_owner, ai.account.owner,
                        )));
                    }
                    Mint::try_from_slice(&ai.account.data).map_err(|e| {
                        RpcError::CustomError(format!(
                            "Failed to deserialize hot mint account: {e}"
                        ))
                    })?;
                    MintState::Hot {
                        account: ai.account,
                    }
                };

                Some(MintInterface {
                    mint: *address,
                    address_tree,
                    compressed_address,
                    state,
                })
            }
            None => None,
        };

        Ok(Response {
            context: resp.context,
            value,
        })
    }
}

impl MerkleTreeExt for LightClient {}

/// Selects a random state tree from the provided list.
///
/// This function should be used together with `get_state_tree_infos()` to first
/// retrieve the list of state trees, then select one randomly.
///
/// # Arguments
/// * `rng` - A mutable reference to a random number generator
/// * `state_trees` - A slice of `TreeInfo` representing state trees
///
/// # Returns
/// A randomly selected `TreeInfo` from the provided list, or an error if the list is empty
///
/// # Errors
/// Returns `RpcError::NoStateTreesAvailable` if the provided slice is empty
///
/// # Example
/// ```ignore
/// use rand::thread_rng;
/// let tree_infos = client.get_state_tree_infos();
/// let mut rng = thread_rng();
/// let selected_tree = select_state_tree_info(&mut rng, &tree_infos)?;
/// ```
pub fn select_state_tree_info<R: rand::Rng>(
    rng: &mut R,
    state_trees: &[TreeInfo],
) -> Result<TreeInfo, RpcError> {
    if state_trees.is_empty() {
        return Err(RpcError::NoStateTreesAvailable);
    }

    Ok(state_trees[rng.gen_range(0..state_trees.len())])
}