light-sdk-macros 0.23.0

Macros for Programs using the Light SDK for ZK Compression
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
//! Program-wide variant enum generation for #[light_program] macro.
//!
//! This module generates:
//! 1. `LightAccountVariant` enum collecting all per-field variants from instruction structs
//! 2. `PackedLightAccountVariant` enum with packed versions
//! 3. `impl DecompressVariant for PackedLightAccountVariant` dispatch
//!
//! Token variants are first-class members of the main enums, using
//! `TokenDataWithSeeds<S>` / `TokenDataWithPackedSeeds<S>` wrappers.
//! The per-field variant structs (`{Field}Variant`, `Packed{Field}Variant`) are generated
//! by `#[derive(LightAccounts)]` in `accounts/variant.rs`.

use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use syn::{Ident, Result, Type};

use super::parsing::{SeedElement, TokenSeedSpec};
use crate::light_pdas::{backend::CodegenBackend, shared_utils::qualify_type_with_crate};

// =============================================================================
// LIGHT VARIANT BUILDER
// =============================================================================

/// Builder for generating program-wide variant enums and dispatch implementations.
///
/// Takes `PdaCtxSeedInfo` and `TokenSeedSpec` collected from instruction account
/// structs and generates unified enums where both PDA and token variants are
/// first-class members.
pub(super) struct LightVariantBuilder<'a> {
    /// PDA ctx seed info collected from all instruction account structs.
    pda_ctx_seeds: &'a [PdaCtxSeedInfo],
    /// Token seed specifications (empty slice if no token accounts).
    token_seeds: &'a [TokenSeedSpec],
}

impl<'a> LightVariantBuilder<'a> {
    /// Create a new LightVariantBuilder with the given PDA ctx seed info.
    pub fn new(pda_ctx_seeds: &'a [PdaCtxSeedInfo]) -> Self {
        Self {
            pda_ctx_seeds,
            token_seeds: &[],
        }
    }

    /// Set token seed specs (for programs with token fields).
    pub fn with_token_seeds(mut self, token_seeds: &'a [TokenSeedSpec]) -> Self {
        self.token_seeds = token_seeds;
        self
    }

    /// Validate the builder configuration.
    pub fn validate(&self) -> Result<()> {
        if self.pda_ctx_seeds.is_empty() {
            return Err(syn::Error::new(
                proc_macro2::Span::call_site(),
                "#[light_program] requires at least one Accounts struct with \
                 #[light_account(init)] fields.\n\n\
                 Make sure your program has:\n\
                 1. An Accounts struct with #[derive(Accounts, LightAccounts)]\n\
                 2. At least one field marked with #[light_account(init)]\n\n\
                 Example:\n\
                 #[derive(Accounts, LightAccounts)]\n\
                 #[instruction(params: MyParams)]\n\
                 pub struct MyAccounts<'info> {\n    \
                     #[account(init, ...)]\n    \
                     #[light_account(init)]\n    \
                     pub my_account: Account<'info, MyData>,\n\
                 }",
            ));
        }
        Ok(())
    }

    /// Generate the complete enum definitions and trait implementations using the specified backend.
    pub fn build_with_backend(&self, backend: &dyn CodegenBackend) -> Result<TokenStream> {
        self.validate()?;

        // NOTE: Variant structs (`RecordVariant`, `PackedRecordVariant`, etc.) are generated
        // by `#[derive(LightAccounts)]` in the instruction module. We just wrap them in
        // the program-wide enum here. Do NOT regenerate them to avoid conflicts.
        let token_seeds_structs = self.generate_token_seeds_structs_with_backend(backend);
        let token_variant_trait_impls =
            self.generate_token_variant_trait_impls_with_backend(backend);
        let unpacked_enum = self.generate_unpacked_enum_with_backend(backend);
        let packed_enum = self.generate_packed_enum_with_backend(backend);
        let light_account_data_struct =
            self.generate_light_account_data_struct_with_backend(backend);
        let decompress_variant_impl = self.generate_decompress_variant_impl_with_backend(backend);
        let pack_impl = self.generate_pack_impl_with_backend(backend);

        Ok(quote! {
            #token_seeds_structs
            #token_variant_trait_impls
            #unpacked_enum
            #packed_enum
            #light_account_data_struct
            #decompress_variant_impl
            #pack_impl
        })
    }

