openzeppelin_relayer/domain/relayer/solana/rpc/methods/
token.rs

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
//! Solana token programs interaction module.
//!
//! This module provides abstractions and utilities for interacting with Solana token programs,
//! specifically SPL Token and Token-2022. It offers unified interfaces for common token operations
//! like transfers, account creation, and account data parsing.
//!
//! This module abstracts away differences between token program versions, allowing
//! for consistent interaction regardless of which token program (SPL Token or Token-2022)
//! is being used.
use ::spl_token::state::Account as SplTokenAccount;
use log::error;
use solana_sdk::{
    account::Account as SolanaAccount, instruction::Instruction, program_pack::Pack, pubkey::Pubkey,
};
use spl_associated_token_account::get_associated_token_address_with_program_id;

use spl_associated_token_account::instruction::create_associated_token_account;

use crate::services::SolanaProviderTrait;

/// Represents a Solana token account with its key properties.
///
/// This struct contains the essential information about a token account,
/// including the mint address, owner, token amount, and frozen status.
#[derive(Debug)]
pub struct TokenAccount {
    /// The mint address of the token
    pub mint: Pubkey,
    /// The owner of the token account
    pub owner: Pubkey,
    /// The amount of tokens held in this account
    pub amount: u64,
    /// Whether the account is frozen
    pub is_frozen: bool,
}

/// Error types that can occur during token operations.
///
/// This enum provides specific error variants for different token-related failures,
/// making it easier to diagnose and handle token operation issues.
#[derive(Debug, thiserror::Error)]
pub enum TokenError {
    /// Error when a token instruction is invalid
    #[error("Invalid token instruction: {0}")]
    InvalidTokenInstruction(String),
    /// Error when a token mint is invalid
    #[error("Invalid token mint: {0}")]
    InvalidTokenMint(String),
    /// Error when a token program is invalid
    #[error("Invalid token program: {0}")]
    InvalidTokenProgram(String),
    /// Error when an instruction fails
    #[error("Instruction error: {0}")]
    Instruction(String),
    /// Error when an account operation fails
    #[error("Account error: {0}")]
    AccountError(String),
}

/// Represents different types of token instructions.
///
/// This enum provides variants for the most common token instructions,
/// with a catch-all variant for other instruction types.
#[derive(Debug)]
pub enum TokenInstruction {
    /// A simple transfer instruction
    Transfer { amount: u64 },
    /// A transfer with decimal checking
    TransferChecked { amount: u64, decimals: u8 },
    /// Catch-all variant for other instruction types
    Other,
}

/// Implementation of the Solana token program functionality.
///
/// This struct provides concrete implementations for the SolanaToken trait,
/// supporting both the SPL Token and Token-2022 programs.
pub struct SolanaTokenProgram;

impl SolanaTokenProgram {
    /// Get the token program for a mint
    pub async fn get_token_program_for_mint<P: SolanaProviderTrait>(
        provider: &P,
        mint: &Pubkey,
    ) -> Result<Pubkey, TokenError> {
        let account = provider
            .get_account_from_pubkey(mint)
            .await
            .map_err(|e| TokenError::InvalidTokenMint(e.to_string()))?;

        if account.owner == spl_token::id() {
            Ok(spl_token::id())
        } else if account.owner == spl_token_2022::id() {
            Ok(spl_token_2022::id())
        } else {
            Err(TokenError::InvalidTokenProgram(format!(
                "Unknown token program: {}",
                account.owner
            )))
        }
    }

    /// Checks if a program ID corresponds to a known token program.
    ///
    /// # Arguments
    ///
    /// * `program_id` - The program ID to check
    ///
    /// # Returns
    ///
    /// `true` if the program ID is SPL Token or Token-2022, `false` otherwise
    pub fn is_token_program(program_id: &Pubkey) -> bool {
        program_id == &spl_token::id() || program_id == &spl_token_2022::id()
    }

