Ethers v6中formatBytes32String无法使用,求排查问题
问题:使用ethers库转换字符串为bytes32时运行报错
我编写了如下Node.js代码,尝试用ethers的formatBytes32String方法转换字符串:
const ethers = require('ethers'); async function createBytes(args) { const name = args[0]; const bytes = ethers.utils.formatBytes32String(name); console.log('name: ', bytes) } createBytes(process.argv.slice(2));
通过PowerShell运行该文件时出现错误,不清楚问题出在哪?
问题原因及解决方案
核心问题:ethers版本不兼容
你大概率安装的是ethers v6及以上版本,这个版本对API结构做了大幅调整——移除了ethers.utils对象,原utils下的方法被直接提升到了ethers根命名空间下。原代码里调用ethers.utils.formatBytes32String自然会报“utils未定义”的错误。
修正方案
方案1:适配ethers v6+(推荐)
直接修改方法调用路径,同时建议增加参数校验避免未传参时的异常:
const ethers = require('ethers'); function createBytes(args) { const name = args[0]; if (!name) { console.error('请传入需要转换的字符串参数'); return; } const bytes = ethers.formatBytes32String(name); console.log('转换结果: ', bytes) } createBytes(process.argv.slice(2));
方案2:降级到ethers v5及以下版本
如果你不想修改代码,可以卸载当前版本,安装v5版本:
npm uninstall ethers npm install ethers@5
安装完成后原代码即可正常运行。
内容的提问来源于stack exchange,提问作者hp0514
相关产品推荐
相关产品推荐

