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
use proc_macro::TokenStream;
use quote::{quote, ToTokens};
use syn::{
    parse::{Parse, ParseStream},
    parse_macro_input,
    punctuated::Punctuated,
    Attribute, Data, DeriveInput, Expr, Fields, GenericParam, Lit, Meta, NestedMeta, Token,
};

struct Seeds(Punctuated<Expr, Token![,]>);

impl Parse for Seeds {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let content;
        syn::bracketed!(content in input);
        Ok(Seeds(content.parse_terminated(Expr::parse)?))
    }
}

#[proc_macro_derive(ExtraMetas, attributes(meta))]
pub fn derive_extra_metas(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    let name = &input.ident;

    // Extract lifetimes
    let lifetimes: Vec<_> = input
        .generics
        .params
        .iter()
        .filter_map(|param| {
            if let GenericParam::Lifetime(lt) = param {
                Some(lt.lifetime.clone())
            } else {
                None
            }
        })
        .collect();

    // Determine if the 'info lifetime is present
    let has_info_lifetime = lifetimes.iter().any(|lt| lt.to_string() == "'info");

    // Extract fields
    let fields = if let Data::Struct(data_struct) = &input.data {
        if let Fields::Named(fields) = &data_struct.fields {
            fields.named.iter().collect::<Vec<_>>()
        } else {
            vec![]
        }
    } else {
        vec![]
    };

    // Process account metas: pubkey or seeds
    let account_metas = fields
        .iter()
        .filter_map(|f| {
            let ident = f.ident.as_ref()?;
            let meta_attr = f.attrs.iter().find(|attr| attr.path.is_ident("meta"))?;
            parse_meta_attribute(ident, meta_attr).ok()
        })
        .collect::<Vec<_>>();

    let field_names = fields
        .iter()
        .filter_map(|f| f.ident.as_ref())
        .collect::<Vec<_>>();

    // Generate from_accounts method
    let from_accounts = if has_info_lifetime {
        quote! {
            fn from_accounts(accounts: &[AccountInfo<'info>]) -> Result<Self, ProgramError> {
                let mut iter = accounts.iter().skip(5); // Adjust skip as needed
                Ok(Self {
                    #(#field_names: iter.next().ok_or(ProgramError::NotEnoughAccountKeys)?.clone(),)*
                })
            }
        }
    } else {
        quote! {
            fn from_accounts(accounts: &[AccountInfo]) -> Result<Self, ProgramError> {
                let mut iter = accounts.iter().skip(5); // Adjust skip as needed
                Ok(Self {
                    #(#field_names: iter.next().ok_or(ProgramError::NotEnoughAccountKeys)?.clone(),)*
                })
            }
        }
    };

    // Generate trait implementation for ExtraMetas
    let gen = if has_info_lifetime {
        quote! {
            impl<#(#lifetimes),*> ExtraMetas<#(#lifetimes),*> for #name<#(#lifetimes),*> {
                #from_accounts

                fn to_extra_account_metas() -> Vec<ExtraAccountMeta> {
                    vec![
                        #(#account_metas),*
                    ]
                }
            }
        }
    } else if !lifetimes.is_empty() {
        quote! {
            impl<#(#lifetimes),*> ExtraMetas<'_, #(#lifetimes),*> for #name<#(#lifetimes),*> {
                #from_accounts

                fn to_extra_account_metas() -> Vec<ExtraAccountMeta> {
                    vec![
                        #(#account_metas),*
                    ]
                }
            }
        }
    } else {
        quote! {
            impl ExtraMetas<'_> for #name {
                #from_accounts

                fn to_extra_account_metas() -> Vec<ExtraAccountMeta> {
                    vec![
                        #(#account_metas),*
                    ]
                }
            }
        }
    };

    gen.into()
}

fn parse_meta_attribute(
    _ident: &syn::Ident,
    attr: &Attribute,
) -> syn::Result<proc_macro2::TokenStream> {
    let meta = attr.parse_meta()?;
    if let Meta::List(list) = meta {
        let mut pubkey = None;
        let mut signer = false;
        let mut writable = false;
        let mut seeds = None;

        for nested in list.nested.iter() {
            match nested {
                NestedMeta::Meta(Meta::NameValue(nv)) => {
                    match nv.path.get_ident().map(|i| i.to_string()).as_deref() {
                        Some("pubkey") => {
                            if let Lit::Str(lit) = &nv.lit {
                                pubkey = Some(lit.value());
                            }
                        }
                        Some("signer") => {
                            if let Lit::Bool(lit) = &nv.lit {
                                signer = lit.value();
                            }
                        }
                        Some("writable") => {
                            if let Lit::Bool(lit) = &nv.lit {
                                writable = lit.value();
                            }
                        }
                        _ => {}
                    }
                }
                NestedMeta::Meta(Meta::List(list)) if list.path.is_ident("seeds") => {
                    seeds = Some(syn::parse2::<Seeds>(list.nested.to_token_stream())?);
                }
                _ => {}
            }
        }

        if pubkey.is_some() && seeds.is_some() {
            return Err(syn::Error::new_spanned(
                attr,
                "Cannot specify both pubkey and seeds",
            ));
        }

        if pubkey.is_none() && seeds.is_none() {
            return Err(syn::Error::new_spanned(
                attr,
                "Must specify either pubkey or seeds",
            ));
        }

        // Generate appropriate ExtraAccountMeta based on pubkey or seeds
        Ok(if let Some(pk) = pubkey {
            quote! {
                ExtraAccountMeta::new_with_pubkey(&#pk.parse().unwrap(), #signer, #writable).unwrap()
            }
        } else if let Some(Seeds(seeds)) = seeds {
            let seed_exprs = seeds.iter();
            quote! {
                ExtraAccountMeta::new_external_pda_with_seeds(
                    0, // Associated token program index, adjust as needed
                    &[#(#seed_exprs),*],
                    #signer,
                    #writable
                ).unwrap()
            }
        } else {
            unreachable!()
        })
    } else {
        Err(syn::Error::new_spanned(
            attr,
            "Expected list-style attribute",
        ))
    }
}