I got an Anchor program and there is some functions that I want to restrict their access in order to create some particular privileges in the program, so I want to grab the caller's account/address public key inside the program in order to save it for future use, how can I do so?
2 Answers
Example:
#[derive(Accounts)]
pub struct DoSomething<'info> {
#[account()]
pub signer: Signer<'info>,
}
To get signer's address you can use:
ctx.accounts.signer.key()
To save the Public Key you can create an Account that holds Public Keys:
pub struct PkList {
pubKeys: Vec<Pubkey>
}
for example like so:
const ADMIN_PUBKEY: Pubkey = pubkey!("4j9iNoHBY34rksAwJmHHCooRbAVxo2vajCHQWKo3Hwii");
#[account(
mut,
address = ADMIN_PUBKEY
)]
pub admin: Signer<'info>,
Here is a full example: https://beta.solpg.io/tutorials/battle-coins
If you want to save it you can do so in a PDA where one of the seeds is the caller and then save an authority in there for example. In the given example you could add it to the PlayerData for example.
-
1This is not what I meant, when someone is calling some particular function on my program I want to grab it and store it in an array. Commented Aug 7, 2023 at 12:53
-
Then you should be able to have an account with a Vec<PubKey> and add one when the function is called and then check the list whenever you need to check if the pubkey (which should be a signer) is in that list.– Jonas H.Commented Aug 7, 2023 at 12:57
-
How can I add one when the function is called? The only parameter in the function is a struct called Context Commented Aug 7, 2023 at 12:59
-
Just add another parameter, PubKey or just take it from the ctx.accounts.signer for example.– Jonas H.Commented Aug 7, 2023 at 13:00
-
1So ctx.accounts.signer.key()? I don't want the PubKey to be a parameter, so users will not be able to manipulate it Commented Aug 7, 2023 at 13:06