Keccak256 – How to Use Ethers.js to Hash Data

ethers.jshashkeccaksignature

I tried to use ethers' keccak256 function like this:

import { keccak256 } from "@ethersproject/keccak256";

const signature = keccak256("balanceOf(address)");

But the script failed with this error:

Error: invalid arrayify value (argument="value", value="balanceOf(address)", code=INVALID_ARGUMENT, version=bytes/5.5.0)

How can I make it work?

Best Answer

Let's look at the function definition for keccak256:

export function keccak256(data: BytesLike): string {
    return '0x' + sha3.keccak_256(arrayify(data));
}

The input is not a string - it's a BytesLike type.

With that in mind, here's how to rewrite the script to make it work:

import { keccak256 } from "@ethersproject/keccak256";
import { toUtf8Bytes } from "@ethersproject/strings";

const signature = keccak256(toUtf8Bytes("balanceOf(address)"));

The trick is to import another package from the ethers stack (@ethersproject/strings) that exports a function called toUtf8Bytes, which converts your string to BytesLike.

Related Topic