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
use {
crate::{
generators::account::{AccountGenerator, AccountType, InitContext, PdaContext},
ParsingContext,
},
proc_macro2::TokenStream,
quote::{format_ident, quote},
std::collections::HashSet,
syn::{parse_quote, Ident, ItemStruct},
typhoon_syn::{
constraints::{Constraint, ConstraintAssociatedToken, ConstraintMint, ConstraintToken},
error, Argument, Arguments,
},
};
pub struct GlobalContext<'a> {
pub need_rent: bool,
pub accounts: Vec<AccountGenerator<'a>>,
pub bumps: HashSet<String>,
pub program_checks: HashSet<String>,
}
impl<'a> GlobalContext<'a> {
pub fn generate_args(&self, context: &ParsingContext) -> Option<(Ident, Option<TokenStream>)> {
let args = context.args.as_ref()?;
let result = match args {
Arguments::Struct(name) => (name.clone(), None),
Arguments::Values(args) => {
let struct_name = format_ident!("{}Args", context.item_struct.ident);
let fields = args
.iter()
.map(|Argument { name, ty }: &Argument| quote!(pub #name: #ty));
let generated_struct = quote! {
#[derive(Debug, PartialEq, bytemuck::AnyBitPattern, bytemuck::NoUninit, Copy, Clone)]
#[repr(C)]
pub struct #struct_name {
#(#fields),*
}
};
(struct_name, Some(generated_struct))
}
};
Some(result)
}
pub fn generate_bumps(&self, context: &ParsingContext) -> Option<(ItemStruct, TokenStream)> {
if self.bumps.is_empty() {
return None;
}
let struct_name = format_ident!("{}Bumps", context.item_struct.ident);
let struct_fields = self.bumps.iter().map(|el| format_ident!("{}", el));
let bumps_struct = parse_quote! {
#[derive(Debug, PartialEq)]
pub struct #struct_name {
#(pub #struct_fields: u8,)*
}
};
let assign_fields = self.bumps.iter().map(|n| {
let name = format_ident!("{n}");
let bump_ident = format_ident!("{n}_bump");
quote!(#name: #bump_ident)
});
let bumps_var = quote! {
let bumps = #struct_name {
#(#assign_fields),*
};
};
Some((bumps_struct, bumps_var))
}
pub fn from_parsing_context(context: &'a ParsingContext) -> Result<Self, syn::Error> {
let mut need_rent = false;
let mut accounts: Vec<AccountGenerator<'_>> = Vec::new();
let mut bumps = HashSet::new();
let mut program_checks = HashSet::new();
let mut states = HashSet::new();
//TODO optimize sorting etc..
for account in &context.accounts {
let account_ty = match account.inner_ty.to_string().as_str() {
"TokenAccount" => AccountType::TokenAccount {
is_ata: false,
mint: None,
owner: None,
},
"Mint" => AccountType::Mint {
authority: None,
decimals: None,
freeze_authority: Box::new(None),
},
_ => AccountType::Other {
space: None,
targets: vec![],
},
};
let mut generator = AccountGenerator::new(account, account_ty);
let name = &account.name;
for constraint in &account.constraints.0 {
match constraint {
Constraint::Init(_) => {
if generator.init.is_some() {
error!(
name,
"The `init` or `init_if_needed` constraint is already specified."
);
}
generator.init = Some(InitContext::default());
}
Constraint::Payer(constraint_payer) => {
if let Some(init_ctx) = &mut generator.init {
if matches!(generator.account_ty, AccountType::Other { .. }) {
need_rent = true;
}
init_ctx.payer = Some(constraint_payer.target.to_owned());
} else {
error!(
name,
"`payer` can only be used with `init` or `init_if_needed` constraint."
)
}
}
Constraint::Space(constraint_space) => {
if generator.init.is_none() {
error!(name, "`space` can only be specified with `init` or `init_if_needed` constraint.");
}
if let AccountType::Other { space, .. } = &mut generator.account_ty {
*space = Some(constraint_space.space.to_owned())
} else {
error!(
name,
"`space` cannot be used on `Mint` or `TokenAccount` type."
)
}
}
Constraint::Seeded(constraint_seeded) => {
if generator.pda.is_some() {
error!(name, "`seeds` or `seeded` are already defined.")
}
generator.pda = Some(PdaContext {
keys: constraint_seeded.0.to_owned(),
bump: None,
is_seeded: true,
program_id: None,
});
}
Constraint::Seeds(constraint_seeds) => {
if generator.pda.is_some() {
error!(name, "`seeds` or `seeded` are already defined.")
}
generator.pda = Some(PdaContext {
keys: Some(constraint_seeds.seeds.to_owned()),
bump: None,
is_seeded: false,
program_id: None,
});
}
Constraint::Bump(constraint_bump) => {
if let Some(pda_ctx) = &mut generator.pda {
match &constraint_bump.0 {
Some(expr) => {
if generator
.init
.as_ref()
.map(|el| el.is_init_if_needed)
.unwrap_or_default()
{
bumps.insert(name.to_string());
}
pda_ctx.bump = Some(expr.to_owned());
if let Some(name) = expr.name() {
states.insert(name.to_string());
}
}
None => {
bumps.insert(name.to_string());
}
}
} else {
error!(name, "`bump` can only be used in a PDA context.");
}
}
Constraint::HasOne(constraint_has_one) => {
if let AccountType::Other { targets, .. } = &mut generator.account_ty {
targets.push((
constraint_has_one.join_target.to_owned(),
constraint_has_one.error.clone(),
));
states.insert(name.to_string());
} else {
error!(
name,
"`has_one` cannot be used on `Mint` or `TokenAccount` type."
);
}
}
Constraint::Program(constraint_program) => {
if let Some(pda_ctx) = &mut generator.pda {
pda_ctx.program_id = Some(constraint_program.0.to_owned());
} else {
error!(name, "`program` can only be used in a PDA context.");
}
}
Constraint::Token(constraint_token) => {
if let AccountType::TokenAccount {
is_ata,
mint,
owner,
} = &mut generator.account_ty
{
if *is_ata {
error!(name, "`associated_token` is already defined.");
}
if generator.init.is_none() {
states.insert(name.to_string());
}
match constraint_token {
ConstraintToken::Mint(ident) => {
*mint = Some(ident.to_owned());
}
ConstraintToken::Owner(expr) => *owner = Some(expr.to_owned()),
}
} else {
error!(
name,
"`token` can only be used with the `TokenAccount` type."
);
}
}
Constraint::Mint(constraint_mint) => {
if let AccountType::Mint {
decimals,
authority,
freeze_authority,
} = &mut generator.account_ty
{
states.insert(name.to_string());
match constraint_mint {
ConstraintMint::Authority(expr) => {
*authority = Some(expr.to_owned())
}
ConstraintMint::Decimals(expr) => *decimals = Some(expr.to_owned()),
ConstraintMint::FreezeAuthority(expr) => {
*freeze_authority = Box::new(Some(expr.to_owned()))
}
}
} else {
error!(
name,
"`mint` constraint can only be used with the `Mint` type"
)
}
}
Constraint::AssociatedToken(constraint_associated_token) => {
if let AccountType::TokenAccount {
mint,
owner,
is_ata,
} = &mut generator.account_ty
{
*is_ata = true;
states.insert(name.to_string());
match constraint_associated_token {
ConstraintAssociatedToken::Mint(ident) => {
*mint = Some(ident.to_owned());
}
ConstraintAssociatedToken::Authority(ident) => {
*owner = Some(parse_quote!(#ident));
}
}
} else {
error!(
name,
"`associated_token` can only be used with the `TokenAccount` type."
);
}
}
Constraint::InitIfNeeded(_) => {
if generator.init.is_some() {
error!(
name,
"The `init` or `init_if_needed` constraint is already specified."
);
}
generator.init = Some(InitContext {
is_init_if_needed: true,
payer: None,
})
}
}
}
for program in generator.needs_programs() {
program_checks.insert(program);
}
accounts.push(generator);
}
for state in states.iter() {
for account in &mut accounts {
if &account.account.name.to_string() == state {
account.init_state = true
}
}
}
Ok(GlobalContext {
need_rent,
accounts,
bumps,
program_checks,
})
}
}