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

HardHat中NFT部署、铸造及转账测试权限问题求助

解决HardHat中以指定账户执行ERC721转账的问题

核心问题定位

你之前用await token.connect(otherAccount.address)切换调用者是错误的——connect()方法需要传入Signer对象(即HardHat测试环境中ethers.getSigners()返回的账户实例),而非账户地址,这才导致msg.sender始终是部署者。

正确操作步骤

假设你已经成功将tokenId=1的NFT铸造给otherAccount,要将其转账至bridgeContract,按以下流程执行:

  1. 创建以otherAccount身份连接的合约实例
    提前生成连接后的合约对象,后续所有操作都用这个实例:

    const tokenAsOtherAccount = yourNFTContract.connect(otherAccount);
    
  2. 给bridge合约授权NFT操作权限
    用otherAccount身份授权bridge合约可以操作指定tokenId的NFT:

    await tokenAsOtherAccount.approve(bridgeContract.address, 1);
    

    或者如果需要批量授权,可使用setApprovalForAll:

    await tokenAsOtherAccount.setApprovalForAll(bridgeContract.address, true);
    
  3. 执行转账操作
    用otherAccount身份调用transferFrom完成转账:

    await tokenAsOtherAccount.transferFrom(
      otherAccount.address,
      bridgeContract.address,
      1
    );
    

    也可以用更安全的safeTransferFrom:

    await tokenAsOtherAccount.safeTransferFrom(
      otherAccount.address,
      bridgeContract.address,
      1
    );
    

验证与排查

  • 确认NFT归属:调用await yourNFTContract.ownerOf(1),返回值必须是otherAccount.address
  • 检查授权状态:调用await yourNFTContract.getApproved(1),返回值应为bridgeContract.address(单NFT授权),或用await yourNFTContract.isApprovedForAll(otherAccount.address, bridgeContract.address)验证批量授权
  • 避免测试上下文冲突:如果测试中使用了loadFixture或快照重置,确保授权和转账在同一个测试块中执行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 03:32:38