kora-lib 2.0.5

Core library for Kora gasless relayer
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
use async_trait::async_trait;
use base64::{engine::general_purpose::STANDARD, Engine as _};
use solana_client::{nonblocking::rpc_client::RpcClient, rpc_config::RpcSimulateTransactionConfig};
use solana_commitment_config::CommitmentConfig;
use solana_keychain::{Signer, SolanaSigner};
use solana_message::{
    compiled_instruction::CompiledInstruction, v0::MessageAddressTableLookup, VersionedMessage,
};
use solana_sdk::{instruction::Instruction, pubkey::Pubkey, transaction::VersionedTransaction};
use std::{collections::HashMap, ops::Deref};

use solana_transaction_status_client_types::{UiInstruction, UiTransactionEncoding};

use crate::{
    error::KoraError,
    fee::fee::{FeeConfigUtil, TransactionFeeUtil},
    state::get_config,
    transaction::{
        instruction_util::IxUtils, ParsedSPLInstructionData, ParsedSPLInstructionType,
        ParsedSystemInstructionData, ParsedSystemInstructionType,
    },
    validator::transaction_validator::TransactionValidator,
    CacheUtil,
};
use solana_address_lookup_table_interface::state::AddressLookupTable;

/// A fully resolved transaction with lookup tables and inner instructions resolved
pub struct VersionedTransactionResolved {
    pub transaction: VersionedTransaction,

    // Includes lookup table addresses
    pub all_account_keys: Vec<Pubkey>,

    // Includes all instructions, including inner instructions
    pub all_instructions: Vec<Instruction>,

    // Parsed instructions by type (None if not parsed yet)
    parsed_system_instructions:
        Option<HashMap<ParsedSystemInstructionType, Vec<ParsedSystemInstructionData>>>,

    // Parsed SPL instructions by type (None if not parsed yet)
    parsed_spl_instructions:
        Option<HashMap<ParsedSPLInstructionType, Vec<ParsedSPLInstructionData>>>,
}

impl Deref for VersionedTransactionResolved {
    type Target = VersionedTransaction;

    fn deref(&self) -> &Self::Target {
        &self.transaction
    }
}

#[async_trait]
pub trait VersionedTransactionOps {
    fn encode_b64_transaction(&self) -> Result<String, KoraError>;
    fn find_signer_position(&self, signer_pubkey: &Pubkey) -> Result<usize, KoraError>;

    async fn sign_transaction(
        &mut self,
        signer: &std::sync::Arc<Signer>,
        rpc_client: &RpcClient,
    ) -> Result<(VersionedTransaction, String), KoraError>;
    async fn sign_and_send_transaction(
        &mut self,
        signer: &std::sync::Arc<Signer>,
        rpc_client: &RpcClient,
    ) -> Result<(String, String), KoraError>;
}

impl VersionedTransactionResolved {
    pub async fn from_transaction(
        transaction: &VersionedTransaction,
        rpc_client: &RpcClient,
        sig_verify: bool,
    ) -> Result<Self, KoraError> {
        let mut resolved = Self {
            transaction: transaction.clone(),
            all_account_keys: vec![],
            all_instructions: vec![],
            parsed_system_instructions: None,
            parsed_spl_instructions: None,
        };

        // 1. Resolve lookup table addresses based on transaction type
        let resolved_addresses = match &transaction.message {
            VersionedMessage::Legacy(_) => {
                // Legacy transactions don't have lookup tables
                vec![]
            }
            VersionedMessage::V0(v0_message) => {
                // V0 transactions may have lookup tables
                LookupTableUtil::resolve_lookup_table_addresses(
                    rpc_client,
                    &v0_message.address_table_lookups,
                )
                .await?
            }
        };

        // Set all accout keys
        let mut all_account_keys = transaction.message.static_account_keys().to_vec();
        all_account_keys.extend(resolved_addresses.clone());
        resolved.all_account_keys = all_account_keys.clone();

        // 2. Fetch all instructions
        let outer_instructions =
            IxUtils::uncompile_instructions(transaction.message.instructions(), &all_account_keys)?;

        let inner_instructions = resolved.fetch_inner_instructions(rpc_client, sig_verify).await?;

        resolved.all_instructions.extend(outer_instructions);
        resolved.all_instructions.extend(inner_instructions);

        Ok(resolved)
    }

    /// Only use this is we built the transaction ourselves, because it won't do any checks for resolving LUT, etc.
    pub fn from_kora_built_transaction(
        transaction: &VersionedTransaction,
    ) -> Result<Self, KoraError> {
        Ok(Self {
            transaction: transaction.clone(),
            all_account_keys: transaction.message.static_account_keys().to_vec(),
            all_instructions: IxUtils::uncompile_instructions(
                transaction.message.instructions(),
                transaction.message.static_account_keys(),
            )?,
            parsed_system_instructions: None,
            parsed_spl_instructions: None,
        })
    }

