String

keccak256 字元串比較失敗

  • February 13, 2019

嘗試將儲存中的字元串與傳遞給函式(記憶體)的字元串進行比較時,嘗試使用 keccak256() 轉換記憶體字元串時出現以下錯誤。我應該做些什麼不同的事情?

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.

您應該首先使用 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)));
   }
}

引用自:https://ethereum.stackexchange.com/questions/67052