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///       Ok(())
23///     }
24/// }
25///
26/// #[derive(Accounts)]
27/// pub struct Create<'info> {
28///   #[account(init, payer = payer, space = 8 + 1)]
29///   my_account: Account<'info, MyAccount>,
30///   #[account(mut)]
31///   payer: Signer<'info>,
32///   system_program: Program<'info, System>,
33/// }
34///
35/// #[account]
36/// pub struct MyAccount {
37///     bump_seed: u8,
38/// }
39///
40/// impl Create<'_> {
41///   pub fn accounts(ctx: &Context<Create>, bump_seed: u8) -> Result<()> {
42///     let seeds = &[ctx.accounts.my_account.to_account_info().key.as_ref(), &[bump_seed]];
43///     Pubkey::create_program_address(seeds, ctx.program_id)
44///       .map_err(|_| error!(ErrorCode::InvalidNonce))?;
45///     Ok(())
46///   }
47/// }
48/// ```
49///
50/// This example demonstrates a useful pattern. Not only can you use
51/// `#[access_control]` to ensure any invariants or preconditions hold prior to
52/// executing an instruction, but also it can be used to finish any validation
53/// on the `Accounts` struct, particularly when instruction arguments are
54/// needed. Here, we use the given `bump_seed` to verify it creates a valid
55/// program-derived address.
56#[proc_macro_attribute]
57pub fn access_control(
58    args: proc_macro::TokenStream,
59    input: proc_macro::TokenStream,
60) -> proc_macro::TokenStream {
61    let mut args = args.to_string();
62    args.retain(|c| !c.is_whitespace());
63    let access_control: Vec<proc_macro2::TokenStream> = args
64        .split(')')
65        .filter(|ac| !ac.is_empty())
66        .map(|ac| format!("{ac})")) // Put back on the split char.
67        .map(|ac| format!("{ac}?;")) // Add `?;` syntax.
68        .map(|ac| {
69            ac.parse::<proc_macro2::TokenStream>().map_err(|_| {
70                syn::Error::new(
71                    proc_macro2::Span::call_site(),
72                    format!("`#[access_control]` argument `{ac} is not valid Rust syntax"),
73                )
74                .into_compile_error()
75            })
76        })
77        .collect::<Result<Vec<_>, _>>()
78        .unwrap_or_else(|err| vec![err]);
79
80    let item_fn = parse_macro_input!(input as syn::ItemFn);
81
82    let fn_attrs = item_fn.attrs;
83    let fn_vis = item_fn.vis;
84    let fn_sig = item_fn.sig;
85    let fn_block = item_fn.block;
86
87    let fn_stmts = fn_block.stmts;
88
89    proc_macro::TokenStream::from(quote! {
90        #(#fn_attrs)*
91        #fn_vis #fn_sig {
92
93            #(#access_control)*
94
95            #(#fn_stmts)*
96        }
97    })
98}