How to restrict acces to Solana programs only to owners of certain NFT collection using Sol Cerberus

I am using Sol Cerberus to manage the access to my Solana program, but I don’t know how can I call my instruction in javascript to test the access using an NFT collection.

For instance this is my Solana program:

use sol_cerberus_macros::rule;

declare_id!("MY_PROGRAM_ID");

#[program]
pub mod sol_cerberus_demo {

    use super::*;

    #[rule(Stats, View)]
    pub fn view_stats(ctx: Context<Add>) -> Result<()> {
        instructions::view::view(ctx)
    }

}

How can I execute view_stats in my web3 application using an NFT to authenticate the request?

>Solution :

You have a good example in the docs. For instance if you have created the role "Authorized" and assigned it to your NFT collection address "MY_NFT_COLLECTION_MINT_ADDRESS" in the SC Manager, then you can do something like this:

{PublicKey} from '@solana/web3.js';

const solCerberus = new SolCerberus(connection, myWallet, {appId: new PublicKey("PASTE_YOUR_SC_APP_ID_HERE")});
await solCerberus.fetchAllRoles()
await solCerberus.fetchPerms()

await solCerberus.login({
  nfts: [
    [
      new PublicKey("MY_NFT_MINT_ADDRESS"), 
      new PublicKey("MY_NFT_COLLECTION_MINT_ADDRESS")
    ]
  ]
})

if (solCerberus.hasPerm("Stats", "view")){
    try {
        // Add square
        await yourAnchorProgram.methods
            .viewStats()
            .accounts({
            ...(await solCerberus.accounts("Stats", "view")), // Fetches the requires SC accounts
            })
            .rpc();
    } catch (e) {
        // If user is not authorized, you can easily catch the error and inform the user:
        if (solCerberus.isUnauthorizedError(e)) {
            alert("Not authorized!")
        }
    }
}

If you don’t know in advance NFT addresses, you can easily fetch them like explained in Solana’s cookbook.

Leave a Reply