Hey everyone! I’m working on a smart contract and I’m stuck. I want users to add NFT tokenIDs from different collection addresses to my contract. The plan is to store these in a mapping.\n\nHere’s what I’m thinking:\n\nsolidity\ncontract NFTStorage {\n mapping(address => uint256) public nftCollection;\n\n function addNFT(address collectionAddress, uint256 tokenId) public {\n // How do I verify the tokenId belongs to the collectionAddress?\n nftCollection[collectionAddress] = tokenId;\n }\n}\n\n\nBut I’m not sure how to make sure the tokenId actually belongs to the given collection address. Any tips on how to handle this? I’m pretty new to smart contract development, so sorry if I’m missing something obvious. Thanks for any help!
hey there! im also pretty new to smart contracts but ive been playing around with nfts a bit. your idea sounds cool! have you thought about using an interface for the nft contract? that way you could call ownerOf() to check if the token really belongs to the collection. something like:
interface IERC721 {
function ownerOf(uint256 tokenId) external view returns (address);
}
then in your addNFT function you could do:
IERC721 nft = IERC721(collectionAddress);
require(nft.ownerOf(tokenId) == msg.sender, “You dont own this NFT”);
just an idea tho, im not sure if thats the best way. how are you planning to use the stored nfts? it’d be cool to hear more about your project!
yo, that’s a neat idea! have u considered using a nested mapping? like mapping(address => mapping(uint256 => bool)) nftCollection;
that way u can store multiple tokenIds per collection. for verification, maybe try interfacing with the nft contract like PixStar54 suggested. just my 2 cents. what’s the endgame for this project?
Great question! I’ve worked on similar projects before. One approach you might consider is using the ERC721 interface to verify ownership. Here’s a snippet that could help:
import '@openzeppelin/contracts/token/ERC721/IERC721.sol';
contract NFTStorage {
mapping(address => mapping(uint256 => bool)) public nftCollection;
function addNFT(address collectionAddress, uint256 tokenId) public {
IERC721 nft = IERC721(collectionAddress);
require(nft.ownerOf(tokenId) == msg.sender, 'Not the owner');
nftCollection[collectionAddress][tokenId] = true;
}
}
This ensures the caller owns the NFT and allows storing multiple tokens per collection. Remember to handle potential revert cases and gas optimization. Have you considered any specific use cases for these stored NFTs?