Hey everyone! I’m helping a buddy with some code and I’m kinda stuck. We’re working with a smart contract and need to check if a wallet owns an NFT from this contract. The dev who made the contract said we should use the balanceOf function and compare the connected wallet to the contract address.
I’m using ‘ethers’ instead of web3, and I’ve got the wallet address set up like this:
import { useRecoilValue } from 'recoil'
import { walletAtom } from './atoms'
const WalletInfo = () => {
const userWallet = useRecoilValue(walletAtom)
console.log('User wallet:', userWallet.address)
// More code here
}
And in my atoms file:
import { atom } from 'recoil'
export const walletAtom = atom({
key: 'userWalletState',
default: {
address: '',
network: '',
},
})
I’m not sure if this helps, but I’m really lost on how to actually check for NFT ownership. Any tips or examples would be super helpful! Thanks!
hey strummingmelody! cool project youre working on
i’ve done something similar before, so maybe i can help out. have you tried using ethers.js to create a contract instance? it’s pretty straightforward once you get the hang of it.
you’ll need the contract’s ABI and address. then you can do something like this:
const provider = new ethers.providers.Web3Provider(window.ethereum)
const contract = new ethers.Contract(contractAddress, contractABI, provider)
after that, you can call the balanceOf function:
const balance = await contract.balanceOf(userWallet.address)
if balance is greater than 0, your buddy owns an nft!
btw, are you using any specific nft standard? erc721 or erc1155? might be helpful to know for more specific advice.
let me know if you need any more help or if you run into any issues! good luck with your project 
hey there, i gues your best bet is to instanciate the contract with its abi and addr then call balanceOf(userwallet.address). if balance > 0, the user owns an nft. hope this helps!
To check NFT ownership using the balanceOf function, you’ll need to create a contract instance with ethers.js. Here’s a basic approach:
- Import ethers and set up your provider.
- Define your contract ABI and address.
- Create a contract instance.
- Call balanceOf with the user’s wallet address.
Here’s a code snippet to illustrate:
import { ethers } from 'ethers';
const provider = new ethers.providers.Web3Provider(window.ethereum);
const contractAddress = 'YOUR_CONTRACT_ADDRESS';
const contractABI = [ /* Your contract ABI here */ ];
const contract = new ethers.Contract(contractAddress, contractABI, provider);
async function checkNFTOwnership(walletAddress) {
const balance = await contract.balanceOf(walletAddress);
return balance.gt(0);
}
You can then use this function with your existing wallet setup. Remember to handle potential errors and edge cases in your implementation.