
本文旨在解决hardhat项目中常见的`typeerror: cannot read properties of undefined (reading 'parseunits')`错误。该问题通常源于`ethers.js`库在v5和v6版本之间对工具函数api的重大变更。我们将详细解释这一变化,提供正确的`ethers v6`语法,并指导开发者如何检查和适配`ethers.js`版本,确保智能合约测试和交互的顺畅进行。
在Hardhat开发中,我们经常需要将人类可读的以太币数量(如"1 ether")转换为EVM所需的最小单位(wei)。ethers.js库提供了parseUnits和parseEther等实用函数来完成这项任务。然而,当开发者在测试或脚本中尝试使用如下代码时,可能会遇到TypeError: Cannot read properties of undefined (reading 'parseUnits')的错误:
const { deployments, ethers, getNamedAccounts } = require("hardhat");
const { assert, expect } = require("chai");
describe("FundMe", async function () {
let fundMe;
let deployer;
// 错误示例:在ethers v6环境中尝试使用v5语法
const sendValue = ethers.utils.parseUnits("1", "ether");
// 或者
// const sendValue = ethers.utils.parseEther("1");
});这个错误明确指出ethers.utils对象上没有parseUnits属性,这通常不是因为拼写错误,而是因为ethers.js库的版本发生了变化。
ethers.js是一个核心的以太坊JavaScript库,广泛用于Hardhat项目。在ethers.js的v5版本中,许多实用工具函数,如parseUnits、formatUnits、keccak256等,都被封装在ethers.utils命名空间下。因此,使用ethers.utils.parseUnits()是正确的。
然而,从ethers.js的v6版本开始,为了简化API和提高模块化程度,许多常用的工具函数被提升到了ethers对象的顶层。这意味着ethers.utils命名空间下的许多函数,包括parseUnits和parseEther,都直接成为了ethers对象的属性。
因此,当你的Hardhat项目依赖于ethers.js v6版本,但你的代码仍然沿用ethers v5的ethers.utils.parseUnits语法时,就会出现上述的TypeError。
解决这个问题的关键是更新你的代码以匹配ethers v6的API。只需将对ethers.utils.parseUnits或ethers.utils.parseEther的调用更改为直接调用ethers.parseUnits或ethers.parseEther即可。
以下是修正后的代码示例:
const { deployments, ethers, getNamedAccounts } = require("hardhat");
const { assert, expect } = require("chai");
describe("FundMe", async function () {
let fundMe;
let deployer;
// 正确的ethers v6语法
const sendValue = ethers.parseUnits("1", "ether");
// 或者,对于以太币单位,更简洁的写法
// const sendValue = ethers.parseEther("1");
});为了避免此类版本兼容性问题,了解你的项目当前使用的ethers.js版本至关重要。你可以通过以下方式进行检查:
package.json文件: 在你的项目根目录下的package.json文件中,查找dependencies或devDependencies部分,通常会看到ethers的依赖项及其版本号:
{
"name": "your-hardhat-project",
"version": "1.0.0",
"devDependencies": {
"hardhat": "^2.x.x",
"@nomicfoundation/hardhat-ethers": "^3.x.x", // 这个包通常会拉取ethers v6
"ethers": "^6.x.x" // 直接声明的ethers版本
}
}请注意,Hardhat本身或其插件(如@nomicfoundation/hardhat-ethers)可能会隐式地依赖特定版本的ethers.js。@nomicfoundation/hardhat-ethers v3及以上版本通常会引入ethers v6。
npm list ethers或yarn why ethers: 在项目终端中运行以下命令,可以查看ethers库的实际安装版本:
npm list ethers # 或者 yarn why ethers
这将显示项目中所有ethers依赖的树状结构和版本信息。
TypeError: Cannot read properties of undefined (reading 'parseUnits')错误是ethers.js从v5到v6版本API变更的一个典型表现。通过将ethers.utils.parseUnits或ethers.utils.parseEther更新为ethers.parseUnits或ethers.parseEther,并确保你的代码与项目实际使用的ethers.js版本保持一致,可以轻松解决这一问题。在日常开发中,养成检查依赖版本和查阅对应版本文档的习惯,将大大提高开发效率并减少不必要的调试时间。
以上就是Hardhat开发中ethers.parseUnits的正确使用姿势及版本迁移的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号