1

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)" } 
GGizmos
  • 3,443
  • 4
  • 27
  • 72

1 Answers1

1

This should help you Solidity: How to represent bytes32 as string

The problem is that currently you are trying to convert your hash to a utf-8 string. The hash has values that aren't supported by utf-8. I think what you meant to do, was represent your hash as a string.

Jared
  • 11
  • 3
  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Oct 14 '21 at 23:29
  • Add more details to your anwer. by the way you hint is great. It hellped me – Sapthaka Oct 13 '22 at 08:42