Skip to main content

anchor_attribute_access_control/
lib.rs

1extern crate proc_macro;
2
3use {
4    quote::quote,
5    syn::{parse::Parser, parse_macro_input, punctuated::Punctuated, Expr, Token},
6};
7
8/// Executes the given access control methods before running the decorated
9/// instruction handler. Any method in scope of the attribute can be invoked
10/// with any arguments from the associated instruction handler. Each method
11/// must return `Result<()>`.
12///
13/// # Example
14///
15/// ```ignore
16/// use anchor_lang::prelude::*;
17///
18/// #[program]
19/// mod errors {
20///     use super::*;
21///
22///     #[access_control(Create::accounts(&ctx, bump_seed))]
23///     pub fn create(ctx: Context<Create>, bump_seed: u8) -> Result<()> {
24///       let my_account = &mut ctx.accounts.my_account;
25///       my_account.bump_seed = bump_seed;
26///       Ok(())
27///     }
28/// }
29///
30/// #[derive(Accounts)]
31/// pub struct Create<'info> {
32///   #[account(init, payer = payer, space = 8 + 1)]
33///   my_account: Account<'info, MyAccount>,
34///   #[account(mut)]
35///   payer: Signer<'info>,
36///   system_program: Program<'info, System>,
37/// }
38///
39/// #[account]
40/// pub struct MyAccount {
41///     bump_seed: u8,
42/// }
43///
44/// impl Create<'_> {
45///   pub fn accounts(ctx: &Context<Create>, bump_seed: u8) -> Result<()> {
46///     let seeds = &[ctx.accounts.my_account.to_account_info().key.as_ref(), &[bump_seed]];
47///     Pubkey::create_program_address(seeds, ctx.program_id)
48///       .map_err(|_| error!(ErrorCode::InvalidNonce))?;
49///     Ok(())
50///   }
51/// }
52/// ```
53///
54/// This example demonstrates a useful pattern. Not only can you use
55/// `#[access_control]` to ensure any invariants or preconditions hold prior to
56/// executing an instruction, but also it can be used to finish any validation
57/// on the `Accounts` struct, particularly when instruction arguments are
58/// needed. Here, we use the given `bump_seed` to verify it creates a valid
59/// program-derived address.
60///
61/// Multiple methods may be provided, separated by commas; they run in order:
62///
63/// ```ignore
64/// #[access_control(is_admin(&ctx), not_paused(&ctx.accounts.config))]
65/// pub fn set_fee(ctx: Context<SetFee>, new_fee: u64) -> Result<()> {
66///     ctx.accounts.config.fee = new_fee;
67///     Ok(())
68/// }
69/// ```
70#[proc_macro_attribute]
71pub fn access_control(
72    args: proc_macro::TokenStream,
73    input: proc_macro::TokenStream,
74) -> proc_macro::TokenStream {
75    let parser = Punctuated::<Expr, Token![,]>::parse_terminated;
76    let exprs = match parser.parse(args) {
77        Ok(exprs) => exprs,
78        Err(err) => return err.to_compile_error().into(),
79    };
80    let access_control: Vec<proc_macro2::TokenStream> =
81        exprs.into_iter().map(|expr| quote! { #expr?; }).collect();
82
83    let item_fn = parse_macro_input!(input as syn::ItemFn);
84
85    let fn_attrs = item_fn.attrs;
86    let fn_vis = item_fn.vis;
87    let fn_sig = item_fn.sig;
88    let fn_block = item_fn.block;
89
90    let fn_stmts = fn_block.stmts;
91
92    proc_macro::TokenStream::from(quote! {
93        #(#fn_attrs)*
94        #fn_vis #fn_sig {
95
96            #(#access_control)*
97
98            #(#fn_stmts)*
99        }
100    })
101}