I am trying to create mapping of type mapping(string => string)
where the you store some text by keyed by its the string representation of its hash, but I've been stymied by the inability to take the calculated hash value and convert it to its string representation.
I tried the below, but it doesn't work. The hashing function appears to work, but the conversion to string doesn't. (Running function hash()
returns an error which I don't really understand.
pragma solidity 0.8.4;
contract HashTextMap {
mapping(string=>string) textMap;
function set(string memory text) public {
bytes32 val;
val = sha256(abi.encodePacked(text));
string memory key = string(abi.encodePacked(val));
textMap[key] = text;
}
function get(string memory key) public view returns(string memory) {
return textMap[key];
}
function hash(string memory text) public pure returns(string memory) {
bytes32 val;
val = sha256(abi.encodePacked(text));
string memory key = string(abi.encodePacked(val));
return key;
}
}
Running this in the remix ide, the contract compiles and sets returns normally, but attempting I can't text get because I can't get the hash using hash() which produces this error.
{ "error": "Failed to decode output: null: invalid codepoint at offset 0; unexpected continuation byte (argument=\"bytes\", value={\"0\":153,\"1\":168,\"2\":124,\"3\":145,\"4\":53,\"5\":23,\"6\":70,\"7\":37,\"8\":43,\"9\":238,\"10\":126,\"11\":38,\"12\":250,\"13\":191,\"14\":48,\"15\":2,\"16\":61,\"17\":234,\"18\":227,\"19\":36,\"20\":138,\"21\":6,\"22\":125,\"23\":166,\"24\":226,\"25\":63,\"26\":146,\"27\":129,\"28\":199,\"29\":135,\"30\":194,\"31\":139}, code=INVALID_ARGUMENT, version=strings/5.4.0)" }