Hardhat部署Solidity合约报错:deployed不是函数,Goerli地址返回undefined
问题背景
刚学习Solidity,跟着YouTube教程开发首个应用,使用Hardhat部署合约时遇到两个问题:
- 执行部署脚本报错:
TypeError: transactions.deployed is not a function
at main (D:\one-more-try(8.16)\smart-contract\scripts\deploy.js:5:22)
at processTicksAndRejections (node:internal/process/task_queues:95:5)
at runMain (D:\one-more-try(8.16)\smart-contract\scripts\deploy.js:12:5)
- 部署到Goerli测试网后,合约地址输出为
undefined:
#npx hardhat run --network goerli scripts/deploy.js
Transactions address: undefined
用户提供代码
部署脚本 deploy.js
const main = async () => { const Transactions = await hre.ethers.getContractFactory("Transactions"); const transactions = await Transactions.deploy(); await transactions.deployed(); console.log("Transactions address: ", transactions.address); }; const runMain = async () => { try { await main(); process.exit(0); } catch (error) { console.error(error); process.exit(1); } }; runMain();
Solidity合约代码
pragma solidity ^0.8.0; contract Transactions { uint256 transactionCounter; event Transfer(address from, address receiver, uint amount, string message, uint256 timestamp, string keyword); struct TransferStruct{ address sender; address receiver; uint amount; string message; uint256 timestamp; string keyword; } TransferStruct[] transactions; function addToBlockchain(address payable receiver, uint amount, string memory message, string memory keyword) public{ transactionCounter += 1; transactions.push(TransferStruct(msg.sender, receiver, amount, message, block.timestamp, keyword)); emit Transfer(msg.sender, receiver, amount, message, block.timestamp, keyword); } function getAllTransactions() public view returns (TransferStruct[] memory){ return transactions; } function getTransactionCounter() public view returns(uint256){ return transactionCounter; } }
问题原因与解决方案
1. transactions.deployed is not a function 报错
原因:ethers.js版本差异导致。教程大概率基于ethers v5,但你当前项目使用的是ethers v6——v6中deploy()方法直接返回已部署的合约实例,deployed()方法已被移除。
解决方法:删除部署脚本中的await transactions.deployed();语句,同时调整地址获取方式:
const main = async () => { const Transactions = await hre.ethers.getContractFactory("Transactions"); const transactions = await Transactions.deploy(); // 移除这一行:await transactions.deployed(); console.log("Transactions address: ", transactions.target); // ethers v6用target替代address }; const runMain = async () => { try { await main(); process.exit(0); } catch (error) { console.error(error); process.exit(1); } }; runMain();
2. 合约地址显示undefined
原因:同样是ethers版本差异。ethers v6中合约实例的地址属性从address更改为target,继续使用transactions.address会返回undefined。
解决方法:将脚本中的transactions.address替换为transactions.target,如上修改后的代码所示。
额外验证步骤
- 检查
package.json中的依赖版本:确认@nomicfoundation/hardhat-toolbox或ethers为v6.x,若为v5.x则需检查网络配置是否正确。 - Goerli测试网配置验证:确保
hardhat.config.js中包含有效的RPC URL和测试钱包私钥:
module.exports = { solidity: "0.8.0", networks: { goerli: { url: "你的Goerli RPC URL", accounts: ["你的测试钱包私钥"] } } };
内容的提问来源于stack exchange,提问作者Anastasia

