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

调用secp256k1模块randomPrivateKey函数时遇TypeError错误求助

解决TypeError: Cannot read properties of undefined (reading 'randomPrivateKey')问题

你的报错原因是在ethereum-cryptography v2.1.3版本中,randomPrivateKey函数并不是挂载在secp.utils下的,而是作为secp256k1模块的顶级导出函数存在。

修改后的可运行代码如下:

const secp = require("ethereum-cryptography/secp256k1");
const { keccak256 } = require("ethereum-cryptography/keccak");
const { toHex } = require("ethereum-cryptography/utils")

// 修正:直接调用secp.randomPrivateKey()
const privateKey = secp.randomPrivateKey();
console.log('Private key:', toHex(privateKey));

const publicKey = secp.getPublicKey(privateKey);
console.log('Public key:', toHex(publicKey));

const address = keccak256(publicKey.slice(1)).slice(-20);
console.log('Ethereum address:', toHex(address));

额外修正:你代码最后一行的打印文案有误,应该是「Ethereum address」而非「Ethereum public key」,已帮你调整。

版本适配说明:v2.x系列的ethereum-cryptography/secp256k1模块,核心工具函数(如randomPrivateKey、getPublicKey)均为顶级导出,不存在utils子对象;若你之前参考的是v1.x版本的文档,会出现这种调用方式不匹配的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 05:14:59