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

HardHat+ethers.js部署Token合约时地址返回undefined求助

问题:部署Token合约无法获取地址,返回undefined

使用HardHat和ethers.js部署智能合约时,Lock合约能正常获取部署地址,但Token合约地址返回undefined。

部署代码

const { ethers } = require("hardhat");
const hre = require("hardhat");

async function main() {
  const currentTimestampInSeconds = Math.round(Date.now() / 1000);
  const unlockTime = currentTimestampInSeconds + 60;

  const lockedAmount = hre.ethers.parseEther("0.001");

  const lock = await hre.ethers.deployContract("Lock", [unlockTime], {
    value: lockedAmount,
  });

  const Token = await hre.ethers.getContractFactory("Token");
  const token = await Token.deploy();

  await token.deploymentTransaction().wait(1);
  console.log(`Token Deployed to: ${token.value}`);

  console.log(
    `Lock with ${ethers.formatEther(
      lockedAmount
    )}ETH and unlock timestamp ${unlockTime} deployed to ${lock.target}`
  );
}

main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});

运行输出

Token Deployed to: undefined
Lock with 0.001ETH and unlock timestamp 1697469516 deployed to 0x9E545E3C0baAB3E08CdfD552C960A1050f373042
Done in 3.80s.

原因分析

  1. 属性使用错误:你用token.value获取Token合约地址,但value并不是ethers.js v6中合约实例的属性,正确的地址属性是target——这也是Lock合约能正常获取地址的原因,它用了lock.target。
  2. 等待部署的方法不规范:token.deploymentTransaction().wait(1)虽能等待交易确认,但ethers.js v6官方推荐用waitForDeployment()方法等待合约部署完成,该方法更简洁且符合规范。

解决方法

修改Token合约部署相关代码,使用正确的地址属性和等待方法:

修正后的完整代码

const { ethers } = require("hardhat");
const hre = require("hardhat");

async function main() {
  const currentTimestampInSeconds = Math.round(Date.now() / 1000);
  const unlockTime = currentTimestampInSeconds + 60;

  const lockedAmount = hre.ethers.parseEther("0.001");

  // 部署Lock合约并等待完成
  const lock = await hre.ethers.deployContract("Lock", [unlockTime], {
    value: lockedAmount,
  });
  await lock.waitForDeployment();

  // 部署Token合约并等待完成
  const Token = await hre.ethers.getContractFactory("Token");
  const token = await Token.deploy();
  await token.waitForDeployment();

  // 使用target属性获取Token合约地址
  console.log(`Token Deployed to: ${token.target}`);

  console.log(
    `Lock with ${ethers.formatEther(lockedAmount)}ETH and unlock timestamp ${unlockTime} deployed to ${lock.target}`
  );
}

main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});

运行修正后的代码,即可正常输出Token合约的部署地址。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 10:05:55