3

I am going to get the same value that is produced by keccak256 in solidity.

This is the code in my solidity file and I want to get the same value in the javascript file using ethers or web3.

bytes32 node = keccak256(abi.encodePacked(nodeString));

I got the same value of abi.encodePacked(nodeString)) by using ethers.utils.solidityPack.

const abiEncodedPackedString = ethers.utils.solidityPack(['string'], [nodeString]);

But when I tried ethers.utils.solidityKeccak256, the result wasn't the same as node in solidity.

const nodeInJavascript = ethers.utils.solidityKeccak256(['string], [abiEncodePackedString]);

I have also tried ethers.utils.keccak256(abiEncodePackedString) but I couldn't get the result either.

Bikas Lin
  • 133
  • 5
  • Does this https://ethereum.stackexchange.com/questions/30024/how-to-keccak256-multiple-types-in-web3js-to-match-solidity-keccak256 answer your question? – Ismael Mar 25 '22 at 15:09
  • Thanks, @Ismael for your kind comment. I have tried all methods mentioned in the question you linked, but I didn't find a proper method. – Bikas Lin Mar 26 '22 at 01:37

1 Answers1

5

There are two ways to achieve this from the documentation https://docs.ethers.io/v5/api/utils/hashing/.

  • ethers.utils.keccak256: It accepts a bytes like sequence so you have to convert the string to a byte sequence with ethers.utils.toUtf8Bytes

    ethers.utils.keccak256(ethers.utils.toUtf8Bytes("hola"))
    

    0x8aca9664752dbae36135fd0956c956fc4a370feeac67485b49bcd4b99608ae41

  • ethers.utils.id

    ethers.utils.id("hola")
    

    0x8aca9664752dbae36135fd0956c956fc4a370feeac67485b49bcd4b99608ae41

Ismael
  • 30,570
  • 21
  • 53
  • 96