2

In my solidity code, I am doing a lot of stuff like this:

keccak256(abi.encodePacked("abc", "def"))

And then returning the value in an event, which is picked up in dapp.

Now, since the dapp is originally suppling the values (such as "abc" in this example), it would help if I can independently calculate the value in dapp layer itself, without needing to rely on the return value in the contract event.

Does someone know if this can be done ?

3 Answers 3

3

Yes, you can use:

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

const result = keccak256(stuff to encode);

There is also an ethers.js variant, something like:

ethers.utils.solidityKeccak256(value) 

Read the ethers documentation for additional info.

2

Yes, you can do that. You can use the same keccak256 function and abi.encodePacked method in your dapp code to calculate the value and then compare it with the value returned in the contract event. You can use a JavaScript library like ethers.js that provides the necessary utility functions for encoding and hashing data in Ethereum.

Here's an example of how you can calculate the value in JavaScript:

const ethers = require('ethers');

const packed = ethers.utils.solidityPack(["string", "string"], ["abc", "def"]);
const hash = ethers.utils.keccak256(packed);
1
  • thanks for the ethere.js version
    – Somjit
    Commented Feb 8, 2023 at 9:11
0

The answers are all really helpful, and show how to do with different libraries.

With the general idea now being in place, using web3js, I could do it as such:

web3.utils.soliditySha3("abc", "def")

soliditySha3 combines both the packing and hashing aspects together into one function, which I found quite neat!

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.