I want to create a hash in JavaScript for a signature. The hash needs to have the same output as this in solidity:
keccak256(abi.encodePacked(address, bytes32))
My solution in JavaScript so far produces a differing hash:
const types = ["address", "bytes32"];
const values = [myAddress, hash];
const message = ethers.utils.defaultAbiCoder.encode(types, values);
const hash = ethers.utils.keccak256(message);
How can I reproduce the code in Solidity in JavaScript?
abi.encodeinstead. For reference: https://ethereum.stackexchange.com/questions/119583/when-to-use-abi-encode-abi-encodepacked-or-abi-encodewithsignature-in-solidity – Markus Schick Jan 25 '23 at 23:31encodePacked()is the correct function as 'packed' means that when the variable is smaller than 32 bytes it will be used as its true size is, if it is not packed, then it will be aligned on 32 bytes with prepended 0s and computed – Nulik Jan 26 '23 at 00:43abi.encodePackedis used bydefaultAbiCoder? You should really only useabi.encodePackedif you know what you are doing, as it can lead to hash collisions when used with dynamic types (see: discussion). The functionabi.encodeis available in Solidity – Markus Schick Jan 26 '23 at 09:33