I have following contract:

pragma solidity ^0.4.0;

contract Lottery {
  address public owner;
  bytes32 public hash;

  function Lottery() {        
    owner = msg.sender;
    hash = sha3(owner);

  function get() constant returns (address, bytes32) {
    return (owner, hash);

Which returns:

    "0": "address: 0xca35b7d915458ef540ade6068dfe2f44e8fa733c",
    "1": "bytes32: 0xb1591967aed668a4b27645ff40c444892d91bf5951b382995d4d4f6ee3a2ce03"

I want to obtain same bytes32 hash on the nodejs by providing same inputs as "address: 0xca35b7d915458ef540ade6068dfe2f44e8fa733c".

The javascript code I have:

module.exports = require('js-sha3');

Web3 = require("web3");
web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));

    console.log("not connected");

var owner = "0xca35b7d915458ef540ade6068dfe2f44e8fa733c"; //given input on the smart-contract.


Which prints:


That is not the same output I got on the solidity.

[Q] What should I do to get the same output using sha3 by providing same address as input on nodejs?

Thank you for your valuable time and help.


You need to parse the address first. Right now, you're computing the hash of the string representation of the address. Try this:

> web3.utils.sha3(new Buffer('0xca35b7d915458ef540ade6068dfe2f44e8fa733c'.substr(2), 'hex'))

(Note the .substr(2) to chop off the "0x" at the beginning of the address.)


Another option:

> web3.utils.sha3(web3.utils.hexToBytes('0xca35b7d915458ef540ade6068dfe2f44e8fa733c'))


The above was with web3.js 1.0.0-beta.x. For web3.js 0.x.x (I tested with 0.14.0):

> web3.sha3('0xca35b7d915458ef540ade6068dfe2f44e8fa733c', { encoding: 'hex' })
| improve this answer | |
  • It says: web3.utils.sha3, Cannot read property 'sha3' of undefined when I just do web3.sha3it just returns "0000000000000000000000000000000000000000000000000000000000000000" @smarx – alper Dec 26 '17 at 14:42
  • What version of web3 are you using? – user19510 Dec 26 '17 at 14:43
  • How can I learn its version? I just did npm install web3 hoping it will install its latest version. @smarx – alper Dec 26 '17 at 14:46
  • I just added code for version 0.x.x to my answer, since I suspect that's what you're using. – user19510 Dec 26 '17 at 14:47
  • 1
    Solidity's keccak256/sha3 concatenates its arguments. 10 will be considered a bytes8, so it will be padded to that size. Prepend your hex string with 0a: web3.sha3('0a' + 'ca35b7d915458ef540ade6068dfe2f44e8fa733c', { encoding: 'hex' }) (and be careful to remove the intervening "0x"). – user19510 Dec 26 '17 at 15:04

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.