生成以太坊加密密钥时遇Uncaught TypeError错误,如何修复?
修复
Uncaught TypeError: Cannot read properties of undefined (reading 'utils')错误 这个错误的核心原因是你导入的secp对象中不存在utils属性——ethereum-cryptography库的模块化设计里,randomPrivateKey这类工具方法被拆分到了单独的子模块,而非挂载在默认导出的secp对象上。
修复步骤:
- 新增
randomPrivateKey的单独导入语句,从ethereum-cryptography/secp256k1/utils模块导入该函数 - 直接调用导入的
randomPrivateKey(),替换原来的secp.utils.randomPrivateKey() - 额外修复组件内的显示问题:原代码中直接渲染
privateKey、publicKey会显示Uint8Array对象,需要用toHex转换为十六进制字符串才能正常显示
修复后的完整代码:
import secp from "ethereum-cryptography/secp256k1"; import { keccak256 } from "ethereum-cryptography/keccak"; import { toHex } from "ethereum-cryptography/utils"; import { randomPrivateKey } from "ethereum-cryptography/secp256k1/utils"; const privateKey = 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)); function GenerateKey() { return ( <div> <p>Private key: {toHex(privateKey)}</p> <p>Public key: {toHex(publicKey)}</p> <p>Address: {toHex(address)}</p> </div> ) } export default GenerateKey;
内容的提问来源于stack exchange,提问作者Miracle Andrew
相关产品推荐
相关产品推荐

