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
//! Decompress code generation.
//!
//! This module provides the `DecompressBuilder` for generating decompress instruction
//! code including context implementation, processor, entrypoint, accounts struct,
//! and PDA seed provider implementations.

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

use super::{
    expr_traversal::transform_expr_for_ctx_seeds,
    parsing::{SeedElement, TokenSeedSpec},
    seed_utils::ctx_fields_to_set,
    variant_enum::PdaCtxSeedInfo,
};
use crate::light_pdas::{
    backend::CodegenBackend,
    shared_utils::{is_constant_identifier, qualify_type_with_crate},
};

// =============================================================================
// DECOMPRESS BUILDER
// =============================================================================

/// Builder for generating decompress instruction code.
///
/// Encapsulates all data needed to generate decompress-related code:
/// context implementation, processor function, instruction entrypoint,
/// accounts struct, and PDA seed provider implementations.
pub(super) struct DecompressBuilder {
    /// PDA context seed information for each variant.
    pda_ctx_seeds: Vec<PdaCtxSeedInfo>,
    /// PDA seed specifications.
    pda_seeds: Option<Vec<TokenSeedSpec>>,
    /// Whether the program has token accounts (tokens/ATAs/mints).
    /// When true, the generated processor calls the full decompress function
    /// that handles both PDA and token accounts.
    has_tokens: bool,
}

impl DecompressBuilder {
    /// Create a new DecompressBuilder with all required configuration.
    ///
    /// # Arguments
    /// * `pda_ctx_seeds` - PDA context seed information for each variant
    /// * `pda_seeds` - PDA seed specifications
    /// * `has_tokens` - Whether the program has token accounts
    pub fn new(
        pda_ctx_seeds: Vec<PdaCtxSeedInfo>,
        pda_seeds: Option<Vec<TokenSeedSpec>>,
        has_tokens: bool,
    ) -> Self {
        Self {
            pda_ctx_seeds,
            pda_seeds,
            has_tokens,
        }
    }

    // -------------------------------------------------------------------------
    // Code Generation Methods
    // -------------------------------------------------------------------------

    /// Generate the processor function for decompress accounts (v2 interface).
    ///
    /// For programs with token accounts, calls the full processor that handles
    /// both PDA and token decompression. For PDA-only programs, calls the
    /// simpler PDA-only processor.
    pub fn generate_processor(&self) -> Result<syn::ItemFn> {
        if self.has_tokens {
            Ok(syn::parse_quote! {
                #[inline(never)]
                pub fn process_decompress_accounts_idempotent<'info>(
                    remaining_accounts: &[solana_account_info::AccountInfo<'info>],
                    params: &light_account::DecompressIdempotentParams<PackedLightAccountVariant>,
                ) -> Result<()> {
                    use solana_program::{clock::Clock, sysvar::Sysvar};
                    let current_slot = Clock::get()?.slot;
                    light_account::process_decompress_accounts_idempotent::<_, PackedLightAccountVariant>(
                        remaining_accounts,
                        params,
                        LIGHT_CPI_SIGNER,
                        &crate::LIGHT_CPI_SIGNER.program_id,
                        current_slot,
                    )
                    .map_err(|e| anchor_lang::error::Error::from(solana_program_error::ProgramError::from(e)))
                }
            })
        } else {
            Ok(syn::parse_quote! {
                #[inline(never)]
                pub fn process_decompress_accounts_idempotent<'info>(
                    remaining_accounts: &[solana_account_info::AccountInfo<'info>],
                    params: &light_account::DecompressIdempotentParams<PackedLightAccountVariant>,
                ) -> Result<()> {
                    use solana_program::{clock::Clock, sysvar::Sysvar};
                    let current_slot = Clock::get()?.slot;
                    light_account::process_decompress_pda_accounts_idempotent::<_, PackedLightAccountVariant>(
                        remaining_accounts,
                        params,
                        LIGHT_CPI_SIGNER,
                        &crate::LIGHT_CPI_SIGNER.program_id,
                        current_slot,
                    )
                    .map_err(|e| anchor_lang::error::Error::from(solana_program_error::ProgramError::from(e)))
                }
            })
        }
    }

