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

NFT项目获取当前报价时返回undefined问题求助

问题排查与解决

核心原因:returnsCurrentOfferPrice 函数无返回值

你定义的 returnsCurrentOfferPrice 是异步函数,但内部仅执行了 await getCurrentOfferPrice(tokenId),却没有返回该调用的结果。异步函数默认会返回一个 resolved 为 undefined 的 Promise,这就是你在 then 回调里拿到 undefined 的直接原因。

解决步骤

1. 修复 returnsCurrentOfferPrice 的返回值

修改该函数,让它返回 getCurrentOfferPrice 的执行结果:

const returnsCurrentOfferPrice = async (tokenId) => {
    // 加上 return,将 getCurrentOfferPrice 的结果传递给上层调用
    return await getCurrentOfferPrice(tokenId)
}

2. 补充错误捕获逻辑(推荐)

当前 getCurrentOfferPrice 没有内部错误处理,一旦区块链调用失败(比如用户拒绝钱包连接、合约调用报错),错误会直接抛到外层。可以给它加上内部捕获,避免流程中断:

const getCurrentOfferPrice = async (tokenId) => {
    try {
        const web3Modal = new Web3Modal();
        const connection = await web3Modal.connect();
        const provider = new ethers.providers.Web3Provider(connection);
        const contract = signerOrProvider(provider);
        
        // 注意:如果合约返回的已经是 BigNumber,无需再用 ethers.BigNumber.from 转换
        const currentOfferPrice = await contract.getCurrentOfferAmount(tokenId);
        const currentOfferPriceInEther = ethers.utils.formatEther(currentOfferPrice);
        console.log('Current offer price', currentOfferPriceInEther );
        return currentOfferPriceInEther;
    } catch (err) {
        console.error('获取报价失败:', err);
        // 抛出错误让外层 catch 处理,或返回默认值(比如 null)
        throw err;
    }
}

3. 验证 signerOrProvider 函数的正确性

确保 signerOrProvider 正确返回合约实例:如果是只读调用,直接传入 provider 即可;如果需要用户授权的写操作,要获取 signer 传入。示例:

const signerOrProvider = (provider) => {
    // 只读场景用 provider,写操作场景用 signer
    const signer = provider.getSigner();
    return new ethers.Contract(CONTRACT_ADDRESS, CONTRACT_ABI, signer);
}

4. 处理钱包连接边界情况

如果用户未连接钱包,web3Modal.connect() 会触发授权弹窗,若用户拒绝会抛出错误。可以在调用前检查钱包连接状态,或在错误处理中提示用户完成连接。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 06:21:37