    /// Fetch inner instructions via simulation
    async fn fetch_inner_instructions(
        &mut self,
        rpc_client: &RpcClient,
        sig_verify: bool,
    ) -> Result<Vec<Instruction>, KoraError> {
        let simulation_result = rpc_client
            .simulate_transaction_with_config(
                &self.transaction,
                RpcSimulateTransactionConfig {
                    commitment: Some(rpc_client.commitment()),
                    sig_verify,
                    inner_instructions: true,
                    replace_recent_blockhash: false,
                    encoding: Some(UiTransactionEncoding::Base64),
                    accounts: None,
                    min_context_slot: None,
                },
            )
            .await
            .map_err(|e| KoraError::RpcError(format!("Failed to simulate transaction: {e}")))?;

        if let Some(err) = simulation_result.value.err {
            return Err(KoraError::InvalidTransaction(format!(
                "Transaction simulation failed: {err}"
            )));
        }

        if let Some(inner_instructions) = simulation_result.value.inner_instructions {
            let mut compiled_inner_instructions: Vec<CompiledInstruction> = vec![];

            inner_instructions.iter().for_each(|ix| {
                ix.instructions.iter().for_each(|inner_ix| match inner_ix {
                    UiInstruction::Compiled(ix) => {
                        compiled_inner_instructions.push(CompiledInstruction {
                            program_id_index: ix.program_id_index,
                            accounts: ix.accounts.clone(),
                            data: bs58::decode(&ix.data).into_vec().unwrap_or_default(),
                        });
                    }
                    UiInstruction::Parsed(ui_parsed) => {
                        if let Some(compiled) = IxUtils::reconstruct_instruction_from_ui(
                            &UiInstruction::Parsed(ui_parsed.clone()),
                            &self.all_account_keys,
                        ) {
                            compiled_inner_instructions.push(compiled);
                        }
                    }
                });
            });

            return IxUtils::uncompile_instructions(
                &compiled_inner_instructions,
                &self.all_account_keys,
            );
        }

        Ok(vec![])
    }

    pub fn get_or_parse_system_instructions(
        &mut self,
    ) -> Result<&HashMap<ParsedSystemInstructionType, Vec<ParsedSystemInstructionData>>, KoraError>
    {
        if self.parsed_system_instructions.is_none() {
            self.parsed_system_instructions = Some(IxUtils::parse_system_instructions(self)?);
        }

        self.parsed_system_instructions.as_ref().ok_or_else(|| {
            KoraError::SerializationError("Parsed system instructions not found".to_string())
        })
    }

    pub fn get_or_parse_spl_instructions(
        &mut self,
    ) -> Result<&HashMap<ParsedSPLInstructionType, Vec<ParsedSPLInstructionData>>, KoraError> {
        if self.parsed_spl_instructions.is_none() {
            self.parsed_spl_instructions = Some(IxUtils::parse_token_instructions(self)?);
        }

        self.parsed_spl_instructions.as_ref().ok_or_else(|| {
            KoraError::SerializationError("Parsed SPL instructions not found".to_string())
        })
    }
}

// Implementation of the consolidated trait for VersionedTransactionResolved
#[async_trait]
impl VersionedTransactionOps for VersionedTransactionResolved {
    fn encode_b64_transaction(&self) -> Result<String, KoraError> {
        let serialized = bincode::serialize(&self.transaction).map_err(|e| {
            KoraError::SerializationError(format!("Base64 serialization failed: {e}"))
        })?;
        Ok(STANDARD.encode(serialized))
    }

    fn find_signer_position(&self, signer_pubkey: &Pubkey) -> Result<usize, KoraError> {
        self.transaction
            .message
            .static_account_keys()
            .iter()
            .position(|key| key == signer_pubkey)
            .ok_or_else(|| {
                KoraError::InvalidTransaction(format!(
                    "Signer {signer_pubkey} not found in transaction account keys"
                ))
            })
    }

    async fn sign_transaction(
        &mut self,
        signer: &std::sync::Arc<Signer>,
        rpc_client: &RpcClient,
    ) -> Result<(VersionedTransaction, String), KoraError> {
        let fee_payer = signer.pubkey();
        let config = &get_config()?;
        let validator = TransactionValidator::new(fee_payer)?;

        // Validate transaction and accounts (already resolved)
        validator.validate_transaction(self, rpc_client).await?;

        // Calculate fee and validate payment if price model requires it
        let fee_calculation = FeeConfigUtil::estimate_kora_fee(
            rpc_client,
            self,
            &fee_payer,
            config.validation.is_payment_required(),
            config.validation.price_source.clone(),
        )
        .await?;

        let required_lamports = fee_calculation.total_fee_lamports;

        // Validate payment if price model is not Free
        if required_lamports > 0 {
            log::info!("Payment validation: required_lamports={}", required_lamports);
            // Get the expected payment destination
            let payment_destination = config.kora.get_payment_address(&fee_payer)?;

            // Validate token payment using the resolved transaction
            TransactionValidator::validate_token_payment(
                self,
                required_lamports,
                rpc_client,
                &payment_destination,
            )
            .await?;

            // Validate strict pricing if enabled
            TransactionValidator::validate_strict_pricing_with_fee(&fee_calculation)?;
        }

        // Get latest blockhash and update transaction
        let mut transaction = self.transaction.clone();

        if transaction.signatures.is_empty() {
            let blockhash = rpc_client
                .get_latest_blockhash_with_commitment(CommitmentConfig::confirmed())
                .await?;
            transaction.message.set_recent_blockhash(blockhash.0);
        }

        // Validate transaction fee using resolved transaction
        let estimated_fee = TransactionFeeUtil::get_estimate_fee_resolved(rpc_client, self).await?;
        validator.validate_lamport_fee(estimated_fee)?;

        // Sign transaction
        let message_bytes = transaction.message.serialize();
        let signature = signer
            .sign_message(&message_bytes)
            .await
            .map_err(|e| KoraError::SigningError(e.to_string()))?;

        // Find the fee payer position - don't assume it's at position 0
        let fee_payer_position = self.find_signer_position(&fee_payer)?;
        transaction.signatures[fee_payer_position] = signature;

        // Serialize signed transaction
        let serialized = bincode::serialize(&transaction)?;
        let encoded = STANDARD.encode(serialized);

        Ok((transaction, encoded))
    }