    /// Creates a transfer checked instruction.
    ///
    /// # Arguments
    ///
    /// * `program_id` - The program ID of the token program
    /// * `source` - The source token account
    /// * `mint` - The mint address
    /// * `destination` - The destination token account
    /// * `authority` - The authority that can sign for the source account
    /// * `amount` - The amount to transfer
    /// * `decimals` - The number of decimals for the token
    ///
    /// # Returns
    ///
    /// A Result containing either the transfer instruction or a TokenError
    pub fn create_transfer_checked_instruction(
        program_id: &Pubkey,
        source: &Pubkey,
        mint: &Pubkey,
        destination: &Pubkey,
        authority: &Pubkey,
        amount: u64,
        decimals: u8,
    ) -> Result<Instruction, TokenError> {
        if !Self::is_token_program(program_id) {
            return Err(TokenError::InvalidTokenProgram(format!(
                "Unknown token program: {}",
                program_id
            )));
        }
        if program_id == &spl_token::id() {
            return spl_token::instruction::transfer_checked(
                program_id,
                source,
                mint,
                destination,
                authority,
                &[],
                amount,
                decimals,
            )
            .map_err(|e| TokenError::Instruction(e.to_string()));
        } else if program_id == &spl_token_2022::id() {
            return spl_token_2022::instruction::transfer_checked(
                program_id,
                source,
                mint,
                destination,
                authority,
                &[],
                amount,
                decimals,
            )
            .map_err(|e| TokenError::Instruction(e.to_string()));
        }
        Err(TokenError::InvalidTokenProgram(format!(
            "Unknown token program: {}",
            program_id
        )))
    }

    /// Unpacks a Solana account into a TokenAccount structure.
    ///
    /// # Arguments
    ///
    /// * `program_id` - The program ID of the token program
    /// * `account` - The Solana account to unpack
    ///
    /// # Returns
    ///
    /// A Result containing either the unpacked TokenAccount or a TokenError
    pub fn unpack_account(
        program_id: &Pubkey,
        account: &SolanaAccount,
    ) -> Result<TokenAccount, TokenError> {
        if !Self::is_token_program(program_id) {
            return Err(TokenError::InvalidTokenProgram(format!(
                "Unknown token program: {}",
                program_id
            )));
        }
        if program_id == &spl_token::id() {
            let account = SplTokenAccount::unpack(&account.data)
                .map_err(|e| TokenError::AccountError(format!("Invalid token account1: {}", e)))?;

            return Ok(TokenAccount {
                mint: account.mint,
                owner: account.owner,
                amount: account.amount,
                is_frozen: account.is_frozen(),
            });
        } else if program_id == &spl_token_2022::id() {
            let state_with_extensions = spl_token_2022::extension::StateWithExtensions::<
                spl_token_2022::state::Account,
            >::unpack(&account.data)
            .map_err(|e| TokenError::AccountError(format!("Invalid token account2: {}", e)))?;

            let base_account = state_with_extensions.base;

            return Ok(TokenAccount {
                mint: base_account.mint,
                owner: base_account.owner,
                amount: base_account.amount,
                is_frozen: base_account.is_frozen(),
            });
        }
        Err(TokenError::InvalidTokenProgram(format!(
            "Unknown token program: {}",
            program_id
        )))
    }

    /// Gets the associated token address for a wallet and mint.
    ///
    /// # Arguments
    ///
    /// * `program_id` - The program ID of the token program
    /// * `wallet` - The wallet address
    /// * `mint` - The mint address
    ///
    /// # Returns
    ///
    /// The associated token address
    pub fn get_associated_token_address(
        program_id: &Pubkey,
        wallet: &Pubkey,
        mint: &Pubkey,
    ) -> Pubkey {
        get_associated_token_address_with_program_id(wallet, mint, program_id)
    }

    /// Creates an instruction to create an associated token account.
    ///
    /// # Arguments
    ///
    /// * `program_id` - The program ID of the token program
    /// * `payer` - The account that will pay for the account creation
    /// * `wallet` - The wallet address
    /// * `mint` - The mint address
    ///
    /// # Returns
    ///
    /// An instruction to create the associated token account
    pub fn create_associated_token_account(
        program_id: &Pubkey,
        payer: &Pubkey,
        wallet: &Pubkey,
        mint: &Pubkey,
    ) -> Instruction {
        create_associated_token_account(payer, wallet, mint, program_id)
    }

