I would like to build a simple JavaScript (JS) front end that checks if a field submitted is the pre-image of a keccak256 hash I already know in my smart contract. I currently use the following:

Front end JS:

    <script src="https://cdn.jsdelivr.net/gh/emn178/js-sha3/build/sha3.min.js"></script>
    <script>keccak_ = keccak_256;</script>
    <script lang="javascript">
                    var preimage = $("input#preimage").val();
                    var hash_ = keccack_(newNumber);
                    var hash__ = '0x'+ hash_;
                    var params = {from:web3.eth.accounts[0]}
                    contractInstance.checkPreimage(hash__, params, function(error, result){...


function checkPreimage(uint256 incoming) public {
 if (uint256(keccak256(abi.encodePacked(known_preimage))) == incoming){
 do_something(); }}
 // known_preimage is of type uint 256 as well

I can't seem to pass the if condition. I'm certain all other parts of the code work.

  • 1
    What is known_preimage (type and value)? Apr 18 '20 at 17:48
  • I'm also looking for this. I need the first 4 byte of that hash to validate the contract and not sure how to proceed in the front end. Using NodeJS and ethers Dec 10 '20 at 0:50

You should use web3's soliditySha3 utility function.

In your case, since there is only one parameter to be hashed:

// 234 is your preimage
const hash = web3.utils.soliditySha3(new BN('234'));

If you wish to hash more than one parameters:

  • In solidity
uint256 hash = uint256(keccak256(abi.encodePacked(known_preimage1, known_preimage_2)));
  • In javascript
const hash = web3.utils.soliditySha3(
    {t: 'uint256', v: new BN('234')},
    {t: 'address', v: '0x407D73d8a49eeb85D32Cf465507dd71d507100c1'},

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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