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.

2

1 Answer 1

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

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.