'@metamask/eth-sig-util" buffer isn't defined?

I'm trying to encrypt some data using MetaMask's public key for encryption (https://docs.metamask.io/guide/rpc-api.html#unrestricted-methods). However, on page load I'm getting the error Buffer is not defined:

image

It seems to only happen when I've imported the '@metamask/eth-sig-util' script and try to encrypt data:

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

const encryptedData = ethUtil.bufferToHex(
  Buffer.from(
    JSON.stringify(
      sigUtil.encrypt({
        publicKey: publicKey,
        data: 'hello world data',
        version: 'x25519-xsalsa20-poly1305',
      })
    ),
    'utf8'
  )
)

I've tried adding in import { Buffer } from 'buffer/', but this doesn't seem to help.

If I omit import sigUtil from '@metamask/eth-sig-util' or

const encryptedData = ethUtil.bufferToHex(
  Buffer.from(
    JSON.stringify(
      sigUtil.encrypt({
        publicKey: publicKey,
        data: 'hello world data',
        version: 'x25519-xsalsa20-poly1305',
      })
    ),
    'utf8'
  )
)

The error goes away. I've also tried switching to using [email protected] instead of the newer @metamask/eth-sig-util, but the error still persists.

Since I've tried all of the above including using a different package version, I'm starting to wonder if this isn't a bug within the @metamask/eth-sig-util library. What is causing this issue? I'm using Vite to build my project and I've tested on both Chrome and FireFox, but the error still persists. What should I check?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source