使用OpenZeppelin的_setTokenURI出现未声明标识符错误求助
问题原因与解决方案
错误原因
_setTokenURI 是 OpenZeppelin ERC721URIStorage 合约提供的专属方法,你的合约仅继承了 ERC721 和 Ownable,并未继承 ERC721URIStorage,所以编译器无法识别这个未声明的标识符。
另外需要注意:OpenZeppelin v4.x 版本开始,基础 ERC721 合约已经移除了 _setTokenURI 方法,将URI存储功能拆分到了 ERC721URIStorage 扩展合约中,必须继承该扩展才能使用相关方法。
修复步骤
- 修改合约的继承列表,添加
ERC721URIStorage;由于ERC721URIStorage本身已经继承了ERC721,可以移除原有的ERC721继承项(保留也不会报错,但写法更简洁)。 - 确保构造函数中调用
ERC721的初始化逻辑保持不变。
修改后的完整代码
pragma solidity ^0.8.9; import '@openzeppelin/contracts/access/Ownable.sol'; import '@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol'; contract MintNft is ERC721URIStorage, Ownable { uint256 public mintPrice = 0.005 ether; uint public totalSupply; uint public maxSupply; bool public isMintEnabled; // Mapping for amount of minted nfts by an address mapping(address => uint256) public mintedWallets; constructor() payable ERC721('Pokemon Card', 'POKE') { maxSupply = 20; } function toggleIsMintEnabled() external onlyOwner { isMintEnabled = !isMintEnabled; } function setMaxSupply(uint256 _maxSupply) external onlyOwner { maxSupply = _maxSupply; } function mint(string memory tokenURI) external payable { require(isMintEnabled,"Minting is not enable"); require(mintedWallets[msg.sender] < 2, 'You have reached maximum mint number'); require(msg.value == mintPrice, "Wrong value"); require(maxSupply > totalSupply, "Sold Out ! "); mintedWallets[msg.sender]++; totalSupply++; uint256 tokenId = totalSupply; _safeMint(msg.sender, tokenId); _setTokenURI(tokenId,tokenURI); } }
内容的提问来源于stack exchange,提问作者evilmerto
相关产品推荐
相关产品推荐