    async fn sign_and_send_transaction(
        &mut self,
        signer: &std::sync::Arc<Signer>,
        rpc_client: &RpcClient,
    ) -> Result<(String, String), KoraError> {
        // Payment validation is handled in sign_transaction
        let (transaction, encoded) = self.sign_transaction(signer, rpc_client).await?;

        // Send and confirm transaction
        let signature = rpc_client
            .send_and_confirm_transaction(&transaction)
            .await
            .map_err(|e| KoraError::RpcError(e.to_string()))?;

        Ok((signature.to_string(), encoded))
    }
}

pub struct LookupTableUtil {}

impl LookupTableUtil {
    /// Resolves addresses from lookup tables for V0 transactions
    pub async fn resolve_lookup_table_addresses(
        rpc_client: &RpcClient,
        lookup_table_lookups: &[MessageAddressTableLookup],
    ) -> Result<Vec<Pubkey>, KoraError> {
        let mut resolved_addresses = Vec::new();

        // Maybe we can use caching here, there's a chance the lookup tables get updated though, so tbd
        for lookup in lookup_table_lookups {
            let lookup_table_account =
                CacheUtil::get_account(rpc_client, &lookup.account_key, false).await.map_err(
                    |e| KoraError::RpcError(format!("Failed to fetch lookup table: {e}")),
                )?;

            // Parse the lookup table account data to get the actual addresses
            let address_lookup_table = AddressLookupTable::deserialize(&lookup_table_account.data)
                .map_err(|e| {
                    KoraError::InvalidTransaction(format!(
                        "Failed to deserialize lookup table: {e}"
                    ))
                })?;

            // Resolve writable addresses
            for &index in &lookup.writable_indexes {
                if let Some(address) = address_lookup_table.addresses.get(index as usize) {
                    resolved_addresses.push(*address);
                } else {
                    return Err(KoraError::InvalidTransaction(format!(
                        "Lookup table index {index} out of bounds for writable addresses"
                    )));
                }
            }

            // Resolve readonly addresses
            for &index in &lookup.readonly_indexes {
                if let Some(address) = address_lookup_table.addresses.get(index as usize) {
                    resolved_addresses.push(*address);
                } else {
                    return Err(KoraError::InvalidTransaction(format!(
                        "Lookup table index {index} out of bounds for readonly addresses"
                    )));
                }
            }
        }

        Ok(resolved_addresses)
    }
}

#[cfg(test)]
mod tests {
    use crate::{
        config::SplTokenConfig,
        tests::{
            common::RpcMockBuilder, config_mock::mock_state::setup_config_mock,
            toml_mock::ConfigBuilder,
        },
        transaction::TransactionUtil,
        Config,
    };
    use serde_json::json;
    use solana_client::rpc_request::RpcRequest;
    use std::collections::HashMap;

    use super::*;
    use solana_address_lookup_table_interface::state::LookupTableMeta;
    use solana_message::{compiled_instruction::CompiledInstruction, v0, Message};
    use solana_sdk::{
        account::Account,
        hash::Hash,
        instruction::{AccountMeta, Instruction},
        signature::Keypair,
        signer::Signer,
    };

    fn setup_test_config() -> Config {
        ConfigBuilder::new()
            .with_programs(vec![])
            .with_tokens(vec![])
            .with_spl_paid_tokens(SplTokenConfig::Allowlist(vec![]))
            .with_free_price()
            .with_cache_config(None, false, 60, 30) // Disable cache for tests
            .build_config()
            .expect("Failed to build test config")
    }