    // =========================================================================
    // UNIFIED BACKEND-BASED GENERATION METHODS
    // =========================================================================

    /// Generate the `LightAccountData` wrapper struct using the specified backend.
    fn generate_light_account_data_struct_with_backend(
        &self,
        backend: &dyn CodegenBackend,
    ) -> TokenStream {
        let account_crate = backend.account_crate();
        let serialize_derive = backend.serialize_derive();
        let deserialize_derive = backend.deserialize_derive();

        if backend.is_pinocchio() {
            quote! {
                #[derive(Clone, Debug, #serialize_derive, #deserialize_derive)]
                pub struct LightAccountData {
                    pub meta: #account_crate::account_meta::CompressedAccountMetaNoLamportsNoAddress,
                    pub data: PackedLightAccountVariant,
                }
            }
        } else {
            quote! {
                /// Wrapper for compressed account data with metadata.
                /// Contains PACKED variant data that will be decompressed into PDA accounts.
                #[derive(Clone, Debug, #serialize_derive, #deserialize_derive)]
                pub struct LightAccountData {
                    pub meta: #account_crate::account_meta::CompressedAccountMetaNoLamportsNoAddress,
                    pub data: PackedLightAccountVariant,
                }
            }
        }
    }

    // =========================================================================
    // TOKEN SEEDS STRUCTS
    // =========================================================================