    /// Generate the decompress instruction entrypoint function (v2 interface).
    ///
    /// Accepts typed `DecompressIdempotentParams` directly.
    /// Anchor deserializes the params from instruction data.
    pub fn generate_entrypoint(&self) -> Result<syn::ItemFn> {
        Ok(syn::parse_quote! {
            #[inline(never)]
            pub fn decompress_accounts_idempotent<'info>(
                ctx: Context<'_, '_, '_, 'info, DecompressAccountsIdempotent<'info>>,
                params: light_account::DecompressIdempotentParams<PackedLightAccountVariant>,
            ) -> Result<()> {
                __processor_functions::process_decompress_accounts_idempotent(
                    ctx.remaining_accounts,
                    &params,
                )
            }
        })
    }

    /// Generate the decompress accounts struct and manual Anchor trait impls.
    ///
    /// Uses PhantomData for the `<'info>` lifetime so Anchor's CPI codegen
    /// can reference `DecompressAccountsIdempotent<'info>`.
    /// All accounts are passed via remaining_accounts.
    pub fn generate_accounts_struct(&self) -> Result<syn::ItemStruct> {
        Ok(syn::parse_quote! {
            pub struct DecompressAccountsIdempotent<'info>(
                std::marker::PhantomData<&'info ()>,
            );
        })
    }

    /// Generate manual Anchor trait implementations for the empty accounts struct.
    pub fn generate_accounts_trait_impls(&self) -> Result<TokenStream> {
        Ok(quote! {
            impl<'info> anchor_lang::Accounts<'info, DecompressAccountsIdempotentBumps>
                for DecompressAccountsIdempotent<'info>
            {
                fn try_accounts(
                    _program_id: &anchor_lang::solana_program::pubkey::Pubkey,
                    _accounts: &mut &'info [anchor_lang::solana_program::account_info::AccountInfo<'info>],
                    _ix_data: &[u8],
                    _bumps: &mut DecompressAccountsIdempotentBumps,
                    _reallocs: &mut std::collections::BTreeSet<anchor_lang::solana_program::pubkey::Pubkey>,
                ) -> anchor_lang::Result<Self> {
                    Ok(DecompressAccountsIdempotent(std::marker::PhantomData))
                }
            }

            #[derive(Debug, Default)]
            pub struct DecompressAccountsIdempotentBumps {}

            impl<'info> anchor_lang::Bumps for DecompressAccountsIdempotent<'info> {
                type Bumps = DecompressAccountsIdempotentBumps;
            }

            impl<'info> anchor_lang::ToAccountInfos<'info> for DecompressAccountsIdempotent<'info> {
                fn to_account_infos(
                    &self,
                ) -> Vec<anchor_lang::solana_program::account_info::AccountInfo<'info>> {
                    Vec::new()
                }
            }

            impl<'info> anchor_lang::ToAccountMetas for DecompressAccountsIdempotent<'info> {
                fn to_account_metas(
                    &self,
                    _is_signer: Option<bool>,
                ) -> Vec<anchor_lang::solana_program::instruction::AccountMeta> {
                    Vec::new()
                }
            }

            impl<'info> anchor_lang::AccountsExit<'info> for DecompressAccountsIdempotent<'info> {
                fn exit(
                    &self,
                    _program_id: &anchor_lang::solana_program::pubkey::Pubkey,
                ) -> anchor_lang::Result<()> {
                    Ok(())
                }
            }

            #[cfg(feature = "idl-build")]
            impl<'info> DecompressAccountsIdempotent<'info> {
                pub fn __anchor_private_gen_idl_accounts(
                    _accounts: &mut std::collections::BTreeMap<
                        String,
                        anchor_lang::idl::types::IdlAccount,
                    >,
                    _types: &mut std::collections::BTreeMap<
                        String,
                        anchor_lang::idl::types::IdlTypeDef,
                    >,
                ) -> Vec<anchor_lang::idl::types::IdlInstructionAccountItem> {
                    Vec::new()
                }
            }

            pub(crate) mod __client_accounts_decompress_accounts_idempotent {
                use super::*;
                pub struct DecompressAccountsIdempotent<'info>(
                    std::marker::PhantomData<&'info ()>,
                );
                impl<'info> borsh::ser::BorshSerialize for DecompressAccountsIdempotent<'info> {
                    fn serialize<W: borsh::maybestd::io::Write>(
                        &self,
                        _writer: &mut W,
                    ) -> ::core::result::Result<(), borsh::maybestd::io::Error> {
                        Ok(())
                    }
                }
                impl<'info> anchor_lang::ToAccountMetas for DecompressAccountsIdempotent<'info> {
                    fn to_account_metas(
                        &self,
                        _is_signer: Option<bool>,
                    ) -> Vec<anchor_lang::solana_program::instruction::AccountMeta> {
                        Vec::new()
                    }
                }
            }

            pub(crate) mod __cpi_client_accounts_decompress_accounts_idempotent {
                use super::*;
                pub struct DecompressAccountsIdempotent<'info>(
                    std::marker::PhantomData<&'info ()>,
                );
                impl<'info> anchor_lang::ToAccountMetas for DecompressAccountsIdempotent<'info> {
                    fn to_account_metas(
                        &self,
                        _is_signer: Option<bool>,
                    ) -> Vec<anchor_lang::solana_program::instruction::AccountMeta> {
                        Vec::new()
                    }
                }
                impl<'info> anchor_lang::ToAccountInfos<'info> for DecompressAccountsIdempotent<'info> {
                    fn to_account_infos(
                        &self,
                    ) -> Vec<anchor_lang::solana_program::account_info::AccountInfo<'info>> {
                        Vec::new()
                    }
                }
            }
        })
    }

    /// Generate PDA seed provider implementations using the specified backend.
    pub fn generate_seed_provider_impls_with_backend(
        &self,
        backend: &dyn CodegenBackend,
    ) -> Result<Vec<TokenStream>> {
        // For mint-only or token-only programs, there are no PDA seeds - return empty Vec
        let pda_seed_specs = match self.pda_seeds.as_ref() {
            Some(specs) if !specs.is_empty() => specs,
            _ => {
                // Fail fast if pda_ctx_seeds has variants but pda_seeds is missing
                if !self.pda_ctx_seeds.is_empty() {
                    let variant_names: Vec<_> = self
                        .pda_ctx_seeds
                        .iter()
                        .map(|v| v.variant_name.to_string())
                        .collect();
                    return Err(syn::Error::new(
                        proc_macro2::Span::call_site(),
                        format!(
                            "generate_seed_provider_impls: pda_seeds is None/empty but \
                             pda_ctx_seeds contains {} variant(s): [{}]. \
                             Each pda_ctx_seeds variant requires a corresponding PDA seed \
                             specification in pda_seeds.",
                            self.pda_ctx_seeds.len(),
                            variant_names.join(", ")
                        ),
                    ));
                }
                return Ok(Vec::new());
            }
        };

        let mut results = Vec::with_capacity(self.pda_ctx_seeds.len());
        let account_crate = backend.account_crate();

        for ctx_info in self.pda_ctx_seeds.iter() {
            let variant_str = ctx_info.variant_name.to_string();
            let spec = pda_seed_specs
                .iter()
                .find(|s| s.variant == variant_str)
                .ok_or_else(|| {
                    super::parsing::macro_error!(
                        &ctx_info.variant_name,
                        "No seed specification for variant '{}'",
                        variant_str
                    )
                })?;

            let ctx_seeds_struct_name = format_ident!("{}CtxSeeds", ctx_info.variant_name);
            let inner_type = qualify_type_with_crate(&ctx_info.inner_type);
            let ctx_fields = &ctx_info.ctx_seed_fields;
            let ctx_fields_decl: Vec<_> = ctx_fields
                .iter()
                .map(|field| {
                    if backend.is_pinocchio() {
                        quote! { pub #field: [u8; 32] }
                    } else {
                        quote! { pub #field: solana_pubkey::Pubkey }
                    }
                })
                .collect();

            let ctx_seeds_struct = if ctx_fields.is_empty() {
                quote! {
                    #[derive(Default)]
                    pub struct #ctx_seeds_struct_name;
                }
            } else {
                quote! {
                    #[derive(Default)]
                    pub struct #ctx_seeds_struct_name {
                        #(#ctx_fields_decl),*
                    }
                }
            };

            let params_only_fields = &ctx_info.params_only_seed_fields;
            let seed_derivation = generate_pda_seed_derivation_for_trait_with_ctx_seeds(
                spec,
                ctx_fields,
                &ctx_info.state_field_names,
                params_only_fields,
                backend.is_pinocchio(),
            )?;

            let has_params_only = !params_only_fields.is_empty();
            let seed_params_impl = if has_params_only {
                quote! {
                    #ctx_seeds_struct

                    impl #account_crate::PdaSeedDerivation<#ctx_seeds_struct_name, SeedParams> for #inner_type {
                        fn derive_pda_seeds_with_accounts(
                            &self,
                            program_id: &[u8; 32],
                            ctx_seeds: &#ctx_seeds_struct_name,
                            seed_params: &SeedParams,
                        ) -> std::result::Result<(Vec<Vec<u8>>, [u8; 32]), #account_crate::LightSdkTypesError> {
                            #seed_derivation
                        }
                    }
                }
            } else {
                quote! {
                    #ctx_seeds_struct

                    impl #account_crate::PdaSeedDerivation<#ctx_seeds_struct_name, SeedParams> for #inner_type {
                        fn derive_pda_seeds_with_accounts(
                            &self,
                            program_id: &[u8; 32],
                            ctx_seeds: &#ctx_seeds_struct_name,
                            _seed_params: &SeedParams,
                        ) -> std::result::Result<(Vec<Vec<u8>>, [u8; 32]), #account_crate::LightSdkTypesError> {
                            #seed_derivation
                        }
                    }
                }
            };
            results.push(seed_params_impl);
        }

        Ok(results)
    }

    // -------------------------------------------------------------------------
    // Backend-Aware Code Generation Methods
    // -------------------------------------------------------------------------

    /// Generate `process_decompress` as an enum associated function using the specified backend.
    pub fn generate_enum_process_decompress_with_backend(
        &self,
        enum_name: &syn::Ident,
        backend: &dyn CodegenBackend,
    ) -> Result<TokenStream> {
        let account_crate = backend.account_crate();
        let program_error = backend.program_error_type();

        let processor_fn = if self.has_tokens {
            quote! { process_decompress_accounts_idempotent }
        } else {
            quote! { process_decompress_pda_accounts_idempotent }
        };

        if backend.is_pinocchio() {
            Ok(quote! {
                impl #enum_name {
                    pub fn process_decompress(
                        accounts: &[pinocchio::account_info::AccountInfo],
                        instruction_data: &[u8],
                    ) -> std::result::Result<(), #program_error> {
                        use borsh::BorshDeserialize;
                        use pinocchio::sysvars::Sysvar;
                        let params = #account_crate::DecompressIdempotentParams::<PackedLightAccountVariant>::try_from_slice(instruction_data)
                            .map_err(|_| #program_error::InvalidInstructionData)?;
                        let current_slot = pinocchio::sysvars::clock::Clock::get()
                            .map_err(|_| #program_error::UnsupportedSysvar)?
                            .slot;
                        #account_crate::#processor_fn::<_, PackedLightAccountVariant>(
                            accounts,
                            &params,
                            crate::LIGHT_CPI_SIGNER,
                            &crate::LIGHT_CPI_SIGNER.program_id,
                            current_slot,
                        )
                        .map_err(|e| #program_error::Custom(u32::from(e)))
                    }
                }
            })
        } else {
            // Anchor version doesn't generate process_decompress on enum - uses separate processor
            Ok(quote! {})
        }
    }

    /// Generate decompress dispatch as an associated function on the enum using the specified backend.
    pub fn generate_enum_decompress_dispatch_with_backend(
        &self,
        enum_name: &syn::Ident,
        backend: &dyn CodegenBackend,
    ) -> Result<TokenStream> {
        let account_crate = backend.account_crate();
        let sdk_error = backend.sdk_error_type();

        let processor_fn = if self.has_tokens {
            quote! { process_decompress_accounts_idempotent }
        } else {
            quote! { process_decompress_pda_accounts_idempotent }
        };

        if backend.is_pinocchio() {
            // Pinocchio uses generate_enum_process_decompress instead
            Ok(quote! {})
        } else {
            Ok(quote! {
                impl #enum_name {
                    pub fn decompress_dispatch<'info>(
                        remaining_accounts: &[solana_account_info::AccountInfo<'info>],
                        params: &#account_crate::DecompressIdempotentParams<PackedLightAccountVariant>,
                        cpi_signer: #account_crate::CpiSigner,
                        program_id: &[u8; 32],
                        current_slot: u64,
                    ) -> std::result::Result<(), #sdk_error> {
                        #account_crate::#processor_fn::<_, PackedLightAccountVariant>(
                            remaining_accounts,
                            params,
                            cpi_signer,
                            program_id,
                            current_slot,
                        )
                    }
                }
            })
        }
    }
}