    #[test]
    fn test_encode_transaction_b64() {
        let keypair = Keypair::new();
        let instruction = Instruction::new_with_bytes(
            Pubkey::new_unique(),
            &[1, 2, 3],
            vec![AccountMeta::new(keypair.pubkey(), true)],
        );
        let message =
            VersionedMessage::Legacy(Message::new(&[instruction], Some(&keypair.pubkey())));
        let tx = VersionedTransaction::try_new(message, &[&keypair]).unwrap();

        let resolved = VersionedTransactionResolved::from_kora_built_transaction(&tx).unwrap();
        let encoded = resolved.encode_b64_transaction().unwrap();
        assert!(!encoded.is_empty());
        assert!(encoded
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '+' || c == '/' || c == '='));
    }

    #[test]
    fn test_encode_decode_b64_transaction() {
        let keypair = Keypair::new();
        let instruction = Instruction::new_with_bytes(
            Pubkey::new_unique(),
            &[1, 2, 3],
            vec![AccountMeta::new(keypair.pubkey(), true)],
        );
        let message =
            VersionedMessage::Legacy(Message::new(&[instruction], Some(&keypair.pubkey())));
        let tx = VersionedTransaction::try_new(message, &[&keypair]).unwrap();

        let resolved = VersionedTransactionResolved::from_kora_built_transaction(&tx).unwrap();
        let encoded = resolved.encode_b64_transaction().unwrap();
        let decoded = TransactionUtil::decode_b64_transaction(&encoded).unwrap();

        assert_eq!(tx, decoded);
    }

    #[test]
    fn test_find_signer_position_success() {
        let keypair = Keypair::new();
        let program_id = Pubkey::new_unique();
        let instruction = Instruction::new_with_bytes(
            program_id,
            &[1, 2, 3],
            vec![AccountMeta::new(keypair.pubkey(), true)],
        );
        let message =
            VersionedMessage::Legacy(Message::new(&[instruction], Some(&keypair.pubkey())));
        let transaction =
            TransactionUtil::new_unsigned_versioned_transaction_resolved(message).unwrap();

        let position = transaction.find_signer_position(&keypair.pubkey()).unwrap();
        assert_eq!(position, 0); // Fee payer is typically at position 0
    }

    #[test]
    fn test_find_signer_position_success_v0() {
        let keypair = Keypair::new();
        let program_id = Pubkey::new_unique();
        let other_account = Pubkey::new_unique();

        let v0_message = v0::Message {
            header: solana_message::MessageHeader {
                num_required_signatures: 1,
                num_readonly_signed_accounts: 0,
                num_readonly_unsigned_accounts: 2,
            },
            account_keys: vec![keypair.pubkey(), other_account, program_id],
            recent_blockhash: Hash::default(),
            instructions: vec![CompiledInstruction {
                program_id_index: 2,
                accounts: vec![0, 1],
                data: vec![1, 2, 3],
            }],
            address_table_lookups: vec![],
        };
        let message = VersionedMessage::V0(v0_message);
        let transaction =
            TransactionUtil::new_unsigned_versioned_transaction_resolved(message).unwrap();

        let position = transaction.find_signer_position(&keypair.pubkey()).unwrap();
        assert_eq!(position, 0);

        let other_position = transaction.find_signer_position(&other_account).unwrap();
        assert_eq!(other_position, 1);
    }

    #[test]
    fn test_find_signer_position_middle_of_accounts() {
        let keypair1 = Keypair::new();
        let keypair2 = Keypair::new();
        let keypair3 = Keypair::new();
        let program_id = Pubkey::new_unique();

        let v0_message = v0::Message {
            header: solana_message::MessageHeader {
                num_required_signatures: 3,
                num_readonly_signed_accounts: 0,
                num_readonly_unsigned_accounts: 1,
            },
            account_keys: vec![keypair1.pubkey(), keypair2.pubkey(), keypair3.pubkey(), program_id],
            recent_blockhash: Hash::default(),
            instructions: vec![CompiledInstruction {
                program_id_index: 3,
                accounts: vec![0, 1, 2],
                data: vec![1, 2, 3],
            }],
            address_table_lookups: vec![],
        };
        let message = VersionedMessage::V0(v0_message);
        let transaction =
            TransactionUtil::new_unsigned_versioned_transaction_resolved(message).unwrap();

        assert_eq!(transaction.find_signer_position(&keypair1.pubkey()).unwrap(), 0);
        assert_eq!(transaction.find_signer_position(&keypair2.pubkey()).unwrap(), 1);
        assert_eq!(transaction.find_signer_position(&keypair3.pubkey()).unwrap(), 2);
    }

    #[test]
    fn test_find_signer_position_not_found() {
        let keypair = Keypair::new();
        let missing_keypair = Keypair::new();
        let instruction = Instruction::new_with_bytes(
            Pubkey::new_unique(),
            &[1, 2, 3],
            vec![AccountMeta::new(keypair.pubkey(), true)],
        );
        let message =
            VersionedMessage::Legacy(Message::new(&[instruction], Some(&keypair.pubkey())));
        let transaction =
            TransactionUtil::new_unsigned_versioned_transaction_resolved(message).unwrap();

        let result = transaction.find_signer_position(&missing_keypair.pubkey());
        assert!(matches!(result, Err(KoraError::InvalidTransaction(_))));

        if let Err(KoraError::InvalidTransaction(msg)) = result {
            assert!(msg.contains(&missing_keypair.pubkey().to_string()));
            assert!(msg.contains("not found in transaction account keys"));
        }
    }

    #[test]
    fn test_find_signer_position_empty_account_keys() {
        // Create a transaction with minimal account keys
        let v0_message = v0::Message {
            header: solana_message::MessageHeader {
                num_required_signatures: 0,
                num_readonly_signed_accounts: 0,
                num_readonly_unsigned_accounts: 0,
            },
            account_keys: vec![], // Empty account keys
            recent_blockhash: Hash::default(),
            instructions: vec![],
            address_table_lookups: vec![],
        };
        let message = VersionedMessage::V0(v0_message);
        let transaction =
            TransactionUtil::new_unsigned_versioned_transaction_resolved(message).unwrap();
        let search_key = Pubkey::new_unique();

        let result = transaction.find_signer_position(&search_key);
        assert!(matches!(result, Err(KoraError::InvalidTransaction(_))));
    }

    #[test]
    fn test_from_kora_built_transaction() {
        let keypair = Keypair::new();
        let program_id = Pubkey::new_unique();
        let instruction = Instruction::new_with_bytes(
            program_id,
            &[1, 2, 3, 4],
            vec![
                AccountMeta::new(keypair.pubkey(), true),
                AccountMeta::new_readonly(Pubkey::new_unique(), false),
            ],
        );
        let message = VersionedMessage::Legacy(Message::new(
            std::slice::from_ref(&instruction),
            Some(&keypair.pubkey()),
        ));
        let transaction = VersionedTransaction::try_new(message.clone(), &[&keypair]).unwrap();

        let resolved =
            VersionedTransactionResolved::from_kora_built_transaction(&transaction).unwrap();

        assert_eq!(resolved.transaction, transaction);
        assert_eq!(resolved.all_account_keys, transaction.message.static_account_keys());
        assert_eq!(resolved.all_instructions.len(), 1);

        // Check instruction properties rather than direct equality since IxUtils::uncompile_instructions
        // properly sets signer status based on the transaction message
        let resolved_instruction = &resolved.all_instructions[0];
        assert_eq!(resolved_instruction.program_id, instruction.program_id);
        assert_eq!(resolved_instruction.data, instruction.data);
        assert_eq!(resolved_instruction.accounts.len(), instruction.accounts.len());

        assert!(resolved.parsed_system_instructions.is_none());
        assert!(resolved.parsed_spl_instructions.is_none());
    }

    #[test]
    fn test_from_kora_built_transaction_v0() {
        let keypair = Keypair::new();
        let program_id = Pubkey::new_unique();
        let other_account = Pubkey::new_unique();

        let v0_message = v0::Message {
            header: solana_message::MessageHeader {
                num_required_signatures: 1,
                num_readonly_signed_accounts: 0,
                num_readonly_unsigned_accounts: 2,
            },
            account_keys: vec![keypair.pubkey(), other_account, program_id],
            recent_blockhash: Hash::new_unique(),
            instructions: vec![CompiledInstruction {
                program_id_index: 2,
                accounts: vec![0, 1],
                data: vec![1, 2, 3],
            }],
            address_table_lookups: vec![],
        };
        let message = VersionedMessage::V0(v0_message);
        let transaction = VersionedTransaction::try_new(message.clone(), &[&keypair]).unwrap();

        let resolved =
            VersionedTransactionResolved::from_kora_built_transaction(&transaction).unwrap();

        assert_eq!(resolved.transaction, transaction);
        assert_eq!(resolved.all_account_keys, vec![keypair.pubkey(), other_account, program_id]);
        assert_eq!(resolved.all_instructions.len(), 1);
        assert_eq!(resolved.all_instructions[0].program_id, program_id);
        assert_eq!(resolved.all_instructions[0].accounts.len(), 2);
        assert_eq!(resolved.all_instructions[0].data, vec![1, 2, 3]);
    }

    #[tokio::test]
    async fn test_from_transaction_legacy() {
        let config = setup_test_config();
        let _m = setup_config_mock(config);

        let keypair = Keypair::new();
        let instruction = Instruction::new_with_bytes(
            Pubkey::new_unique(),
            &[1, 2, 3],
            vec![AccountMeta::new(keypair.pubkey(), true)],
        );
        let message = VersionedMessage::Legacy(Message::new(
            std::slice::from_ref(&instruction),
            Some(&keypair.pubkey()),
        ));
        let transaction = VersionedTransaction::try_new(message, &[&keypair]).unwrap();

        // Mock RPC client that will be used for inner instructions
        let mut mocks = HashMap::new();
        mocks.insert(
            RpcRequest::SimulateTransaction,
            json!({
                "context": { "slot": 1 },
                "value": {
                    "err": null,
                    "logs": [],
                    "accounts": null,
                    "unitsConsumed": 1000,
                    "innerInstructions": []
                }
            }),
        );
        let rpc_client = RpcMockBuilder::new().with_custom_mocks(mocks).build();

        let resolved =
            VersionedTransactionResolved::from_transaction(&transaction, &rpc_client, true)
                .await
                .unwrap();

        assert_eq!(resolved.transaction, transaction);
        assert_eq!(resolved.all_account_keys, transaction.message.static_account_keys());
        assert_eq!(resolved.all_instructions.len(), 1); // Only outer instruction since no inner instructions in mock

        // Check instruction properties rather than direct equality since IxUtils::uncompile_instructions
        // properly sets signer status based on the transaction message
        let resolved_instruction = &resolved.all_instructions[0];
        assert_eq!(resolved_instruction.program_id, instruction.program_id);
        assert_eq!(resolved_instruction.data, instruction.data);
        assert_eq!(resolved_instruction.accounts.len(), instruction.accounts.len());
        assert_eq!(resolved_instruction.accounts[0].pubkey, instruction.accounts[0].pubkey);
        assert_eq!(
            resolved_instruction.accounts[0].is_writable,
            instruction.accounts[0].is_writable
        );
    }

    #[tokio::test]
    async fn test_from_transaction_v0_with_lookup_tables() {
        let config = setup_test_config();
        let _m = setup_config_mock(config);

        let keypair = Keypair::new();
        let program_id = Pubkey::new_unique();
        let lookup_table_account = Pubkey::new_unique();
        let resolved_address = Pubkey::new_unique();

        // Create lookup table
        let lookup_table = AddressLookupTable {
            meta: LookupTableMeta {
                deactivation_slot: u64::MAX,
                last_extended_slot: 0,
                last_extended_slot_start_index: 0,
                authority: Some(Pubkey::new_unique()),
                _padding: 0,
            },
            addresses: vec![resolved_address].into(),
        };

        let v0_message = v0::Message {
            header: solana_message::MessageHeader {
                num_required_signatures: 1,
                num_readonly_signed_accounts: 0,
                num_readonly_unsigned_accounts: 1,
            },
            account_keys: vec![keypair.pubkey(), program_id],
            recent_blockhash: Hash::new_unique(),
            instructions: vec![CompiledInstruction {
                program_id_index: 1,
                accounts: vec![0, 2], // Index 2 comes from lookup table
                data: vec![42],
            }],
            address_table_lookups: vec![solana_message::v0::MessageAddressTableLookup {
                account_key: lookup_table_account,
                writable_indexes: vec![0],
                readonly_indexes: vec![],
            }],
        };

        let message = VersionedMessage::V0(v0_message);
        let transaction = VersionedTransaction::try_new(message, &[&keypair]).unwrap();

        // Create mock RPC client with lookup table account and simulation
        let mut mocks = HashMap::new();
        let serialized_data = lookup_table.serialize_for_tests().unwrap();
        let encoded_data = base64::engine::general_purpose::STANDARD.encode(&serialized_data);

        mocks.insert(
            RpcRequest::GetAccountInfo,
            json!({
                "context": { "slot": 1 },
                "value": {
                    "data": [encoded_data, "base64"],
                    "executable": false,
                    "lamports": 0,
                    "owner": "AddressLookupTab1e1111111111111111111111111".to_string(),
                    "rentEpoch": 0
                }
            }),
        );

        mocks.insert(
            RpcRequest::SimulateTransaction,
            json!({
                "context": { "slot": 1 },
                "value": {
                    "err": null,
                    "logs": [],
                    "accounts": null,
                    "unitsConsumed": 1000,
                    "innerInstructions": []
                }
            }),
        );

        let rpc_client = RpcMockBuilder::new().with_custom_mocks(mocks).build();

        let resolved =
            VersionedTransactionResolved::from_transaction(&transaction, &rpc_client, true)
                .await
                .unwrap();

        assert_eq!(resolved.transaction, transaction);

        // Should include both static accounts and resolved addresses
        assert_eq!(resolved.all_account_keys.len(), 3); // keypair, program_id, resolved_address
        assert_eq!(resolved.all_account_keys[0], keypair.pubkey());
        assert_eq!(resolved.all_account_keys[1], program_id);
        assert_eq!(resolved.all_account_keys[2], resolved_address);
    }

    #[tokio::test]
    async fn test_from_transaction_simulation_failure() {
        let config = setup_test_config();
        let _m = setup_config_mock(config);

        let keypair = Keypair::new();
        let instruction = Instruction::new_with_bytes(
            Pubkey::new_unique(),
            &[1, 2, 3],
            vec![AccountMeta::new(keypair.pubkey(), true)],
        );
        let message =
            VersionedMessage::Legacy(Message::new(&[instruction], Some(&keypair.pubkey())));
        let transaction = VersionedTransaction::try_new(message, &[&keypair]).unwrap();

        // Mock RPC client with simulation error
        let mut mocks = HashMap::new();
        mocks.insert(
            RpcRequest::SimulateTransaction,
            json!({
                "context": { "slot": 1 },
                "value": {
                    "err": "InstructionError",
                    "logs": ["Some error log"],
                    "accounts": null,
                    "unitsConsumed": 0
                }
            }),
        );
        let rpc_client = RpcMockBuilder::new().with_custom_mocks(mocks).build();

        let result =
            VersionedTransactionResolved::from_transaction(&transaction, &rpc_client, true).await;

        // The simulation should fail, but the exact error type depends on mock implementation
        // We expect either an RpcError (from mock deserialization) or InvalidTransaction (from simulation logic)
        assert!(result.is_err());

        match result {
            Err(KoraError::RpcError(msg)) => {
                assert!(msg.contains("Failed to simulate transaction"));
            }
            Err(KoraError::InvalidTransaction(msg)) => {
                assert!(msg.contains("inner instructions fetching failed"));
            }
            _ => panic!("Expected RpcError or InvalidTransaction"),
        }
    }

    #[tokio::test]
    async fn test_fetch_inner_instructions_with_inner_instructions() {
        let config = setup_test_config();
        let _m = setup_config_mock(config);

        let keypair = Keypair::new();
        let instruction = Instruction::new_with_bytes(
            Pubkey::new_unique(),
            &[1, 2, 3],
            vec![AccountMeta::new(keypair.pubkey(), true)],
        );
        let message =
            VersionedMessage::Legacy(Message::new(&[instruction], Some(&keypair.pubkey())));
        let transaction = VersionedTransaction::try_new(message, &[&keypair]).unwrap();

        // Mock RPC client with inner instructions
        let inner_instruction_data = bs58::encode(&[10, 20, 30]).into_string();
        let mut mocks = HashMap::new();
        mocks.insert(
            RpcRequest::SimulateTransaction,
            json!({
                "context": { "slot": 1 },
                "value": {
                    "err": null,
                    "logs": [],
                    "accounts": null,
                    "unitsConsumed": 1000,
                    "innerInstructions": [
                        {
                            "index": 0,
                            "instructions": [
                                {
                                    "programIdIndex": 1,
                                    "accounts": [0],
                                    "data": inner_instruction_data
                                }
                            ]
                        }
                    ]
                }
            }),
        );
        let rpc_client = RpcMockBuilder::new().with_custom_mocks(mocks).build();

        let mut resolved =
            VersionedTransactionResolved::from_kora_built_transaction(&transaction).unwrap();
        let inner_instructions =
            resolved.fetch_inner_instructions(&rpc_client, true).await.unwrap();

        assert_eq!(inner_instructions.len(), 1);
        assert_eq!(inner_instructions[0].data, vec![10, 20, 30]);
    }

    #[tokio::test]
    async fn test_fetch_inner_instructions_with_sig_verify_false() {
        let config = setup_test_config();
        let _m = setup_config_mock(config);

        let keypair = Keypair::new();
        let instruction = Instruction::new_with_bytes(
            Pubkey::new_unique(),
            &[1, 2, 3],
            vec![AccountMeta::new(keypair.pubkey(), true)],
        );
        let message =
            VersionedMessage::Legacy(Message::new(&[instruction], Some(&keypair.pubkey())));
        let transaction = VersionedTransaction::try_new(message, &[&keypair]).unwrap();

        // Mock RPC client with inner instructions
        let inner_instruction_data = bs58::encode(&[10, 20, 30]).into_string();
        let mut mocks = HashMap::new();
        mocks.insert(
            RpcRequest::SimulateTransaction,
            json!({
                "context": { "slot": 1 },
                "value": {
                    "err": null,
                    "logs": [],
                    "accounts": null,
                    "unitsConsumed": 1000,
                    "innerInstructions": [
                        {
                            "index": 0,
                            "instructions": [
                                {
                                    "programIdIndex": 1,
                                    "accounts": [0],
                                    "data": inner_instruction_data
                                }
                            ]
                        }
                    ]
                }
            }),
        );
        let rpc_client = RpcMockBuilder::new().with_custom_mocks(mocks).build();

        let mut resolved =
            VersionedTransactionResolved::from_kora_built_transaction(&transaction).unwrap();
        let inner_instructions =
            resolved.fetch_inner_instructions(&rpc_client, false).await.unwrap();

        assert_eq!(inner_instructions.len(), 1);
        assert_eq!(inner_instructions[0].data, vec![10, 20, 30]);
    }

    #[tokio::test]
    async fn test_get_or_parse_system_instructions() {
        let config = setup_test_config();
        let _m = setup_config_mock(config);

        let keypair = Keypair::new();
        let recipient = Pubkey::new_unique();

        // Create a system transfer instruction
        let instruction =
            solana_system_interface::instruction::transfer(&keypair.pubkey(), &recipient, 1000000);
        let message =
            VersionedMessage::Legacy(Message::new(&[instruction], Some(&keypair.pubkey())));
        let transaction = VersionedTransaction::try_new(message, &[&keypair]).unwrap();

        let mut resolved =
            VersionedTransactionResolved::from_kora_built_transaction(&transaction).unwrap();

        // First call should parse and cache
        let parsed1_len = {
            let parsed1 = resolved.get_or_parse_system_instructions().unwrap();
            assert!(!parsed1.is_empty());
            parsed1.len()
        };

        // Second call should return cached result
        let parsed2 = resolved.get_or_parse_system_instructions().unwrap();
        assert_eq!(parsed1_len, parsed2.len());

        // Should contain transfer instruction
        assert!(
            parsed2.contains_key(&crate::transaction::ParsedSystemInstructionType::SystemTransfer)
        );
    }

    #[tokio::test]
    async fn test_resolve_lookup_table_addresses() {
        let config = setup_test_config();
        let _m = setup_config_mock(config);

        let lookup_account_key = Pubkey::new_unique();
        let address1 = Pubkey::new_unique();
        let address2 = Pubkey::new_unique();
        let address3 = Pubkey::new_unique();

        let lookup_table = AddressLookupTable {
            meta: LookupTableMeta {
                deactivation_slot: u64::MAX,
                last_extended_slot: 0,
                last_extended_slot_start_index: 0,
                authority: Some(Pubkey::new_unique()),
                _padding: 0,
            },
            addresses: vec![address1, address2, address3].into(),
        };

        let serialized_data = lookup_table.serialize_for_tests().unwrap();

        let rpc_client = RpcMockBuilder::new()
            .with_account_info(&Account {
                data: serialized_data,
                executable: false,
                lamports: 0,
                owner: Pubkey::new_unique(),
                rent_epoch: 0,
            })
            .build();

        let lookups = vec![solana_message::v0::MessageAddressTableLookup {
            account_key: lookup_account_key,
            writable_indexes: vec![0, 2], // address1, address3
            readonly_indexes: vec![1],    // address2
        }];

        let resolved_addresses =
            LookupTableUtil::resolve_lookup_table_addresses(&rpc_client, &lookups).await.unwrap();

        assert_eq!(resolved_addresses.len(), 3);
        assert_eq!(resolved_addresses[0], address1);
        assert_eq!(resolved_addresses[1], address3);
        assert_eq!(resolved_addresses[2], address2);
    }

    #[tokio::test]
    async fn test_resolve_lookup_table_addresses_empty() {
        let rpc_client = RpcMockBuilder::new().with_account_not_found().build();
        let lookups = vec![];

        let resolved_addresses =
            LookupTableUtil::resolve_lookup_table_addresses(&rpc_client, &lookups).await.unwrap();

        assert_eq!(resolved_addresses.len(), 0);
    }

    #[tokio::test]
    async fn test_resolve_lookup_table_addresses_account_not_found() {
        let rpc_client = RpcMockBuilder::new().with_account_not_found().build();
        let lookups = vec![solana_message::v0::MessageAddressTableLookup {
            account_key: Pubkey::new_unique(),
            writable_indexes: vec![0],
            readonly_indexes: vec![],
        }];

        let result = LookupTableUtil::resolve_lookup_table_addresses(&rpc_client, &lookups).await;
        assert!(matches!(result, Err(KoraError::RpcError(_))));

        if let Err(KoraError::RpcError(msg)) = result {
            assert!(msg.contains("Failed to fetch lookup table"));
        }
    }

    #[tokio::test]
    async fn test_resolve_lookup_table_addresses_invalid_index() {
        let config = setup_test_config();
        let _m = setup_config_mock(config);

        let lookup_account_key = Pubkey::new_unique();
        let address1 = Pubkey::new_unique();

        let lookup_table = AddressLookupTable {
            meta: LookupTableMeta {
                deactivation_slot: u64::MAX,
                last_extended_slot: 0,
                last_extended_slot_start_index: 0,
                authority: Some(Pubkey::new_unique()),
                _padding: 0,
            },
            addresses: vec![address1].into(), // Only 1 address, index 0
        };

        let serialized_data = lookup_table.serialize_for_tests().unwrap();
        let rpc_client = RpcMockBuilder::new()
            .with_account_info(&Account {
                data: serialized_data,
                executable: false,
                lamports: 0,
                owner: Pubkey::new_unique(),
                rent_epoch: 0,
            })
            .build();

        // Try to access index 1 which doesn't exist
        let lookups = vec![solana_message::v0::MessageAddressTableLookup {
            account_key: lookup_account_key,
            writable_indexes: vec![1], // Invalid index
            readonly_indexes: vec![],
        }];

        let result = LookupTableUtil::resolve_lookup_table_addresses(&rpc_client, &lookups).await;
        assert!(matches!(result, Err(KoraError::InvalidTransaction(_))));

        if let Err(KoraError::InvalidTransaction(msg)) = result {
            assert!(msg.contains("index 1 out of bounds"));
            assert!(msg.contains("writable addresses"));
        }
    }

    #[tokio::test]
    async fn test_resolve_lookup_table_addresses_invalid_readonly_index() {
        let config = setup_test_config();
        let _m = setup_config_mock(config);

        let lookup_account_key = Pubkey::new_unique();
        let address1 = Pubkey::new_unique();

        let lookup_table = AddressLookupTable {
            meta: LookupTableMeta {
                deactivation_slot: u64::MAX,
                last_extended_slot: 0,
                last_extended_slot_start_index: 0,
                authority: Some(Pubkey::new_unique()),
                _padding: 0,
            },
            addresses: vec![address1].into(),
        };

        let serialized_data = lookup_table.serialize_for_tests().unwrap();
        let rpc_client = RpcMockBuilder::new()
            .with_account_info(&Account {
                data: serialized_data,
                executable: false,
                lamports: 0,
                owner: Pubkey::new_unique(),
                rent_epoch: 0,
            })
            .build();

        let lookups = vec![solana_message::v0::MessageAddressTableLookup {
            account_key: lookup_account_key,
            writable_indexes: vec![],
            readonly_indexes: vec![5], // Invalid index
        }];

        let result = LookupTableUtil::resolve_lookup_table_addresses(&rpc_client, &lookups).await;
        assert!(matches!(result, Err(KoraError::InvalidTransaction(_))));

        if let Err(KoraError::InvalidTransaction(msg)) = result {
            assert!(msg.contains("index 5 out of bounds"));
            assert!(msg.contains("readonly addresses"));
        }
    }
}