    /// Generate `{Variant}Seeds`, `Packed{Variant}Seeds`, and their Pack/Unpack impls
    /// for each token variant using the specified backend.
    fn generate_token_seeds_structs_with_backend(
        &self,
        backend: &dyn CodegenBackend,
    ) -> TokenStream {
        let account_crate = backend.account_crate();
        let serialize_derive = backend.serialize_derive();
        let deserialize_derive = backend.deserialize_derive();
        let sdk_error = backend.sdk_error_type();

        let structs: Vec<_> = self
            .token_seeds
            .iter()
            .map(|spec| {
                let variant_name = &spec.variant;
                let seeds_name = format_ident!("{}Seeds", variant_name);
                let packed_seeds_name = format_ident!("Packed{}Seeds", variant_name);
                let ctx_fields = extract_ctx_fields_from_token_spec(spec);

                // Unpacked seeds: Pubkey or [u8; 32] fields depending on backend
                let unpacked_fields: Vec<_> = ctx_fields
                    .iter()
                    .map(|f| {
                        if backend.is_pinocchio() {
                            quote! { pub #f: [u8; 32] }
                        } else {
                            quote! { pub #f: Pubkey }
                        }
                    })
                    .collect();

                // Packed seeds: u8 index fields + bump
                let packed_fields: Vec<_> = ctx_fields
                    .iter()
                    .map(|f| {
                        let idx = format_ident!("{}_idx", f);
                        quote! { pub #idx: u8 }
                    })
                    .collect();

                // Pack impl: Pubkey -> u8 index
                let pack_stmts: Vec<_> = ctx_fields
                    .iter()
                    .map(|f| {
                        let idx = format_ident!("{}_idx", f);
                        if backend.is_pinocchio() {
                            quote! { #idx: remaining_accounts.insert_or_get(light_account_pinocchio::solana_pubkey::Pubkey::from(self.#f)) }
                        } else {
                            quote! { #idx: remaining_accounts.insert_or_get(AM::pubkey_from_bytes(self.#f.to_bytes())) }
                        }
                    })
                    .collect();

                // Seed refs for find_program_address bump derivation
                let bump_seed_refs: Vec<_> = spec
                    .seeds
                    .iter()
                    .map(seed_to_unpacked_ref)
                    .collect();

                // Unpack impl: u8 index -> Pubkey or [u8; 32]
                let unpack_resolve_stmts: Vec<_> = ctx_fields
                    .iter()
                    .map(|f| {
                        let idx = format_ident!("{}_idx", f);
                        if backend.is_pinocchio() {
                            quote! {
                                let #f: [u8; 32] =
                                    remaining_accounts
                                        .get(self.#idx as usize)
                                        .ok_or(#sdk_error::InvalidInstructionData)?
                                        .key();
                            }
                        } else {
                            quote! {
                                let #f = solana_pubkey::Pubkey::new_from_array(
                                    remaining_accounts
                                        .get(self.#idx as usize)
                                        .ok_or(#sdk_error::InvalidInstructionData)?
                                        .key()
                                );
                            }
                        }
                    })
                    .collect();

                let unpack_field_assigns: Vec<_> = ctx_fields.iter().map(|f| quote! { #f }).collect();

                let seeds_struct = if unpacked_fields.is_empty() {
                    quote! {
                        #[derive(#serialize_derive, #deserialize_derive, Clone, Debug)]
                        pub struct #seeds_name;
                    }
                } else {
                    quote! {
                        #[derive(#serialize_derive, #deserialize_derive, Clone, Debug)]
                        pub struct #seeds_name {
                            #(#unpacked_fields,)*
                        }
                    }
                };

                let pack_impl = if backend.is_pinocchio() {
                    quote! {
                        #[cfg(not(target_os = "solana"))]
                        impl #account_crate::Pack<#account_crate::solana_instruction::AccountMeta> for #seeds_name {
                            type Packed = #packed_seeds_name;

                            fn pack(
                                &self,
                                remaining_accounts: &mut #account_crate::PackedAccounts,
                            ) -> std::result::Result<Self::Packed, #sdk_error> {
                                let __seeds: &[&[u8]] = &[#(#bump_seed_refs),*];
                                let (_, __bump) = #account_crate::solana_pubkey::Pubkey::find_program_address(
                                    __seeds,
                                    &#account_crate::solana_pubkey::Pubkey::from(crate::LIGHT_CPI_SIGNER.program_id),
                                );
                                Ok(#packed_seeds_name {
                                    #(#pack_stmts,)*
                                    bump: __bump,
                                })
                            }
                        }
                    }
                } else {
                    quote! {
                        // Pack trait is only available off-chain (client-side)
                        #[cfg(not(target_os = "solana"))]
                        impl<AM: #account_crate::AccountMetaTrait> #account_crate::Pack<AM> for #seeds_name {
                            type Packed = #packed_seeds_name;

                            fn pack(
                                &self,
                                remaining_accounts: &mut #account_crate::interface::instruction::PackedAccounts<AM>,
                            ) -> std::result::Result<Self::Packed, #sdk_error> {
                                let __seeds: &[&[u8]] = &[#(#bump_seed_refs),*];
                                let (_, __bump) = solana_pubkey::Pubkey::find_program_address(
                                    __seeds,
                                    &solana_pubkey::Pubkey::from(crate::LIGHT_CPI_SIGNER.program_id),
                                );
                                Ok(#packed_seeds_name {
                                    #(#pack_stmts,)*
                                    bump: __bump,
                                })
                            }
                        }
                    }
                };

                let unpack_impl = if backend.is_pinocchio() {
                    quote! {
                        impl<AI: #account_crate::light_account_checks::AccountInfoTrait> #account_crate::Unpack<AI> for #packed_seeds_name {
                            type Unpacked = #seeds_name;

                            fn unpack(
                                &self,
                                remaining_accounts: &[AI],
                            ) -> std::result::Result<Self::Unpacked, #sdk_error> {
                                #(#unpack_resolve_stmts)*
                                Ok(#seeds_name {
                                    #(#unpack_field_assigns,)*
                                })
                            }
                        }
                    }
                } else {
                    quote! {
                        impl<AI: #account_crate::AccountInfoTrait> #account_crate::Unpack<AI> for #packed_seeds_name {
                            type Unpacked = #seeds_name;

                            fn unpack(
                                &self,
                                remaining_accounts: &[AI],
                            ) -> std::result::Result<Self::Unpacked, #sdk_error> {
                                #(#unpack_resolve_stmts)*
                                Ok(#seeds_name {
                                    #(#unpack_field_assigns,)*
                                })
                            }
                        }
                    }
                };

                quote! {
                    #seeds_struct

                    #[derive(#serialize_derive, #deserialize_derive, Clone, Debug)]
                    pub struct #packed_seeds_name {
                        #(#packed_fields,)*
                        pub bump: u8,
                    }

                    #pack_impl

                    #unpack_impl
                }
            })
            .collect();

        quote! { #(#structs)* }
    }

    // =========================================================================
    // TOKEN VARIANT TRAIT IMPLS
    // =========================================================================

    /// Generate `UnpackedTokenSeeds<N>` and `PackedTokenSeeds<N>` impls
    /// on the local seed structs using the specified backend.
    fn generate_token_variant_trait_impls_with_backend(
        &self,
        backend: &dyn CodegenBackend,
    ) -> TokenStream {
        let account_crate = backend.account_crate();
        let sdk_error = backend.sdk_error_type();
        let account_info_trait = backend.account_info_trait();

        let impls: Vec<_> = self
            .token_seeds
            .iter()
            .map(|spec| {
                let seeds_name = format_ident!("{}Seeds", spec.variant);
                let packed_seeds_name = format_ident!("Packed{}Seeds", spec.variant);

                // seed_count = number of seeds + 1 for bump
                let seed_count = spec.seeds.len() + 1;

                // --- Unpacked seed refs (self is the seeds struct directly) ---
                let unpacked_seed_ref_items: Vec<_> = spec
                    .seeds
                    .iter()
                    .map(seed_to_unpacked_ref)
                    .collect();

                // seed_vec items (owned Vec<u8> for each seed, self is seeds struct)
                let seed_vec_items: Vec<_> = spec
                    .seeds
                    .iter()
                    .map(|seed| {
                        match seed {
                            SeedElement::Literal(lit) => {
                                let value = lit.value();
                                quote! { #value.as_bytes().to_vec() }
                            }
                            SeedElement::Expression(expr) => {
                                if let Some(field_name) = extract_ctx_field_from_expr(expr) {
                                    quote! { self.#field_name.as_ref().to_vec() }
                                } else {
                                    if let syn::Expr::Lit(lit_expr) = &**expr {
                                        if let syn::Lit::ByteStr(byte_str) = &lit_expr.lit {
                                            let bytes = byte_str.value();
                                            return quote! { vec![#(#bytes),*] };
                                        }
                                    }
                                    if let syn::Expr::Path(path_expr) = &**expr {
                                        if path_expr.qself.is_none() {
                                            if let Some(last_seg) = path_expr.path.segments.last() {
                                                if crate::light_pdas::shared_utils::is_constant_identifier(&last_seg.ident.to_string()) {
                                                    let path = &path_expr.path;
                                                    return quote! { { let __seed: &[u8] = #path.as_ref(); __seed.to_vec() } };
                                                }
                                            }
                                        }
                                    }
                                    quote! { { let __seed: &[u8] = (#expr).as_ref(); __seed.to_vec() } }
                                }
                            }
                        }
                    })
                    .collect();

                // --- Packed seed refs (self is the packed seeds struct directly) ---
                let packed_seed_ref_items: Vec<_> = spec
                    .seeds
                    .iter()
                    .map(|s| seed_to_packed_ref_with_crate(s, &account_crate))
                    .collect();

                // --- Owner derivation from owner_seeds (constants only) ---
                let owner_derivation = if let Some(owner_seeds) = &spec.owner_seeds {
                    let owner_seed_refs: Vec<_> = owner_seeds
                        .iter()
                        .map(|seed| {
                            match seed {
                                SeedElement::Literal(lit) => {
                                    let value = lit.value();
                                    quote! { #value.as_bytes() }
                                }
                                SeedElement::Expression(expr) => {
                                    // For constants like AUTH_SEED.as_bytes()
                                    quote! { { let __seed: &[u8] = (#expr).as_ref(); __seed } }
                                }
                            }
                        })
                        .collect();

                    if backend.is_pinocchio() {
                        quote! {
                            let (__owner, _) = #account_crate::solana_pubkey::Pubkey::find_program_address(
                                &[#(#owner_seed_refs),*],
                                &#account_crate::solana_pubkey::Pubkey::from(crate::LIGHT_CPI_SIGNER.program_id),
                            );
                            __owner.to_bytes()
                        }
                    } else {
                        quote! {
                            let (__owner, _) = solana_pubkey::Pubkey::find_program_address(
                                &[#(#owner_seed_refs),*],
                                &solana_pubkey::Pubkey::from(crate::LIGHT_CPI_SIGNER.program_id),
                            );
                            __owner.to_bytes()
                        }
                    }
                } else {
                    // No owner_seeds - return default (shouldn't happen for token accounts)
                    quote! { [0u8; 32] }
                };

                quote! {
                    impl #account_crate::UnpackedTokenSeeds<#seed_count>
                        for #seeds_name
                    {
                        type Packed = #packed_seeds_name;

                        const PROGRAM_ID: [u8; 32] = crate::LIGHT_CPI_SIGNER.program_id;

                        fn seed_vec(&self) -> Vec<Vec<u8>> {
                            vec![#(#seed_vec_items),*]
                        }

                        fn seed_refs_with_bump<'a>(&'a self, bump_storage: &'a [u8; 1]) -> [&'a [u8]; #seed_count] {
                            [#(#unpacked_seed_ref_items,)* bump_storage]
                        }
                    }

                    impl #account_crate::PackedTokenSeeds<#seed_count>
                        for #packed_seeds_name
                    {
                        type Unpacked = #seeds_name;

                        fn bump(&self) -> u8 {
                            self.bump
                        }

                        fn unpack_seeds<AI: #account_info_trait>(
                            &self,
                            accounts: &[AI],
                        ) -> std::result::Result<Self::Unpacked, #sdk_error> {
                            <Self as #account_crate::Unpack<AI>>::unpack(self, accounts)
                        }

                        fn seed_refs_with_bump<'a, AI: #account_info_trait>(
                            &'a self,
                            accounts: &'a [AI],
                            bump_storage: &'a [u8; 1],
                        ) -> std::result::Result<[&'a [u8]; #seed_count], #sdk_error> {
                            Ok([#(#packed_seed_ref_items,)* bump_storage])
                        }

                        fn derive_owner(&self) -> [u8; 32] {
                            #owner_derivation
                        }
                    }
                }
            })
            .collect();

        quote! { #(#impls)* }
    }

    // =========================================================================
    // ENUM GENERATION
    // =========================================================================

    /// Generate the unpacked `LightAccountVariant` enum using the specified backend.
    fn generate_unpacked_enum_with_backend(&self, backend: &dyn CodegenBackend) -> TokenStream {
        let account_crate = backend.account_crate();
        let serialize_derive = backend.serialize_derive();
        let deserialize_derive = backend.deserialize_derive();

        let pda_variants: Vec<_> = self
            .pda_ctx_seeds
            .iter()
            .map(|info| {
                let variant_name = &info.variant_name;
                let seeds_type = format_ident!("{}Seeds", variant_name);
                let inner_type = qualify_type_with_crate(&info.inner_type);
                quote! { #variant_name { seeds: #seeds_type, data: #inner_type } }
            })
            .collect();

        let token_variants: Vec<_> = self
            .token_seeds
            .iter()
            .map(|spec| {
                let variant_name = &spec.variant;
                let seeds_name = format_ident!("{}Seeds", variant_name);
                quote! {
                    #variant_name(#account_crate::token::TokenDataWithSeeds<#seeds_name>)
                }
            })
            .collect();

        if backend.is_pinocchio() {
            quote! {
                #[derive(#serialize_derive, #deserialize_derive, Clone, Debug)]
                pub enum LightAccountVariant {
                    #(#pda_variants,)*
                    #(#token_variants,)*
                }
            }
        } else {
            quote! {
                /// Program-wide unpacked variant enum collecting all per-field variants.
                #[derive(#serialize_derive, #deserialize_derive, Clone, Debug)]
                pub enum LightAccountVariant {
                    #(#pda_variants,)*
                    #(#token_variants,)*
                }
            }
        }
    }

    /// Generate the packed `PackedLightAccountVariant` enum using the specified backend.
    fn generate_packed_enum_with_backend(&self, backend: &dyn CodegenBackend) -> TokenStream {
        let account_crate = backend.account_crate();
        let serialize_derive = backend.serialize_derive();
        let deserialize_derive = backend.deserialize_derive();

        let pda_variants: Vec<_> =
            self.pda_ctx_seeds
                .iter()
                .map(|info| {
                    let variant_name = &info.variant_name;
                    let packed_seeds_type = format_ident!("Packed{}Seeds", variant_name);
                    let inner_type = &info.inner_type;
                    let packed_data_type =
                        crate::light_pdas::shared_utils::make_packed_type(inner_type)
                            .unwrap_or_else(|| {
                                let type_str = quote!(#inner_type).to_string().replace(' ', "");
                                let packed_name = format_ident!("Packed{}", type_str);
                                syn::parse_quote!(#packed_name)
                            });
                    quote! { #variant_name { seeds: #packed_seeds_type, data: #packed_data_type } }
                })
                .collect();

        let token_variants: Vec<_> = self
            .token_seeds
            .iter()
            .map(|spec| {
                let variant_name = &spec.variant;
                let packed_seeds_name = format_ident!("Packed{}Seeds", variant_name);
                quote! {
                    #variant_name(#account_crate::token::TokenDataWithPackedSeeds<#packed_seeds_name>)
                }
            })
            .collect();

        if backend.is_pinocchio() {
            quote! {
                #[derive(#serialize_derive, #deserialize_derive, Clone, Debug)]
                pub enum PackedLightAccountVariant {
                    #(#pda_variants,)*
                    #(#token_variants,)*
                }
            }
        } else {
            quote! {
                /// Program-wide packed variant enum for efficient serialization.
                #[derive(#serialize_derive, #deserialize_derive, Clone, Debug)]
                pub enum PackedLightAccountVariant {
                    #(#pda_variants,)*
                    #(#token_variants,)*
                }
            }
        }
    }

    // =========================================================================
    // DECOMPRESS VARIANT IMPL
    // =========================================================================

    /// Generate `impl DecompressVariant for PackedLightAccountVariant` using the specified backend.
    fn generate_decompress_variant_impl_with_backend(
        &self,
        backend: &dyn CodegenBackend,
    ) -> TokenStream {
        let account_crate = backend.account_crate();
        let account_info_type = backend.account_info_type();
        let sdk_error = backend.sdk_error_type();

        let pda_arms: Vec<_> = self
            .pda_ctx_seeds
            .iter()
            .map(|info| {
                let variant_name = &info.variant_name;
                let packed_variant_type = format_ident!("Packed{}Variant", variant_name);
                let seed_count = info.seed_count;

                quote! {
                    Self::#variant_name { seeds, data } => {
                        let packed_data = #packed_variant_type { seeds: seeds.clone(), data: data.clone() };
                        #account_crate::prepare_account_for_decompression::<#seed_count, #packed_variant_type, #account_info_type>(
                            &packed_data,
                            tree_info,
                            output_queue_index,
                            pda_account,
                            ctx,
                        )
                    }
                }
            })
            .collect();

        let token_arms: Vec<_> = self
            .token_seeds
            .iter()
            .map(|spec| {
                let variant_name = &spec.variant;
                let packed_seeds_name = format_ident!("Packed{}Seeds", variant_name);
                let seed_count = spec.seeds.len() + 1;

                quote! {
                    Self::#variant_name(packed_data) => {
                        #account_crate::token::prepare_token_account_for_decompression::<
                            #seed_count,
                            #account_crate::token::TokenDataWithPackedSeeds<#packed_seeds_name>,
                            #account_info_type,
                        >(
                            packed_data,
                            tree_info,
                            output_queue_index,
                            pda_account,
                            ctx,
                        )
                    }
                }
            })
            .collect();

        if backend.is_pinocchio() {
            quote! {
                impl #account_crate::DecompressVariant<#account_info_type> for PackedLightAccountVariant {
                    fn decompress(
                        &self,
                        tree_info: &#account_crate::PackedStateTreeInfo,
                        pda_account: &#account_info_type,
                        ctx: &mut #account_crate::DecompressCtx<'_>,
                    ) -> std::result::Result<(), #sdk_error> {
                        let output_queue_index = ctx.output_queue_index;
                        match self {
                            #(#pda_arms)*
                            #(#token_arms)*
                        }
                    }
                }
            }
        } else {
            quote! {
                impl<'info> #account_crate::DecompressVariant<#account_crate::AccountInfo<'info>> for PackedLightAccountVariant {
                    fn decompress(
                        &self,
                        tree_info: &#account_crate::PackedStateTreeInfo,
                        pda_account: &#account_crate::AccountInfo<'info>,
                        ctx: &mut #account_crate::DecompressCtx<'_, 'info>,
                    ) -> std::result::Result<(), #sdk_error> {
                        let output_queue_index = ctx.output_queue_index;
                        match self {
                            #(#pda_arms)*
                            #(#token_arms)*
                        }
                    }
                }
            }
        }
    }

    // =========================================================================
    // PACK IMPL
    // =========================================================================

    /// Generate `impl Pack for LightAccountVariant` using the specified backend.
    fn generate_pack_impl_with_backend(&self, backend: &dyn CodegenBackend) -> TokenStream {
        let account_crate = backend.account_crate();
        let sdk_error = backend.sdk_error_type();
        let packed_accounts_type = backend.packed_accounts_type();
        let account_meta_type = backend.account_meta_type();

        let pda_arms: Vec<_> = self
            .pda_ctx_seeds
            .iter()
            .map(|info| {
                let variant_name = &info.variant_name;
                let variant_struct_name = format_ident!("{}Variant", variant_name);

                quote! {
                    Self::#variant_name { seeds, data } => {
                        let variant = #variant_struct_name { seeds: seeds.clone(), data: data.clone() };
                        let packed = #account_crate::Pack::pack(&variant, accounts)?;
                        Ok(PackedLightAccountVariant::#variant_name { seeds: packed.seeds, data: packed.data })
                    }
                }
            })
            .collect();

        let token_arms: Vec<_> = self
            .token_seeds
            .iter()
            .map(|spec| {
                let variant_name = &spec.variant;
                quote! {
                    Self::#variant_name(data) => {
                        let packed = #account_crate::Pack::pack(data, accounts)?;
                        Ok(PackedLightAccountVariant::#variant_name(packed))
                    }
                }
            })
            .collect();

        if backend.is_pinocchio() {
            quote! {
                #[cfg(not(target_os = "solana"))]
                impl #account_crate::Pack<#account_meta_type> for LightAccountVariant {
                    type Packed = PackedLightAccountVariant;

                    fn pack(
                        &self,
                        accounts: &mut #packed_accounts_type,
                    ) -> std::result::Result<Self::Packed, #sdk_error> {
                        match self {
                            #(#pda_arms)*
                            #(#token_arms)*
                        }
                    }
                }
            }
        } else {
            quote! {
                // Pack trait is only available off-chain (client-side)
                #[cfg(not(target_os = "solana"))]
                impl<AM: #account_meta_type> #account_crate::Pack<AM> for LightAccountVariant {
                    type Packed = PackedLightAccountVariant;

                    fn pack(
                        &self,
                        accounts: &mut #packed_accounts_type,
                    ) -> std::result::Result<Self::Packed, #sdk_error> {
                        match self {
                            #(#pda_arms)*
                            #(#token_arms)*
                        }
                    }
                }
            }
        }
    }
}

/// Info about ctx.* seeds for a PDA type.
#[derive(Clone, Debug)]
pub struct PdaCtxSeedInfo {
    /// The variant name (derived from field name, e.g., "Record" from field "record")
    pub variant_name: Ident,
    /// The inner type (e.g., crate::state::SinglePubkeyRecord - preserves full path)
    pub inner_type: Type,
    /// Field names from ctx.accounts.XXX references in seeds
    pub ctx_seed_fields: Vec<Ident>,
    /// Field names that exist on the state struct (for filtering data.* seeds)
    pub state_field_names: std::collections::HashSet<String>,
    /// Params-only seed fields (name, type, has_conversion) - seeds from params.* that don't exist on state
    /// The bool indicates whether a conversion method like to_le_bytes() is applied
    pub params_only_seed_fields: Vec<(Ident, Type, bool)>,
    /// Total number of seeds + 1 for bump. This is used as the const generic N
    /// for PackedLightAccountVariant<N>.
    pub seed_count: usize,
}

impl PdaCtxSeedInfo {
    pub fn with_state_fields(
        variant_name: Ident,
        inner_type: Type,
        ctx_seed_fields: Vec<Ident>,
        state_field_names: std::collections::HashSet<String>,
        params_only_seed_fields: Vec<(Ident, Type, bool)>,
        seed_count: usize,
    ) -> Self {
        Self {
            variant_name,
            inner_type,
            ctx_seed_fields,
            state_field_names,
            params_only_seed_fields,
            seed_count,
        }
    }
}

// =============================================================================
// HELPER FUNCTIONS
// =============================================================================

/// Extract ctx.* field names from seed elements (both token seeds and owner seeds).
///
/// Uses the visitor-based FieldExtractor for clean AST traversal.
pub fn extract_ctx_fields_from_token_spec(spec: &TokenSeedSpec) -> Vec<Ident> {
    const EXCLUDED: &[&str] = &[
        "fee_payer",
        "rent_sponsor",
        "config",
        "compression_authority",
    ];

    let mut all_fields = Vec::new();
    let mut seen = std::collections::HashSet::new();

    for seed in spec.seeds.iter().chain(spec.owner_seeds.iter().flatten()) {
        if let SeedElement::Expression(expr) = seed {
            // Extract fields from this expression using the visitor
            let fields = super::visitors::FieldExtractor::ctx_fields(EXCLUDED).extract(expr);
            // Deduplicate across seeds
            for field in fields {
                let name = field.to_string();
                if seen.insert(name) {
                    all_fields.push(field);
                }
            }
        }
    }

    all_fields
}

/// Extract a single ctx field name from an expression.
/// Returns `Some(field_name)` for expressions like `ctx.accounts.mint.key()` or `ctx.mint.key()`.
fn extract_ctx_field_from_expr(expr: &syn::Expr) -> Option<Ident> {
    let fields = super::visitors::FieldExtractor::ctx_fields(&[
        "fee_payer",
        "rent_sponsor",
        "config",
        "compression_authority",
    ])
    .extract(expr);
    fields.into_iter().next()
}

/// Generate a seed ref expression for the UNPACKED variant (uses `self.seeds.field.as_ref()`).
fn seed_to_unpacked_ref(seed: &SeedElement) -> TokenStream {
    match seed {
        SeedElement::Literal(lit) => {
            let value = lit.value();
            quote! { #value.as_bytes() }
        }
        SeedElement::Expression(expr) => {
            if let syn::Expr::Lit(lit_expr) = &**expr {
                if let syn::Lit::ByteStr(byte_str) = &lit_expr.lit {
                    let bytes = byte_str.value();
                    return quote! { &[#(#bytes),*] };
                }
            }
            if let syn::Expr::Path(path_expr) = &**expr {
                if path_expr.qself.is_none() {
                    if let Some(last_seg) = path_expr.path.segments.last() {
                        if crate::light_pdas::shared_utils::is_constant_identifier(
                            &last_seg.ident.to_string(),
                        ) {
                            let path = &path_expr.path;
                            return quote! { { let __seed: &[u8] = #path.as_ref(); __seed } };
                        }
                    }
                }
            }
            if let Some(field_name) = extract_ctx_field_from_expr(expr) {
                return quote! { self.#field_name.as_ref() };
            }
            quote! { { let __seed: &[u8] = (#expr).as_ref(); __seed } }
        }
    }
}

/// Generate a seed ref expression for the PACKED variant (uses `accounts[idx].key.as_ref()`).
///
/// `account_crate` selects the error path: `light_account` for Anchor, `light_account_pinocchio` for pinocchio.
fn seed_to_packed_ref_with_crate(seed: &SeedElement, account_crate: &TokenStream) -> TokenStream {
    match seed {
        SeedElement::Literal(lit) => {
            let value = lit.value();
            quote! { #value.as_bytes() }
        }
        SeedElement::Expression(expr) => {
            if let syn::Expr::Lit(lit_expr) = &**expr {
                if let syn::Lit::ByteStr(byte_str) = &lit_expr.lit {
                    let bytes = byte_str.value();
                    return quote! { &[#(#bytes),*] };
                }
            }
            if let syn::Expr::Path(path_expr) = &**expr {
                if path_expr.qself.is_none() {
                    if let Some(last_seg) = path_expr.path.segments.last() {
                        if crate::light_pdas::shared_utils::is_constant_identifier(
                            &last_seg.ident.to_string(),
                        ) {
                            let path = &path_expr.path;
                            return quote! { { let __seed: &[u8] = #path.as_ref(); __seed } };
                        }
                    }
                }
            }
            if let Some(field_name) = extract_ctx_field_from_expr(expr) {
                let idx_field = format_ident!("{}_idx", field_name);
                return quote! {
                    accounts
                        .get(self.#idx_field as usize)
                        .ok_or(#account_crate::LightSdkTypesError::InvalidInstructionData)?
                        .key_ref()
                };
            }
            quote! { { let __seed: &[u8] = (#expr).as_ref(); __seed } }
        }
    }
}