// =============================================================================
// PDA SEED DERIVATION (Internal helpers used by DecompressBuilder)
// =============================================================================

/// Generate PDA seed derivation that uses CtxSeeds struct instead of DecompressAccountsIdempotent.
/// Maps ctx.field -> ctx_seeds.field (direct Pubkey access, no Option unwrapping needed)
/// Only maps data.field -> self.field if the field exists on the state struct.
/// For params-only fields, uses seed_params.field instead of skipping.
#[inline(never)]
fn generate_pda_seed_derivation_for_trait_with_ctx_seeds(
    spec: &TokenSeedSpec,
    ctx_seed_fields: &[syn::Ident],
    state_field_names: &std::collections::HashSet<String>,
    params_only_fields: &[(syn::Ident, syn::Type, bool)],
    is_pinocchio: bool,
) -> Result<TokenStream> {
    let account_crate = if is_pinocchio {
        quote! { light_account_pinocchio }
    } else {
        quote! { light_account }
    };
    // Build a lookup for params-only field names
    let params_only_names: std::collections::HashSet<String> = params_only_fields
        .iter()
        .map(|(name, _, _)| name.to_string())
        .collect();
    let params_only_has_conversion: std::collections::HashMap<String, bool> = params_only_fields
        .iter()
        .map(|(name, _, has_conv)| (name.to_string(), *has_conv))
        .collect();
    let mut bindings: Vec<TokenStream> = Vec::new();
    let mut seed_refs = Vec::new();

    // Convert ctx_seed_fields to a set for quick lookup
    let ctx_field_names = ctx_fields_to_set(ctx_seed_fields);

    for (i, seed) in spec.seeds.iter().enumerate() {
        match seed {
            SeedElement::Literal(lit) => {
                let value = lit.value();
                seed_refs.push(quote! { #value.as_bytes() });
            }
            SeedElement::Expression(expr) => {
                // Handle byte string literals: b"seed" -> use directly (no .as_bytes())
                if let syn::Expr::Lit(lit_expr) = &**expr {
                    if let syn::Lit::ByteStr(byte_str) = &lit_expr.lit {
                        let bytes = byte_str.value();
                        seed_refs.push(quote! { &[#(#bytes),*] });
                        continue;
                    }
                }

                // Handle uppercase constants (single-segment and multi-segment paths)
                if let syn::Expr::Path(path_expr) = &**expr {
                    if let Some(ident) = path_expr.path.get_ident() {
                        // Single-segment path like AUTH_SEED
                        let ident_str = ident.to_string();
                        if is_constant_identifier(&ident_str) {
                            seed_refs.push(
                                quote! { { let __seed: &[u8] = crate::#ident.as_ref(); __seed } },
                            );
                            continue;
                        }
                    } else if let Some(last_seg) = path_expr.path.segments.last() {
                        // Multi-segment path like crate::AUTH_SEED or <Type as Trait>::CONSTANT
                        if is_constant_identifier(&last_seg.ident.to_string()) {
                            // Use the full ExprPath (not just path) to preserve qself
                            // for type-qualified paths like <SeedHolder as HasSeed>::TRAIT_SEED
                            let full_expr = &**expr;
                            seed_refs.push(
                                quote! { { let __seed: &[u8] = #full_expr.as_ref(); __seed } },
                            );
                            continue;
                        }
                    }
                }

                // Check if this is a data.field expression where the field doesn't exist on state
                // If so, use seed_params.field instead of skipping
                if let Some(field_name) = get_params_only_field_name(expr, state_field_names) {
                    if params_only_names.contains(&field_name) {
                        let field_ident =
                            syn::Ident::new(&field_name, proc_macro2::Span::call_site());
                        let binding_name =
                            syn::Ident::new(&format!("seed_{}", i), proc_macro2::Span::call_site());

                        // Check if this field has a conversion (to_le_bytes, to_be_bytes)
                        let has_conversion = params_only_has_conversion
                            .get(&field_name)
                            .copied()
                            .unwrap_or(false);

                        if has_conversion {
                            // u64 field with to_le_bytes conversion
                            // Must bind bytes to a variable to avoid temporary value dropped while borrowed
                            let bytes_binding_name = syn::Ident::new(
                                &format!("{}_bytes", binding_name),
                                proc_macro2::Span::call_site(),
                            );
                            bindings.push(quote! {
                                let #binding_name = seed_params.#field_ident
                                    .ok_or(#account_crate::LightSdkTypesError::InvalidInstructionData)?;
                                let #bytes_binding_name = #binding_name.to_le_bytes();
                            });
                            seed_refs.push(quote! { #bytes_binding_name.as_ref() });
                        } else {
                            // Pubkey field
                            bindings.push(quote! {
                                let #binding_name = seed_params.#field_ident
                                    .ok_or(#account_crate::LightSdkTypesError::InvalidInstructionData)?;
                            });
                            seed_refs.push(quote! { #binding_name.as_ref() });
                        }
                        continue;
                    }
                }

                let binding_name =
                    syn::Ident::new(&format!("seed_{}", i), proc_macro2::Span::call_site());
                let mapped_expr =
                    transform_expr_for_ctx_seeds(expr, &ctx_field_names, state_field_names);

                // Strip trailing .as_ref() / .as_bytes() to avoid binding a temporary
                // reference (E0515/E0716). Instead, bind the owned value and call
                // .as_ref() when constructing the seeds array.
                //
                // Before: let seed_0 = crate::id().as_ref();  // ERROR: temporary dropped
                // After:  let seed_0 = crate::id();  seed_0.as_ref()  // OK: owned value lives long enough
                let (stripped_expr, trailing_method) = strip_trailing_ref_method(&mapped_expr);
                let ref_method = trailing_method.unwrap_or_else(|| format_ident!("as_ref"));

                bindings.push(quote! {
                    let #binding_name = #stripped_expr;
                });
                seed_refs.push(quote! { (#binding_name).#ref_method() });
            }
        }
    }

    let indices: Vec<usize> = (0..seed_refs.len()).collect();

    let pda_derivation = if is_pinocchio {
        quote! {
            let (pda, bump) = pinocchio::pubkey::find_program_address(seeds, program_id);
        }
    } else {
        quote! {
            let program_id_pubkey = solana_pubkey::Pubkey::from(*program_id);
            let (pda, bump) = solana_pubkey::Pubkey::find_program_address(seeds, &program_id_pubkey);
        }
    };

    let pda_to_bytes = if is_pinocchio {
        quote! { pda }
    } else {
        quote! { pda.to_bytes() }
    };

    Ok(quote! {
        #(#bindings)*
        let seeds: &[&[u8]] = &[#(#seed_refs,)*];
        #pda_derivation
        let mut seeds_vec = Vec::with_capacity(seeds.len() + 1);
        #(
            seeds_vec.push(seeds[#indices].to_vec());
        )*
        // Avoid vec![bump] macro which expands to box_new allocation
        {
            let mut bump_vec = Vec::with_capacity(1);
            bump_vec.push(bump);
            seeds_vec.push(bump_vec);
        }
        Ok((seeds_vec, #pda_to_bytes))
    })
}

/// Get the field name from a params-only seed expression.
/// Returns Some(field_name) if the expression is a data.field where field doesn't exist on state.
fn get_params_only_field_name(
    expr: &syn::Expr,
    state_field_names: &std::collections::HashSet<String>,
) -> Option<String> {
    use crate::light_pdas::shared_utils::is_base_path;

    match expr {
        syn::Expr::Field(field_expr) => {
            if let syn::Member::Named(field_name) = &field_expr.member {
                if is_base_path(&field_expr.base, "data") {
                    let name = field_name.to_string();
                    if !state_field_names.contains(&name) {
                        return Some(name);
                    }
                }
            }
            None
        }
        syn::Expr::MethodCall(method_call) => {
            get_params_only_field_name(&method_call.receiver, state_field_names)
        }
        syn::Expr::Reference(ref_expr) => {
            get_params_only_field_name(&ref_expr.expr, state_field_names)
        }
        _ => None,
    }
}

/// Strip trailing `.as_ref()` or `.as_bytes()` method call from an expression.
///
/// Returns `(stripped_expr, Some(method_name))` if a trailing method was stripped,
/// or `(original_expr, None)` if no stripping was needed.
///
/// This avoids the E0515/E0716 error where binding a temporary reference:
///   `let seed = crate::id().as_ref();`  // ERROR: temporary value dropped
/// is replaced with:
///   `let seed = crate::id();`           // OK: owned value
///   `seed.as_ref()`                     // borrow from owned
fn strip_trailing_ref_method(expr: &syn::Expr) -> (syn::Expr, Option<syn::Ident>) {
    if let syn::Expr::MethodCall(mc) = expr {
        let method_name = mc.method.to_string();
        if (method_name == "as_ref" || method_name == "as_bytes") && mc.args.is_empty() {
            return ((*mc.receiver).clone(), Some(mc.method.clone()));
        }
    }
    (expr.clone(), None)
}