3

I have a method which returns bytes type data from an external contract call. I need to convert that bytes type data into my desired output type data like address/uint/bool/string/int etc. I have tried finding conversion library but couldn't find any. Note if I convert the bytes as a string like this string(returnData) the address type data got converted into something I'm unable to decode it. the same thing happens for another data type as well.

function getData(string memory _key) public returns (string memory _stringData, address _addressData, uint _uintData, bytes memory _bytesData, bool _boolData) {

    Delegate _delegate = Delegate(MAN.getLatestDelegateContract()); // this is my own internal machanism, skip thi please 
    // Retrieve method name according to data type
    string memory _methodName = _delegate.getDataType(_key);
    // Prepare input call
    bytes memory _input = abi.encodePacked(bytes4(keccak256(abi.encodePacked("get",_methodName,"(bytes32)"))),keccak256(abi.encodePacked(_key)));
    // Make the call
    (bool success, bytes memory ret) = address(deployedEternalStorages).call(_input);
        // from the call data returned as bytes

        if (success) {
        // Return data as desired type
        if(keccak256(abi.encodePacked(_methodName)) == keccak256("address")){
            //convert bytes to address and assign into below variable
            //_addressData = 
        }
        else if(keccak256(abi.encodePacked(_methodName)) == keccak256("uint")){
            //convert bytes to uint and assig into below variable
            //_uintData = 
        }
        else if(keccak256(abi.encodePacked(_methodName)) == keccak256("bytes")){
            _bytesData = ret;
        }
        else if(keccak256(abi.encodePacked(_methodName)) == keccak256("bool")){
            //convert bytes to bool and assig into below variable
            //_boolData = 
        }
        else{
            _stringData = string(ret);
        }
    } else {
        // Call failed revert
        revert();
    }
}

Can anybody help with any conversion library or any other way to convert the data types. Note: I'm using 0.5.0 version in my code.

2 Answers 2

0

https://solidity.readthedocs.io/en/v0.5.2/types.html?highlight=bytes#dynamically-sized-byte-array

Bytes is a not a value type according to the docs, and is actually a dynamically-sized array.

This library can convert uint to Bytes32 and vice-versa, if that helps any.

1
  • Thanks for the documentation link, but that library doesn't work. Anyway, an alternative solution for this. Commented Feb 5, 2019 at 5:36
0

what you are looking is BytesLib.sol https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.