    /// Unpacks a token instruction from its binary data.
    ///
    /// # Arguments
    ///
    /// * `program_id` - The program ID of the token program
    /// * `data` - The binary instruction data
    ///
    /// # Returns
    ///
    /// A Result containing either the unpacked TokenInstruction or a TokenError
    pub fn unpack_instruction(
        program_id: &Pubkey,
        data: &[u8],
    ) -> Result<TokenInstruction, TokenError> {
        if !Self::is_token_program(program_id) {
            return Err(TokenError::InvalidTokenProgram(format!(
                "Unknown token program: {}",
                program_id
            )));
        }
        if program_id == &spl_token::id() {
            match spl_token::instruction::TokenInstruction::unpack(data) {
                Ok(instr) => match instr {
                    spl_token::instruction::TokenInstruction::Transfer { amount } => {
                        Ok(TokenInstruction::Transfer { amount })
                    }
                    spl_token::instruction::TokenInstruction::TransferChecked {
                        amount,
                        decimals,
                    } => Ok(TokenInstruction::TransferChecked { amount, decimals }),
                    _ => Ok(TokenInstruction::Other), // Catch all other instruction types
                },
                Err(e) => Err(TokenError::InvalidTokenInstruction(e.to_string())),
            }
        } else if program_id == &spl_token_2022::id() {
            match spl_token_2022::instruction::TokenInstruction::unpack(data) {
                Ok(instr) => match instr {
                    #[allow(deprecated)]
                    spl_token_2022::instruction::TokenInstruction::Transfer { amount } => {
                        Ok(TokenInstruction::Transfer { amount })
                    }
                    spl_token_2022::instruction::TokenInstruction::TransferChecked {
                        amount,
                        decimals,
                    } => Ok(TokenInstruction::TransferChecked { amount, decimals }),
                    _ => Ok(TokenInstruction::Other), // Catch all other instruction types
                },
                Err(e) => Err(TokenError::InvalidTokenInstruction(e.to_string())),
            }
        } else {
            Err(TokenError::InvalidTokenProgram(format!(
                "Unknown token program: {}",
                program_id
            )))
        }
    }
}

#[cfg(test)]
mod tests {
    use mockall::predicate::eq;
    use solana_sdk::{program_pack::Pack, pubkey::Pubkey};
    use spl_associated_token_account::get_associated_token_address_with_program_id;
    use spl_associated_token_account::instruction::create_associated_token_account;
    use spl_token::state::Account;

    use crate::{
        domain::{SolanaTokenProgram, TokenError, TokenInstruction},
        services::MockSolanaProviderTrait,
    };

    #[tokio::test]
    async fn test_get_token_program_for_mint_spl_token() {
        let mint = Pubkey::new_unique();
        let mut mock_provider = MockSolanaProviderTrait::new();

        mock_provider
            .expect_get_account_from_pubkey()
            .with(eq(mint))
            .times(1)
            .returning(|_| {
                Box::pin(async {
                    Ok(solana_sdk::account::Account {
                        lamports: 1000000,
                        data: vec![],
                        owner: spl_token::id(),
                        executable: false,
                        rent_epoch: 0,
                    })
                })
            });

        let result = SolanaTokenProgram::get_token_program_for_mint(&mock_provider, &mint).await;

        assert!(result.is_ok());
        assert_eq!(result.unwrap(), spl_token::id());
    }

