[Ethereum] How to generate keccak256(STRING,INTEGER) from Javascript

keccaksha3soliditytruffle

In my solidity code I use bytes32 generated by
keccak256("STRING_VALUE',INTEGER)
to store values in the map.

One of the sample values that get generated is

0x728021dd1e605706a029ef0f0a96028fab0d170608cbfcc8b28ff7786d985dcf

Now I want to generate this hash in my JS code, I have tried using libraries like js-sha3, keccak, solidity-sha3. None of them take Integer as a parameter and also they return hash that is irrelevant to what is generated above.

How do I generate similar hash in the JS?

Best Answer

Simple convert your integer into base 16, and append to original string finally calculate hash. It will be same.

function solSha3 (...args) {
    args = args.map(arg => {
        if (typeof arg === 'string') {
            if (arg.substring(0, 2) === '0x') {
                return arg.slice(2)
            } else {
                return web3.toHex(arg).slice(2)
            }
        }

        if (typeof arg === 'number') {
            return leftPad((arg).toString(16), 64, 0)
        } else {
          return ''
        }
    })

    args = args.join('')

    return '0x' + web3.sha3(args, { encoding: 'hex' })
}

For more details refer Github link

Related Topic