Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading