3

I am a beginner in trying this program solana. i have such a question.

can i get nft or account at user address in solana program(smart contract)?

I have a case where I want to make a smart contract which checks whether the user has a certain nft, if so then it will continue and if not it will return an error.

meaning I have to check whether the user has the nft in question.

how do i do that? in the client I can use rpc to fetch nfts accounts, but can this be done in the solana rust program?

1 Answer 1

3

If you are using Anchor, which I recommend for beginners.

You have an account that is defined as Account<'info, anchor_spl::token::TokenAccount>, you can get the amount of SPL tokens stored in that account with:

let amt: u64 = ctx.accounts.my_token_account.amount;
if amt == 1 {
   msg!("I have the NFT")
} else {
   msg("I don't have the NFT")
}

An NFT is an SPL Token that has a total supply of 1. So in this case, if amt != 1 then that person doesn't have that NFT.

Also, you have to make sure that the mint of the token account you're checking is the same as the mint of the NFT in question.

This can be done by adding a constraint.

#[account(mut,token::mint = <mint>)]
token_account : Account<'info, anchor_spl::token::TokenAccount>
3
  • 1
    Great solution. It's worth adding that you should enforce that the mint of the token account you're checking is the same as the mint of the nft in question.
    – Ademola
    Jan 1, 2023 at 18:28
  • thanks for the answer, very helpful. in almost the same case, i want to check if the user has the nft of the symbol i mean (example program success run if user have nft with symbol X & Y, it not program will error). because I don't want the program to run when the user does not satisfy the nft condition of symbol X and Y. is this possible too? Jan 1, 2023 at 20:33
  • Yes, the last part of my updated answer checks if the NFT matches the mint you want to check (nft with symbol X)
    – vicyyn
    Jan 1, 2023 at 20:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.