【问题标题】:TypeError: Cannot read properties of undefined (reading 'bufferToHex') - MetamaskTypeError:无法读取未定义的属性(读取“bufferToHex”)-元掩码
【发布时间】:2022-06-14 05:52:58
【问题描述】:

我正在尝试使用 Metamask RPC API (here) 中的方法加密消息。我首先使用“eth_getEncryptionPublicKey”来获取我连接到的帐户的加密密钥。然后我使用以下代码加密我的消息。但是,我收到以下错误,我不明白如何解决它。请问有人可以建议吗?

我不知道这是否与我的错误有关,但“@metamask/eth-sig-util”是用 TypeScript 编写的。

import ethUtil from 'ethereumjs-util';
import sigUtil from '@metamask/eth-sig-util';

const encryptString = (encryptionKey, text) => {
console.log('encryptString.encryptionKey: ' + encryptionKey);
console.log('encryptString.text: ' + text);

const encryptedMessage = ethUtil.bufferToHex(
  Buffer.from(
    JSON.stringify(
      sigUtil.encrypt({
        publicKey: encryptionKey,
        data: text,
        version: 'x25519-xsalsa20-poly1305',
      })
    ),
    'utf-8'
  )
);

};

控制台:

encryptString.publicKey: Rb1/QuAkQ7qpyo9wzY5+E0Kw2AkL1Vipb8LObOGkkNw=
encryptString.text: Hello World

错误:

Uncaught TypeError: Cannot read properties of undefined (reading 'bufferToHex')

【问题讨论】:

    标签: javascript metamask


    【解决方案1】:

    我遇到了同样的错误,使用这些导入对我有用:

    import { bufferToHex } from 'ethereumjs-util';
    import { encrypt } from '@metamask/eth-sig-util';
    

    适合您的情况的完整代码:

    import { bufferToHex } from 'ethereumjs-util';
    import { encrypt } from '@metamask/eth-sig-util';
    
    const encryptedMessage = bufferToHex(
        Buffer.from(
            JSON.stringify(
                encrypt({
                    publicKey: encryptionKey,
                    data: 'hello world!',
                    version: 'x25519-xsalsa20-poly1305',
                }),
            ),
            'utf8',
        ),
    );
    
    console.log(`Encrypted message: ${encryptedMessage}`);
    
    const decryptedMessage = await window as.ethereum.request({
        method: 'eth_decrypt',
        params: [encryptedMessage, account],
    });
    
    console.log(`Decrypted message: ${decryptedMessage}`);
    

    【讨论】:

      猜你喜欢
      • 2021-11-26
      • 2021-11-24
      • 2021-12-20
      • 2021-11-27
      • 2022-01-21
      • 2021-12-04
      • 2021-12-09
      • 2021-12-06
      • 2022-01-13
      相关资源
      最近更新 更多