Skip to main content

anchor_attribute_access_control/
lib.rs

1extern crate proc_macro;
2
3use {quote::quote, syn::parse_macro_input};
4
5/// Executes the given access control method before running the decorated
6/// instruction handler. Any method in scope of the attribute can be invoked
7/// with any arguments from the associated instruction handler.
8///
9/// # Example
10///
11/// ```ignore
12/// use anchor_lang::prelude::*;
13///
14/// #[program]
15/// mod errors {
16///     use super::*;
17///
18///     #[access_control(Create::accounts(&ctx, bump_seed))]
19///     pub fn create(ctx: Context<Create>, bump_seed: u8) -> Result<()> {
20///       let my_account = &mut ctx.accounts.my_account;
21///       my_account.bump_seed = bump_seed;
22///     }
23/// }
24///
25/// #[derive(Accounts)]
26/// pub struct Create {
27///   #[account(init)]
28///   my_account: Account<'info, MyAccount>,
29/// }
30///
31/// impl Create {
32///   pub fn accounts(ctx: &Context<Create>, bump_seed: u8) -> Result<()> {
33///     let seeds = &[ctx.accounts.my_account.to_account_info().key.as_ref(), &[bump_seed]];
34///     Pubkey::create_program_address(seeds, ctx.program_id)
35///       .map_err(|_| ErrorCode::InvalidNonce)?;
36///     Ok(())
37///   }
38/// }
39/// ```
40///
41/// This example demonstrates a useful pattern. Not only can you use
42/// `#[access_control]` to ensure any invariants or preconditions hold prior to
43/// executing an instruction, but also it can be used to finish any validation
44/// on the `Accounts` struct, particularly when instruction arguments are
45/// needed. Here, we use the given `bump_seed` to verify it creates a valid
46/// program-derived address.
47#[proc_macro_attribute]
48pub fn access_control(
49    args: proc_macro::TokenStream,
50    input: proc_macro::TokenStream,
51) -> proc_macro::TokenStream {
52    let mut args = args.to_string();
53    args.retain(|c| !c.is_whitespace());
54    let access_control: Vec<proc_macro2::TokenStream> = args
55        .split(')')
56        .filter(|ac| !ac.is_empty())
57        .map(|ac| format!("{ac})")) // Put back on the split char.
58        .map(|ac| format!("{ac}?;")) // Add `?;` syntax.
59        .map(|ac| ac.parse().unwrap())
60        .collect();
61
62    let item_fn = parse_macro_input!(input as syn::ItemFn);
63
64    let fn_attrs = item_fn.attrs;
65    let fn_vis = item_fn.vis;
66    let fn_sig = item_fn.sig;
67    let fn_block = item_fn.block;
68
69    let fn_stmts = fn_block.stmts;
70
71    proc_macro::TokenStream::from(quote! {
72        #(#fn_attrs)*
73        #fn_vis #fn_sig {
74
75            #(#access_control)*
76
77            #(#fn_stmts)*
78        }
79    })
80}