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

如何解决ethers.js中TypeError: Cannot read 'toHexString' of undefined错误?

解决ethers.js私钥加密时的TypeError: Cannot read properties of undefined (reading 'toHexString')错误

问题根源

  1. dotenv未正确加载环境变量
    代码中require("dotenv").config缺少调用括号,导致.env文件中的变量没有注入到process.env,process.env.PRIVATE_KEY和process.env.PRIVATE_KEY_PASSWORD均为undefined,这是触发错误的核心原因。

  2. wallet.encrypt参数冗余
    ethers.Wallet实例的encrypt方法仅需传入加密密码即可,实例已持有初始化时传入的私钥,无需重复传入。传入undefined的私钥会触发内部校验报错。

修复后的代码

const ethers = require("ethers");
const fs = require("fs-extra");
require("dotenv").config(); // 修复:添加函数调用括号

async function main() {
  // 新增环境变量校验,提前排查配置问题
  if (!process.env.PRIVATE_KEY) {
    throw new Error("请在.env文件中配置PRIVATE_KEY");
  }
  if (!process.env.PRIVATE_KEY_PASSWORD) {
    throw new Error("请在.env文件中配置PRIVATE_KEY_PASSWORD");
  }

  const wallet = new ethers.Wallet(process.env.PRIVATE_KEY);
  // 修复:仅传入加密密码参数
  const encryptedJsonkey = await wallet.encrypt(process.env.PRIVATE_KEY_PASSWORD);
  console.log(encryptedJsonkey);

  // 可选:将加密结果写入文件持久化存储
  await fs.writeFile("./encrypted-wallet.json", encryptedJsonkey);
}

main()
  .then(() => process.exit(0))
  .catch((error) => {
    console.error(error);
    process.exit(1);
  });

额外注意事项

  • 确保你的.env文件格式正确:
    PRIVATE_KEY=你的以太坊私钥字符串
    PRIVATE_KEY_PASSWORD=自定义的加密密码
    
  • 运行前确认依赖已安装:npm install ethers fs-extra dotenv

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 20:22:33