I am trying to help a friend out with some coding, but I'm no expert either. Another developer created a smart contract and he mentioned that I should use the balanceOf function from the smart contract and verify the connected wallet against the smart contract address to find out if the connected wallet contains a NFT of this contract. The problem is that I do not know where to start and I'd like to ask the community for some help and guidance.
Additional info I know:
import { walletState } from "../state/app";
import { useRecoilValue } from "recoil";
const wallet = useRecoilValue(walletState);
console.log("Wallet address: ", wallet.address);
../state/app contains:
import { atom } from "recoil";
export const walletState = atom({
key: "_app.walletState",
default: {
address: "",
chainId: "",
},
});
But I don't even know if that's relevant to get to a working solution on NFT ownership verification.
Using balanceOf
on the frontend, by itself, isn't a safe way to verify someone owns the NFT.
I'll describe below how to do it to answer your question, You can do it, but this is not safe!
You need to know the address of the NFT in advance.
balanceOf
is an ERC721 (NFT) function that tells you how many NFTs an address owns in a collection. It takes an address as a (required) argument.
In ethers js, this would look like
const abi = [
"function balanceOf(address) public view returns (uint256)",
]
// replace the address below with the collection you care about
const NFT_ADDRESS = "0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d";
const nftContract = new ethers.Contract(NFT_ADDRESS, abi, wallet);
const balance = await nftContract.balanceOf(wallet.address);
// if balance is more than 0, this person owns at least one NFT in the collection.
Why isn't this safe? Anyone can overwrite the javascript locally to change their address to be one of the owners of the NFT collection. To do this safely, you need to ask the person to a sign a message then verify on the backend that their address, when plugged into balanceOf
returns 1 or more, and their signature matches the address.