You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ERC721URIStorage中_requireOwned未声明错误求助

问题:Solidity合约编译报错(Undeclared identifier: _requireOwned)

错误信息

DeclarationError: Undeclared identifier.
--> @openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol:35:9:
|
35 | _requireOwned(tokenId);
| ^^^^^^^^^^^^^

合约代码

//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";

contract RealEstate is ERC721URIStorage {
    using Counters for Counters.Counter;
    Counters.Counter private _tokenIds;

    constructor() ERC721("Real Estate", "REAL") {}

    function mint(string memory tokenURI) public returns (uint256) {
        _tokenIds.increment();

        uint256 newItemId = _tokenIds.current();
        _mint(msg.sender, newItemId);
        _setTokenURI(newItemId, tokenURI);

        return newItemId;
    }

    function totalSupply() public view returns (uint256) {
        return _tokenIds.current();
    }
}

已尝试的无效操作

  • 移除ERC721URIStorage.sol中的_requireOwned(tokenId);语句
  • 在自定义合约中添加_requireOwned函数定义

解决方案

原因分析

报错核心是OpenZeppelin合约版本不兼容:

  • _requireOwned是OpenZeppelin v5.x版本新增的内部归属检查函数
  • 若本地安装的是v4.x或更早版本的OpenZeppelin库,ERC721基类中无此函数,编译时会提示未声明

具体修复方法(任选其一)

方法1:升级OpenZeppelin依赖到v5.x版本

在项目根目录执行命令更新依赖:

npm install @openzeppelin/contracts@latest

或用yarn:

yarn add @openzeppelin/contracts@latest

方法2:替换函数兼容旧版本(不升级依赖)

直接修改ERC721URIStorage.sol中的代码,将_requireOwned(tokenId);替换为v4.x版本的等价逻辑:

// 替换前
_requireOwned(tokenId);

// 替换后
require(_ownerOf(tokenId) == _msgSender(), "ERC721URIStorage: caller is not token owner");

注意:不建议直接修改node_modules内的文件,最好复制该合约到本地项目修改后再导入,避免依赖更新丢失修改。

方法3:锁定依赖到v4.x版本

若不想升级到v5.x,安装v4.x系列最新版本即可:

npm install @openzeppelin/contracts@4.9.3

此时ERC721URIStorage中不会出现_requireOwned函数,报错自动消失。


内容的提问来源于stack exchange,提问作者Anurag singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 17:16:04