    #[tokio::test]
    async fn test_get_token_program_for_mint_token_2022() {
        let mint = Pubkey::new_unique();
        let mut mock_provider = MockSolanaProviderTrait::new();

        mock_provider
            .expect_get_account_from_pubkey()
            .with(eq(mint))
            .times(1)
            .returning(|_| {
                Box::pin(async {
                    Ok(solana_sdk::account::Account {
                        lamports: 1000000,
                        data: vec![],
                        owner: spl_token_2022::id(),
                        executable: false,
                        rent_epoch: 0,
                    })
                })
            });

        let result = SolanaTokenProgram::get_token_program_for_mint(&mock_provider, &mint).await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), spl_token_2022::id());
    }

    #[tokio::test]
    async fn test_get_token_program_for_mint_invalid() {
        let mint = Pubkey::new_unique();
        let mut mock_provider = MockSolanaProviderTrait::new();

        mock_provider
            .expect_get_account_from_pubkey()
            .with(eq(mint))
            .times(1)
            .returning(|_| {
                Box::pin(async {
                    Ok(solana_sdk::account::Account {
                        lamports: 1000000,
                        data: vec![],
                        owner: Pubkey::new_unique(),
                        executable: false,
                        rent_epoch: 0,
                    })
                })
            });

        let result = SolanaTokenProgram::get_token_program_for_mint(&mock_provider, &mint).await;
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            TokenError::InvalidTokenProgram(_)
        ));
    }

    #[test]
    fn test_is_token_program() {
        assert!(SolanaTokenProgram::is_token_program(&spl_token::id()));
        assert!(SolanaTokenProgram::is_token_program(&spl_token_2022::id()));
        assert!(!SolanaTokenProgram::is_token_program(&Pubkey::new_unique()));
    }

    #[test]
    fn test_create_transfer_checked_instruction_spl_token() {
        let program_id = spl_token::id();
        let source = Pubkey::new_unique();
        let mint = Pubkey::new_unique();
        let destination = Pubkey::new_unique();
        let authority = Pubkey::new_unique();
        let amount = 1000;
        let decimals = 9;

        let result = SolanaTokenProgram::create_transfer_checked_instruction(
            &program_id,
            &source,
            &mint,
            &destination,
            &authority,
            amount,
            decimals,
        );

        assert!(result.is_ok());
        let instruction = result.unwrap();
        assert_eq!(instruction.program_id, program_id);
        assert_eq!(instruction.accounts.len(), 4);
        assert_eq!(instruction.accounts[0].pubkey, source);
        assert_eq!(instruction.accounts[1].pubkey, mint);
        assert_eq!(instruction.accounts[2].pubkey, destination);
        assert_eq!(instruction.accounts[3].pubkey, authority);
    }

    #[test]
    fn test_create_transfer_checked_instruction_token_2022() {
        let program_id = spl_token_2022::id();
        let source = Pubkey::new_unique();
        let mint = Pubkey::new_unique();
        let destination = Pubkey::new_unique();
        let authority = Pubkey::new_unique();
        let amount = 1000;
        let decimals = 9;

        let result = SolanaTokenProgram::create_transfer_checked_instruction(
            &program_id,
            &source,
            &mint,
            &destination,
            &authority,
            amount,
            decimals,
        );

        assert!(result.is_ok());
        let instruction = result.unwrap();
        assert_eq!(instruction.program_id, program_id);
        assert_eq!(instruction.accounts.len(), 4);
        assert_eq!(instruction.accounts[0].pubkey, source);
        assert_eq!(instruction.accounts[1].pubkey, mint);
        assert_eq!(instruction.accounts[2].pubkey, destination);
        assert_eq!(instruction.accounts[3].pubkey, authority);
    }

    #[test]
    fn test_create_transfer_checked_instruction_invalid_program() {
        let program_id = Pubkey::new_unique(); // Invalid program ID
        let source = Pubkey::new_unique();
        let mint = Pubkey::new_unique();
        let destination = Pubkey::new_unique();
        let authority = Pubkey::new_unique();
        let amount = 1000;
        let decimals = 9;

        let result = SolanaTokenProgram::create_transfer_checked_instruction(
            &program_id,
            &source,
            &mint,
            &destination,
            &authority,
            amount,
            decimals,
        );

        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            TokenError::InvalidTokenProgram(_)
        ));
    }

    #[test]
    fn test_unpack_account_spl_token() {
        let program_id = spl_token::id();
        let mint = Pubkey::new_unique();
        let owner = Pubkey::new_unique();
        let amount = 1000;

        let spl_account = Account {
            mint,
            owner,
            amount,
            state: spl_token::state::AccountState::Initialized,
            ..Default::default()
        };

        let mut account_data = vec![0; Account::LEN];
        Account::pack(spl_account, &mut account_data).unwrap();

        let solana_account = solana_sdk::account::Account {
            lamports: 0,
            data: account_data,
            owner: program_id,
            executable: false,
            rent_epoch: 0,
        };

        let result = SolanaTokenProgram::unpack_account(&program_id, &solana_account);
        assert!(result.is_ok());

        let token_account = result.unwrap();
        assert_eq!(token_account.mint, mint);
        assert_eq!(token_account.owner, owner);
        assert_eq!(token_account.amount, amount);
        assert!(!token_account.is_frozen);
    }

    #[test]
    fn test_unpack_account_token_2022() {
        let program_id = spl_token_2022::id();
        let mint = Pubkey::new_unique();
        let owner = Pubkey::new_unique();
        let amount = 1000;

        let spl_account = Account {
            mint,
            owner,
            amount,
            state: spl_token::state::AccountState::Initialized,
            ..Default::default()
        };

        let mut account_data = vec![0; Account::LEN];
        Account::pack(spl_account, &mut account_data).unwrap();

        let solana_account = solana_sdk::account::Account {
            lamports: 0,
            data: account_data,
            owner: program_id,
            executable: false,
            rent_epoch: 0,
        };

        let result = SolanaTokenProgram::unpack_account(&program_id, &solana_account);
        assert!(result.is_ok());

        let token_account = result.unwrap();
        assert_eq!(token_account.mint, mint);
        assert_eq!(token_account.owner, owner);
        assert_eq!(token_account.amount, amount);
        assert!(!token_account.is_frozen);
    }

    #[test]
    fn test_unpack_account_invalid_program() {
        let program_id = Pubkey::new_unique(); // Invalid program ID
        let mint = Pubkey::new_unique();
        let owner = Pubkey::new_unique();
        let amount = 1000;

        let spl_account = Account {
            mint,
            owner,
            amount,
            state: spl_token::state::AccountState::Initialized,
            ..Default::default()
        };

        let mut account_data = vec![0; Account::LEN];
        Account::pack(spl_account, &mut account_data).unwrap();

        let account = solana_sdk::account::Account {
            lamports: 0,
            data: account_data,
            owner: program_id,
            executable: false,
            rent_epoch: 0,
        };

        let result = SolanaTokenProgram::unpack_account(&program_id, &account);
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            TokenError::InvalidTokenProgram(_)
        ));
    }

    #[test]
    fn test_get_associated_token_address_spl_token() {
        let program_id = spl_token::id();
        let wallet = Pubkey::new_unique();
        let mint = Pubkey::new_unique();

        let result = SolanaTokenProgram::get_associated_token_address(&program_id, &wallet, &mint);
        let expected = get_associated_token_address_with_program_id(&wallet, &mint, &program_id);

        assert_eq!(result, expected);
    }

    #[test]
    fn test_get_associated_token_address_token_2022() {
        let program_id = spl_token_2022::id();
        let wallet = Pubkey::new_unique();
        let mint = Pubkey::new_unique();

        let result = SolanaTokenProgram::get_associated_token_address(&program_id, &wallet, &mint);
        let expected = get_associated_token_address_with_program_id(&wallet, &mint, &program_id);

        assert_eq!(result, expected);
    }

    #[test]
    fn test_create_associated_token_account() {
        let program_id = spl_token::id();
        let payer = Pubkey::new_unique();
        let wallet = Pubkey::new_unique();
        let mint = Pubkey::new_unique();

        let instruction = SolanaTokenProgram::create_associated_token_account(
            &program_id,
            &payer,
            &wallet,
            &mint,
        );

        let expected = create_associated_token_account(&payer, &wallet, &mint, &program_id);

        assert_eq!(instruction.program_id, expected.program_id);
        assert_eq!(instruction.accounts.len(), expected.accounts.len());

        for (i, account) in instruction.accounts.iter().enumerate() {
            assert_eq!(account.pubkey, expected.accounts[i].pubkey);
            assert_eq!(account.is_signer, expected.accounts[i].is_signer);
            assert_eq!(account.is_writable, expected.accounts[i].is_writable);
        }
    }

    #[test]
    fn test_unpack_instruction_spl_token_transfer() {
        let program_id = spl_token::id();
        let amount = 1000u64;

        let instruction = spl_token::instruction::transfer(
            &program_id,
            &Pubkey::new_unique(),
            &Pubkey::new_unique(),
            &Pubkey::new_unique(),
            &[],
            amount,
        )
        .unwrap();

        let result = SolanaTokenProgram::unpack_instruction(&program_id, &instruction.data);
        assert!(result.is_ok());

        if let TokenInstruction::Transfer {
            amount: parsed_amount,
        } = result.unwrap()
        {
            assert_eq!(parsed_amount, amount);
        } else {
            panic!("Expected Transfer instruction");
        }
    }

    #[test]
    fn test_unpack_instruction_spl_token_transfer_checked() {
        let program_id = spl_token::id();
        let amount = 1000u64;
        let decimals = 9u8;

        let instruction = spl_token::instruction::transfer_checked(
            &program_id,
            &Pubkey::new_unique(),
            &Pubkey::new_unique(),
            &Pubkey::new_unique(),
            &Pubkey::new_unique(),
            &[],
            amount,
            decimals,
        )
        .unwrap();

        let result = SolanaTokenProgram::unpack_instruction(&program_id, &instruction.data);
        assert!(result.is_ok());

        if let TokenInstruction::TransferChecked {
            amount: parsed_amount,
            decimals: parsed_decimals,
        } = result.unwrap()
        {
            assert_eq!(parsed_amount, amount);
            assert_eq!(parsed_decimals, decimals);
        } else {
            panic!("Expected TransferChecked instruction");
        }
    }

    #[test]
    fn test_unpack_instruction_token_2022_transfer() {
        let program_id = spl_token_2022::id();
        let amount = 1000u64;

        #[allow(deprecated)]
        let instruction = spl_token_2022::instruction::transfer(
            &program_id,
            &Pubkey::new_unique(),
            &Pubkey::new_unique(),
            &Pubkey::new_unique(),
            &[],
            amount,
        )
        .unwrap();

        let result = SolanaTokenProgram::unpack_instruction(&program_id, &instruction.data);
        assert!(result.is_ok());

        if let TokenInstruction::Transfer {
            amount: parsed_amount,
        } = result.unwrap()
        {
            assert_eq!(parsed_amount, amount);
        } else {
            panic!("Expected Transfer instruction");
        }
    }

    #[test]
    fn test_unpack_instruction_token_2022_transfer_checked() {
        let program_id = spl_token_2022::id();
        let amount = 1000u64;
        let decimals = 9u8;

        let instruction = spl_token_2022::instruction::transfer_checked(
            &program_id,
            &Pubkey::new_unique(),
            &Pubkey::new_unique(),
            &Pubkey::new_unique(),
            &Pubkey::new_unique(),
            &[],
            amount,
            decimals,
        )
        .unwrap();

        let result = SolanaTokenProgram::unpack_instruction(&program_id, &instruction.data);
        assert!(result.is_ok());

        if let TokenInstruction::TransferChecked {
            amount: parsed_amount,
            decimals: parsed_decimals,
        } = result.unwrap()
        {
            assert_eq!(parsed_amount, amount);
            assert_eq!(parsed_decimals, decimals);
        } else {
            panic!("Expected TransferChecked instruction");
        }
    }

    #[test]
    fn test_unpack_instruction_invalid_program() {
        let program_id = Pubkey::new_unique(); // Invalid program ID
        let data = vec![0, 1, 2, 3];

        let result = SolanaTokenProgram::unpack_instruction(&program_id, &data);
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            TokenError::InvalidTokenProgram(_)
        ));
    }
}