I have created a message hash in JavaScript using:

let message = {
        'message': 'Receiver closing signature',
        'sender': sender,
        'balance': value

message = web3.utils.toHex(message);
let messageHash = web3.utils.sha3(message);

How should I define the equivalent object in solidity, and what function should I use to get the same message hash.

  • Do you have to convert to hex first? That sounds like the hard part to replicate in Solidity... – Shawn Tabrizi Oct 8 '18 at 5:00
  • Yes as sha3 parameter should be A string to hash. – Devraj Singh Rawat Oct 8 '18 at 6:45
  • Right, but you could do something like JSON.stringify(message) instead... – Shawn Tabrizi Oct 8 '18 at 10:16
  • Agree I can use JSON.stringify(message) ! How should we construct the same message at solidity side – Devraj Singh Rawat Oct 8 '18 at 10:30
  • So if in other words in below function, Need to construct mentioned sample message using the given input parameters. How should I do it? // Solidity function convertToString(address _address, uint256 _number, string message ) public { // Message = "{"message":"This is Sample message","address":"0xf32a7ecb5Cd6521165d7099112222223568a4FE","number":"11"}" } – Devraj Singh Rawat Oct 8 '18 at 10:54

My suggestion is to use the abi.encode method in solidity, and the equivalent web3.eth.abi.encodeParameters in web3.js.

Something like this:

Solidity Source

pragma solidity ^0.4.24;

contract test{

    struct mStruct {
        string message;
        address sender;
        uint balance;

    function testme() public pure returns(bytes32) {

        mStruct memory message = mStruct("Receiver closing signature", 0xCA35b7d915458EF540aDe6068dFe2F44E8fa733c, 100);
        return keccak256(abi.encode(message.message, message.sender, message.balance));



JavaScript Source

message = {
    'message': 'Receiver closing signature',
    'sender': '0xCA35b7d915458EF540aDe6068dFe2F44E8fa733c',
    'balance': 100

encoded = web3.eth.abi.encodeParameters(['string', 'address', 'uint'],[message.message, message.sender, message.balance])

hash = web3.utils.keccak256(encoded)



  • +1 that’s nice! I wasn’t aware of the abi object. – ivicaa Oct 8 '18 at 12:07
  • @Shawn Tabrizi .. you are awesome Bro... Liked the way u have moved the complexcity at web3 end from solidity .. . ++++1 – Devraj Singh Rawat Oct 8 '18 at 14:33

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.