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
use crate::{
AccountField, AccountsStruct, CompositeField, Constraint, ConstraintAssociated,
ConstraintBelongsTo, ConstraintExecutable, ConstraintLiteral, ConstraintOwner,
ConstraintRentExempt, ConstraintSeeds, ConstraintSigner, ConstraintState, Field, Ty,
};
use heck::SnakeCase;
use quote::quote;
pub fn generate(accs: AccountsStruct) -> proc_macro2::TokenStream {
let non_associated_fields: Vec<&AccountField> =
accs.fields.iter().filter(|af| !is_associated(af)).collect();
let deser_fields: Vec<proc_macro2::TokenStream> = accs
.fields
.iter()
.map(|af: &AccountField| {
match af {
AccountField::AccountsStruct(s) => {
let name = &s.ident;
let ty = &s.raw_field.ty;
quote! {
#[cfg(feature = "anchor-debug")]
::solana_program::log::sol_log(stringify!(#name));
let #name: #ty = anchor_lang::Accounts::try_accounts(program_id, accounts)?;
}
}
AccountField::Field(f) => {
if is_associated(af) {
let name = &f.ident;
quote!{
let #name = &accounts[0];
*accounts = &accounts[1..];
}
} else {
let name = &f.typed_ident();
match f.is_init {
false => quote! {
#[cfg(feature = "anchor-debug")]
::solana_program::log::sol_log(stringify!(#name));
let #name = anchor_lang::Accounts::try_accounts(program_id, accounts)?;
},
true => quote! {
#[cfg(feature = "anchor-debug")]
::solana_program::log::sol_log(stringify!(#name));
let #name = anchor_lang::AccountsInit::try_accounts_init(program_id, accounts)?;
},
}
}
}
}
})
.collect();
let deser_associated_fields: Vec<proc_macro2::TokenStream> = accs
.fields
.iter()
.filter_map(|af| match af {
AccountField::AccountsStruct(_s) => None,
AccountField::Field(f) => match is_associated(af) {
false => None,
true => Some(f),
},
})
.map(|field: &Field| {
let checks = field
.constraints
.iter()
.map(|c| generate_field_constraint(&field, c))
.collect::<Vec<proc_macro2::TokenStream>>();
quote! {
#(#checks)*
}
})
.collect();
let access_checks: Vec<proc_macro2::TokenStream> = non_associated_fields
.iter()
.map(|af: &&AccountField| {
let checks: Vec<proc_macro2::TokenStream> = match af {
AccountField::Field(f) => f
.constraints
.iter()
.map(|c| generate_field_constraint(&f, c))
.collect(),
AccountField::AccountsStruct(s) => s
.constraints
.iter()
.map(|c| generate_composite_constraint(&s, c))
.collect(),
};
quote! {
#(#checks)*
}
})
.collect();
let return_tys: Vec<proc_macro2::TokenStream> = accs
.fields
.iter()
.map(|f: &AccountField| {
let name = match f {
AccountField::AccountsStruct(s) => &s.ident,
AccountField::Field(f) => &f.ident,
};
quote! {
#name
}
})
.collect();
let on_save: Vec<proc_macro2::TokenStream> = accs
.fields
.iter()
.map(|af: &AccountField| match af {
AccountField::AccountsStruct(s) => {
let name = &s.ident;
quote! {
anchor_lang::AccountsExit::exit(&self.#name, program_id)?;
}
}
AccountField::Field(f) => {
let ident = &f.ident;
match f.is_mut {
false => quote! {},
true => quote! {
anchor_lang::AccountsExit::exit(&self.#ident, program_id)?;
},
}
}
})
.collect();
let to_acc_infos: Vec<proc_macro2::TokenStream> = accs
.fields
.iter()
.map(|f: &AccountField| {
let name = match f {
AccountField::AccountsStruct(s) => &s.ident,
AccountField::Field(f) => &f.ident,
};
quote! {
account_infos.extend(self.#name.to_account_infos());
}
})
.collect();
let to_acc_metas: Vec<proc_macro2::TokenStream> = accs
.fields
.iter()
.map(|f: &AccountField| {
let (name, is_signer) = match f {
AccountField::AccountsStruct(s) => (&s.ident, quote! {None}),
AccountField::Field(f) => {
let is_signer = match f.is_signer {
false => quote! {None},
true => quote! {Some(true)},
};
(&f.ident, is_signer)
}
};
quote! {
account_metas.extend(self.#name.to_account_metas(#is_signer));
}
})
.collect();
let name = &accs.ident;
let (combined_generics, trait_generics, strct_generics) = match accs.generics.lt_token {
None => (quote! {<'info>}, quote! {<'info>}, quote! {}),
Some(_) => {
let g = &accs.generics;
(quote! {#g}, quote! {#g}, quote! {#g})
}
};
let account_mod_name: proc_macro2::TokenStream = format!(
"__client_accounts_{}",
accs.ident.to_string().to_snake_case()
)
.parse()
.unwrap();
let account_struct_fields: Vec<proc_macro2::TokenStream> = accs
.fields
.iter()
.map(|f: &AccountField| match f {
AccountField::AccountsStruct(s) => {
let name = &s.ident;
let symbol: proc_macro2::TokenStream = format!(
"__client_accounts_{0}::{1}",
s.symbol.to_snake_case(),
s.symbol,
)
.parse()
.unwrap();
quote! {
pub #name: #symbol
}
}
AccountField::Field(f) => {
let name = &f.ident;
quote! {
pub #name: anchor_lang::solana_program::pubkey::Pubkey
}
}
})
.collect();
let account_struct_metas: Vec<proc_macro2::TokenStream> = accs
.fields
.iter()
.map(|f: &AccountField| match f {
AccountField::AccountsStruct(s) => {
let name = &s.ident;
quote! {
account_metas.extend(self.#name.to_account_metas(None));
}
}
AccountField::Field(f) => {
let is_signer = match f.is_signer {
false => quote! {false},
true => quote! {true},
};
let meta = match f.is_mut {
false => quote! { anchor_lang::solana_program::instruction::AccountMeta::new_readonly },
true => quote! { anchor_lang::solana_program::instruction::AccountMeta::new },
};
let name = &f.ident;
quote! {
account_metas.push(#meta(self.#name, #is_signer));
}
}
})
.collect();
let re_exports: Vec<proc_macro2::TokenStream> = {
let mut re_exports = std::collections::HashSet::new();
for f in accs.fields.iter().filter_map(|f: &AccountField| match f {
AccountField::AccountsStruct(s) => Some(s),
AccountField::Field(_) => None,
}) {
re_exports.insert(format!(
"__client_accounts_{0}::{1}",
f.symbol.to_snake_case(),
f.symbol,
));
}
re_exports
.iter()
.map(|symbol: &String| {
let symbol: proc_macro2::TokenStream = symbol.parse().unwrap();
quote! {
pub use #symbol;
}
})
.collect()
};
quote! {
mod #account_mod_name {
use super::*;
use anchor_lang::prelude::borsh;
#(#re_exports)*
#[derive(anchor_lang::AnchorSerialize)]
pub struct #name {
#(#account_struct_fields),*
}
impl anchor_lang::ToAccountMetas for #name {
fn to_account_metas(&self, is_signer: Option<bool>) -> Vec<anchor_lang::solana_program::instruction::AccountMeta> {
let mut account_metas = vec![];
#(#account_struct_metas)*
account_metas
}
}
}
impl#combined_generics anchor_lang::Accounts#trait_generics for #name#strct_generics {
#[inline(never)]
fn try_accounts(program_id: &anchor_lang::solana_program::pubkey::Pubkey, accounts: &mut &[anchor_lang::solana_program::account_info::AccountInfo<'info>]) -> std::result::Result<Self, anchor_lang::solana_program::program_error::ProgramError> {
#(#deser_fields)*
#(#deser_associated_fields)*
#(#access_checks)*
Ok(#name {
#(#return_tys),*
})
}
}
impl#combined_generics anchor_lang::ToAccountInfos#trait_generics for #name#strct_generics {
fn to_account_infos(&self) -> Vec<anchor_lang::solana_program::account_info::AccountInfo<'info>> {
let mut account_infos = vec![];
#(#to_acc_infos)*
account_infos
}
}
impl#combined_generics anchor_lang::ToAccountMetas for #name#strct_generics {
fn to_account_metas(&self, is_signer: Option<bool>) -> Vec<anchor_lang::solana_program::instruction::AccountMeta> {
let mut account_metas = vec![];
#(#to_acc_metas)*
account_metas
}
}
impl#combined_generics anchor_lang::AccountsExit#trait_generics for #name#strct_generics {
fn exit(&self, program_id: &anchor_lang::solana_program::pubkey::Pubkey) -> anchor_lang::solana_program::entrypoint::ProgramResult {
#(#on_save)*
Ok(())
}
}
}
}
fn is_associated(af: &AccountField) -> bool {
match af {
AccountField::AccountsStruct(_s) => false,
AccountField::Field(f) => f
.constraints
.iter()
.filter(|c| match c {
Constraint::Associated(_c) => true,
_ => false,
})
.next()
.is_some(),
}
}
pub fn generate_field_constraint(f: &Field, c: &Constraint) -> proc_macro2::TokenStream {
match c {
Constraint::BelongsTo(c) => generate_constraint_belongs_to(f, c),
Constraint::Signer(c) => generate_constraint_signer(f, c),
Constraint::Literal(c) => generate_constraint_literal(c),
Constraint::Owner(c) => generate_constraint_owner(f, c),
Constraint::RentExempt(c) => generate_constraint_rent_exempt(f, c),
Constraint::Seeds(c) => generate_constraint_seeds(f, c),
Constraint::Executable(c) => generate_constraint_executable(f, c),
Constraint::State(c) => generate_constraint_state(f, c),
Constraint::Associated(c) => generate_constraint_associated(f, c),
}
}
pub fn generate_composite_constraint(
_f: &CompositeField,
c: &Constraint,
) -> proc_macro2::TokenStream {
match c {
Constraint::Literal(c) => generate_constraint_literal(c),
_ => panic!("Composite fields can only use literal constraints"),
}
}
pub fn generate_constraint_belongs_to(
f: &Field,
c: &ConstraintBelongsTo,
) -> proc_macro2::TokenStream {
let target = c.join_target.clone();
let ident = &f.ident;
let field = match &f.ty {
Ty::Loader(_) => quote! {#ident.load()?},
_ => quote! {#ident},
};
quote! {
if &#field.#target != #target.to_account_info().key {
return Err(anchor_lang::solana_program::program_error::ProgramError::Custom(1));
}
}
}
pub fn generate_constraint_signer(f: &Field, _c: &ConstraintSigner) -> proc_macro2::TokenStream {
let ident = &f.ident;
let info = match f.ty {
Ty::AccountInfo => quote! { #ident },
Ty::ProgramAccount(_) => quote! { #ident.to_account_info() },
_ => panic!("Invalid syntax: signer cannot be specified."),
};
quote! {
if cfg!(not(feature = "cpi")) {
if !#info.is_signer {
return Err(anchor_lang::solana_program::program_error::ProgramError::MissingRequiredSignature);
}
}
}
}
pub fn generate_constraint_literal(c: &ConstraintLiteral) -> proc_macro2::TokenStream {
let tokens = &c.tokens;
quote! {
if !(#tokens) {
return Err(anchor_lang::solana_program::program_error::ProgramError::Custom(1));
}
}
}
pub fn generate_constraint_owner(f: &Field, c: &ConstraintOwner) -> proc_macro2::TokenStream {
let ident = &f.ident;
let owner_target = c.owner_target.clone();
quote! {
if #ident.to_account_info().owner != #owner_target.to_account_info().key {
return Err(ProgramError::Custom(76));
}
}
}
pub fn generate_constraint_rent_exempt(
f: &Field,
c: &ConstraintRentExempt,
) -> proc_macro2::TokenStream {
let ident = &f.ident;
let info = match f.ty {
Ty::AccountInfo => quote! { #ident },
Ty::ProgramAccount(_) => quote! { #ident.to_account_info() },
Ty::Loader(_) => quote! { #ident.to_account_info() },
_ => panic!("Invalid syntax: rent exemption cannot be specified."),
};
match c {
ConstraintRentExempt::Skip => quote! {},
ConstraintRentExempt::Enforce => quote! {
if !rent.is_exempt(#info.lamports(), #info.try_data_len()?) {
return Err(anchor_lang::solana_program::program_error::ProgramError::Custom(2));
}
},
}
}
pub fn generate_constraint_seeds(f: &Field, c: &ConstraintSeeds) -> proc_macro2::TokenStream {
let name = &f.ident;
let seeds = &c.seeds;
quote! {
let program_signer = Pubkey::create_program_address(
&#seeds,
program_id,
).map_err(|_| anchor_lang::solana_program::program_error::ProgramError::Custom(1))?;
if #name.to_account_info().key != &program_signer {
return Err(anchor_lang::solana_program::program_error::ProgramError::Custom(1));
}
}
}
pub fn generate_constraint_executable(
f: &Field,
_c: &ConstraintExecutable,
) -> proc_macro2::TokenStream {
let name = &f.ident;
quote! {
if !#name.to_account_info().executable {
return Err(anchor_lang::solana_program::program_error::ProgramError::Custom(5))
}
}
}
pub fn generate_constraint_state(f: &Field, c: &ConstraintState) -> proc_macro2::TokenStream {
let program_target = c.program_target.clone();
let ident = &f.ident;
let account_ty = match &f.ty {
Ty::CpiState(ty) => &ty.account_ident,
_ => panic!("Invalid state constraint"),
};
quote! {
if #ident.to_account_info().key != &anchor_lang::CpiState::<#account_ty>::address(#program_target.to_account_info().key) {
return Err(ProgramError::Custom(1));
}
if #ident.to_account_info().owner != #program_target.to_account_info().key {
return Err(ProgramError::Custom(1));
}
}
}
pub fn generate_constraint_associated(
f: &Field,
c: &ConstraintAssociated,
) -> proc_macro2::TokenStream {
let associated_target = c.associated_target.clone();
let field = &f.ident;
let (account_ty, is_zero_copy) = match &f.ty {
Ty::ProgramAccount(ty) => (&ty.account_ident, false),
Ty::Loader(ty) => (&ty.account_ident, true),
_ => panic!("Invalid associated constraint"),
};
let space = match &f.space {
None => match is_zero_copy {
false => {
quote! {
let space = 8 + #account_ty::default().try_to_vec().unwrap().len();
}
}
true => {
quote! {
let space = 8 + anchor_lang::__private::bytemuck::bytes_of(&#account_ty::default()).len();
}
}
},
Some(s) => quote! {
let space = #s;
},
};
let payer = match &f.payer {
None => quote! {
let payer = #associated_target.to_account_info();
},
Some(p) => quote! {
let payer = #p.to_account_info();
},
};
let seeds_no_nonce = match f.associated_seeds.len() {
0 => quote! {
[
&b"anchor"[..],
#associated_target.to_account_info().key.as_ref(),
]
},
_ => {
let seeds = to_seeds_tts(&f.associated_seeds);
quote! {
[
&b"anchor"[..],
#associated_target.to_account_info().key.as_ref(),
#seeds
]
}
}
};
let seeds_with_nonce = match f.associated_seeds.len() {
0 => quote! {
[
&b"anchor"[..],
#associated_target.to_account_info().key.as_ref(),
&[nonce],
]
},
_ => {
let seeds = to_seeds_tts(&f.associated_seeds);
quote! {
[
&b"anchor"[..],
#associated_target.to_account_info().key.as_ref(),
#seeds
&[nonce],
]
}
}
};
let account_wrapper_ty = match is_zero_copy {
false => quote! {
anchor_lang::ProgramAccount
},
true => quote! {
anchor_lang::Loader
},
};
let nonce_assignment = match is_zero_copy {
false => quote! {},
true => quote! {
.load_init()?
},
};
quote! {
let #field: #account_wrapper_ty<#account_ty> = {
#space
#payer
let (associated_field, nonce) = Pubkey::find_program_address(
&#seeds_no_nonce,
program_id,
);
if &associated_field != #field.key {
return Err(ProgramError::Custom(45));
}
let lamports = rent.minimum_balance(space);
let ix = anchor_lang::solana_program::system_instruction::create_account(
payer.key,
#field.key,
lamports,
space as u64,
program_id,
);
let seeds = #seeds_with_nonce;
let signer = &[&seeds[..]];
anchor_lang::solana_program::program::invoke_signed(
&ix,
&[
#field.clone(),
payer.clone(),
system_program.clone(),
],
signer,
).map_err(|e| {
anchor_lang::solana_program::msg!("Unable to create associated account");
e
})?;
let mut pa: #account_wrapper_ty<#account_ty> = #account_wrapper_ty::try_from_init(
&#field,
)?;
pa#nonce_assignment.__nonce = nonce;
pa
};
}
}
fn to_seeds_tts(seeds: &[syn::Ident]) -> proc_macro2::TokenStream {
assert!(seeds.len() > 0);
let seed_0 = &seeds[0];
let mut tts = quote! {
#seed_0.to_account_info().key.as_ref(),
};
for seed in &seeds[1..] {
tts = quote! {
#tts
#seed.to_account_info().key.as_ref(),
};
}
tts
}