Keccak256 – Troubleshooting String Comparison Failures

keccakstring

When trying to compare a string from storage to a string being passed into a function (memory), I am getting the following error when attempting to convert the memory string using keccak256(). What am I supposed to be doing differently?

TypeError: Invalid type for argument in function call. Invalid implicit conversion from string memory to bytes memory requested. This function requires a single bytes argument. Use abi.encodePacked(...) to obtain the pre-0.5.0 behaviour or abi.encode(...) to use ABI encoding.

Best Answer

You should first convert the strings to bytes using abi.encode():

pragma solidity 0.5.4;

contract Test {
    string public constant text = "Hello world!";

    function isEqualTo(string memory myString) public pure returns(bool) {
        return (keccak256(abi.encode(text)) == keccak256(abi.encode(myString)));
    }
}
Related Topic